keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
2D
mitenjain/nanopore
submodules/samtools-0.1.19/sam_header.h
.h
1,597
49
#ifndef __SAM_HEADER_H__ #define __SAM_HEADER_H__ #ifdef __cplusplus extern "C" { #endif void *sam_header_parse2(const char *headerText); void *sam_header_merge(int n, const void **dicts); void sam_header_free(void *header); char *sam_header_write(const void *headerDict); // returns a newly allocated string /* // Usage example const char *key, *val; void *iter = sam_header_parse2(bam->header->text); while ( iter = sam_header_key_val(iter, "RG","ID","SM" &key,&val) ) printf("%s\t%s\n", key,val); */ void *sam_header2key_val(void *iter, const char type[2], const char key_tag[2], const char value_tag[2], const char **key, const char **value); char **sam_header2list(const void *_dict, char type[2], char key_tag[2], int *_n); /* // Usage example int i, j, n; const char *tags[] = {"SN","LN","UR","M5",NULL}; void *dict = sam_header_parse2(bam->header->text); char **tbl = sam_header2tbl_n(h->dict, "SQ", tags, &n); for (i=0; i<n; i++) { for (j=0; j<4; j++) if ( tbl[4*i+j] ) printf("\t%s", tbl[4*i+j]); else printf("-"); printf("\n"); } if (tbl) free(tbl); */ char **sam_header2tbl_n(const void *dict, const char type[2], const char *tags[], int *n); void *sam_header2tbl(const void *dict, char type[2], char key_tag[2], char value_tag[2]); const char *sam_tbl_get(void *h, const char *key); int sam_tbl_size(void *h); void sam_tbl_destroy(void *h); #ifdef __cplusplus } #endif #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_color.c
.c
3,333
146
#include <ctype.h> #include "bam.h" /*! @abstract Get the color encoding the previous and current base @param b pointer to an alignment @param i The i-th position, 0-based @return color @discussion Returns 0 no color information is found. */ char bam_aux_getCSi(bam1_t *b, int i) { uint8_t *c = bam_aux_get(b, "CS"); char *cs = NULL; // return the base if the tag was not found if(0 == c) return 0; cs = bam_aux2Z(c); // adjust for strandedness and leading adaptor if(bam1_strand(b)) { i = strlen(cs) - 1 - i; // adjust for leading hard clip uint32_t cigar = bam1_cigar(b)[0]; if((cigar & BAM_CIGAR_MASK) == BAM_CHARD_CLIP) { i -= cigar >> BAM_CIGAR_SHIFT; } } else { i++; } return cs[i]; } /*! @abstract Get the color quality of the color encoding the previous and current base @param b pointer to an alignment @param i The i-th position, 0-based @return color quality @discussion Returns 0 no color information is found. */ char bam_aux_getCQi(bam1_t *b, int i) { uint8_t *c = bam_aux_get(b, "CQ"); char *cq = NULL; // return the base if the tag was not found if(0 == c) return 0; cq = bam_aux2Z(c); // adjust for strandedness if(bam1_strand(b)) { i = strlen(cq) - 1 - i; // adjust for leading hard clip uint32_t cigar = bam1_cigar(b)[0]; if((cigar & BAM_CIGAR_MASK) == BAM_CHARD_CLIP) { i -= (cigar >> BAM_CIGAR_SHIFT); } } return cq[i]; } char bam_aux_nt2int(char a) { switch(toupper(a)) { case 'A': return 0; break; case 'C': return 1; break; case 'G': return 2; break; case 'T': return 3; break; default: return 4; break; } } char bam_aux_ntnt2cs(char a, char b) { a = bam_aux_nt2int(a); b = bam_aux_nt2int(b); if(4 == a || 4 == b) return '4'; return "0123"[(int)(a ^ b)]; } /*! @abstract Get the color error profile at the give position @param b pointer to an alignment @return the original color if the color was an error, '-' (dash) otherwise @discussion Returns 0 no color information is found. */ char bam_aux_getCEi(bam1_t *b, int i) { int cs_i; uint8_t *c = bam_aux_get(b, "CS"); char *cs = NULL; char prev_b, cur_b; char cur_color, cor_color; // return the base if the tag was not found if(0 == c) return 0; cs = bam_aux2Z(c); // adjust for strandedness and leading adaptor if(bam1_strand(b)) { //reverse strand cs_i = strlen(cs) - 1 - i; // adjust for leading hard clip uint32_t cigar = bam1_cigar(b)[0]; if((cigar & BAM_CIGAR_MASK) == BAM_CHARD_CLIP) { cs_i -= cigar >> BAM_CIGAR_SHIFT; } // get current color cur_color = cs[cs_i]; // get previous base. Note: must rc adaptor prev_b = (cs_i == 1) ? "TGCAN"[(int)bam_aux_nt2int(cs[0])] : bam_nt16_rev_table[bam1_seqi(bam1_seq(b), i+1)]; // get current base cur_b = bam_nt16_rev_table[bam1_seqi(bam1_seq(b), i)]; } else { cs_i=i+1; // get current color cur_color = cs[cs_i]; // get previous base prev_b = (0 == i) ? cs[0] : bam_nt16_rev_table[bam1_seqi(bam1_seq(b), i-1)]; // get current base cur_b = bam_nt16_rev_table[bam1_seqi(bam1_seq(b), i)]; } // corrected color cor_color = bam_aux_ntnt2cs(prev_b, cur_b); if(cur_color == cor_color) { return '-'; } else { return cur_color; } }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/sam_view.c
.c
14,887
442
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <math.h> #include <inttypes.h> #include "sam_header.h" #include "sam.h" #include "faidx.h" #include "kstring.h" #include "khash.h" KHASH_SET_INIT_STR(rg) // When counting records instead of printing them, // data passed to the bam_fetch callback is encapsulated in this struct. typedef struct { bam_header_t *header; int64_t *count; // int does overflow for very big BAMs } count_func_data_t; typedef khash_t(rg) *rghash_t; // FIXME: we'd better use no global variables... static rghash_t g_rghash = 0; static int g_min_mapQ = 0, g_flag_on = 0, g_flag_off = 0, g_qual_scale = 0, g_min_qlen = 0; static uint32_t g_subsam_seed = 0; static double g_subsam_frac = -1.; static char *g_library, *g_rg; static void *g_bed; void *bed_read(const char *fn); void bed_destroy(void *_h); int bed_overlap(const void *_h, const char *chr, int beg, int end); static int process_aln(const bam_header_t *h, bam1_t *b) { if (g_qual_scale > 1) { int i; uint8_t *qual = bam1_qual(b); for (i = 0; i < b->core.l_qseq; ++i) { int c = qual[i] * g_qual_scale; qual[i] = c < 93? c : 93; } } if (g_min_qlen > 0) { int k, qlen = 0; uint32_t *cigar = bam1_cigar(b); for (k = 0; k < b->core.n_cigar; ++k) if ((bam_cigar_type(bam_cigar_op(cigar[k]))&1) || bam_cigar_op(cigar[k]) == BAM_CHARD_CLIP) qlen += bam_cigar_oplen(cigar[k]); if (qlen < g_min_qlen) return 1; } if (b->core.qual < g_min_mapQ || ((b->core.flag & g_flag_on) != g_flag_on) || (b->core.flag & g_flag_off)) return 1; if (g_bed && b->core.tid >= 0 && !bed_overlap(g_bed, h->target_name[b->core.tid], b->core.pos, bam_calend(&b->core, bam1_cigar(b)))) return 1; if (g_subsam_frac > 0.) { uint32_t k = __ac_X31_hash_string(bam1_qname(b)) + g_subsam_seed; if ((double)(k&0xffffff) / 0x1000000 >= g_subsam_frac) return 1; } if (g_rg || g_rghash) { uint8_t *s = bam_aux_get(b, "RG"); if (s) { if (g_rg) return (strcmp(g_rg, (char*)(s + 1)) == 0)? 0 : 1; if (g_rghash) { khint_t k = kh_get(rg, g_rghash, (char*)(s + 1)); return (k != kh_end(g_rghash))? 0 : 1; } } } if (g_library) { const char *p = bam_get_library((bam_header_t*)h, b); return (p && strcmp(p, g_library) == 0)? 0 : 1; } return 0; } static char *drop_rg(char *hdtxt, rghash_t h, int *len) { char *p = hdtxt, *q, *r, *s; kstring_t str; memset(&str, 0, sizeof(kstring_t)); while (1) { int toprint = 0; q = strchr(p, '\n'); if (q == 0) q = p + strlen(p); if (q - p < 3) break; // the line is too short; then stop if (strncmp(p, "@RG\t", 4) == 0) { int c; khint_t k; if ((r = strstr(p, "\tID:")) != 0) { r += 4; for (s = r; *s != '\0' && *s != '\n' && *s != '\t'; ++s); c = *s; *s = '\0'; k = kh_get(rg, h, r); *s = c; if (k != kh_end(h)) toprint = 1; } } else toprint = 1; if (toprint) { kputsn(p, q - p, &str); kputc('\n', &str); } p = q + 1; } *len = str.l; return str.s; } // callback function for bam_fetch() that prints nonskipped records static int view_func(const bam1_t *b, void *data) { if (!process_aln(((samfile_t*)data)->header, (bam1_t*)b)) samwrite((samfile_t*)data, b); return 0; } // callback function for bam_fetch() that counts nonskipped records static int count_func(const bam1_t *b, void *data) { if (!process_aln(((count_func_data_t*)data)->header, (bam1_t*)b)) { (*((count_func_data_t*)data)->count)++; } return 0; } static int usage(int is_long_help); int main_samview(int argc, char *argv[]) { int c, is_header = 0, is_header_only = 0, is_bamin = 1, ret = 0, compress_level = -1, is_bamout = 0, is_count = 0; int of_type = BAM_OFDEC, is_long_help = 0, n_threads = 0; int64_t count = 0; samfile_t *in = 0, *out = 0; char in_mode[5], out_mode[5], *fn_out = 0, *fn_list = 0, *fn_ref = 0, *fn_rg = 0, *q; /* parse command-line options */ strcpy(in_mode, "r"); strcpy(out_mode, "w"); while ((c = getopt(argc, argv, "SbBct:h1Ho:q:f:F:ul:r:xX?T:R:L:s:Q:@:m:")) >= 0) { switch (c) { case 's': if ((g_subsam_seed = strtol(optarg, &q, 10)) != 0) { srand(g_subsam_seed); g_subsam_seed = rand(); } g_subsam_frac = strtod(q, &q); break; case 'm': g_min_qlen = atoi(optarg); break; case 'c': is_count = 1; break; case 'S': is_bamin = 0; break; case 'b': is_bamout = 1; break; case 't': fn_list = strdup(optarg); is_bamin = 0; break; case 'h': is_header = 1; break; case 'H': is_header_only = 1; break; case 'o': fn_out = strdup(optarg); break; case 'f': g_flag_on = strtol(optarg, 0, 0); break; case 'F': g_flag_off = strtol(optarg, 0, 0); break; case 'q': g_min_mapQ = atoi(optarg); break; case 'u': compress_level = 0; break; case '1': compress_level = 1; break; case 'l': g_library = strdup(optarg); break; case 'L': g_bed = bed_read(optarg); break; case 'r': g_rg = strdup(optarg); break; case 'R': fn_rg = strdup(optarg); break; case 'x': of_type = BAM_OFHEX; break; case 'X': of_type = BAM_OFSTR; break; case '?': is_long_help = 1; break; case 'T': fn_ref = strdup(optarg); is_bamin = 0; break; case 'B': bam_no_B = 1; break; case 'Q': g_qual_scale = atoi(optarg); break; case '@': n_threads = strtol(optarg, 0, 0); break; default: return usage(is_long_help); } } if (compress_level >= 0) is_bamout = 1; if (is_header_only) is_header = 1; if (is_bamout) strcat(out_mode, "b"); else { if (of_type == BAM_OFHEX) strcat(out_mode, "x"); else if (of_type == BAM_OFSTR) strcat(out_mode, "X"); } if (is_bamin) strcat(in_mode, "b"); if (is_header) strcat(out_mode, "h"); if (compress_level >= 0) { char tmp[2]; tmp[0] = compress_level + '0'; tmp[1] = '\0'; strcat(out_mode, tmp); } if (argc == optind) return usage(is_long_help); // potential memory leak... // read the list of read groups if (fn_rg) { FILE *fp_rg; char buf[1024]; int ret; g_rghash = kh_init(rg); fp_rg = fopen(fn_rg, "r"); while (!feof(fp_rg) && fscanf(fp_rg, "%s", buf) > 0) // this is not a good style, but bear me... kh_put(rg, g_rghash, strdup(buf), &ret); // we'd better check duplicates... fclose(fp_rg); } // generate the fn_list if necessary if (fn_list == 0 && fn_ref) fn_list = samfaipath(fn_ref); // open file handlers if ((in = samopen(argv[optind], in_mode, fn_list)) == 0) { fprintf(stderr, "[main_samview] fail to open \"%s\" for reading.\n", argv[optind]); ret = 1; goto view_end; } if (in->header == 0) { fprintf(stderr, "[main_samview] fail to read the header from \"%s\".\n", argv[optind]); ret = 1; goto view_end; } if (g_rghash) { // FIXME: I do not know what "bam_header_t::n_text" is for... char *tmp; int l; tmp = drop_rg(in->header->text, g_rghash, &l); free(in->header->text); in->header->text = tmp; in->header->l_text = l; } if (!is_count && (out = samopen(fn_out? fn_out : "-", out_mode, in->header)) == 0) { fprintf(stderr, "[main_samview] fail to open \"%s\" for writing.\n", fn_out? fn_out : "standard output"); ret = 1; goto view_end; } if (n_threads > 1) samthreads(out, n_threads, 256); if (is_header_only) goto view_end; // no need to print alignments if (argc == optind + 1) { // convert/print the entire file bam1_t *b = bam_init1(); int r; while ((r = samread(in, b)) >= 0) { // read one alignment from `in' if (!process_aln(in->header, b)) { if (!is_count) samwrite(out, b); // write the alignment to `out' count++; } } if (r < -1) { fprintf(stderr, "[main_samview] truncated file.\n"); ret = 1; } bam_destroy1(b); } else { // retrieve alignments in specified regions int i; bam_index_t *idx = 0; if (is_bamin) idx = bam_index_load(argv[optind]); // load BAM index if (idx == 0) { // index is unavailable fprintf(stderr, "[main_samview] random alignment retrieval only works for indexed BAM files.\n"); ret = 1; goto view_end; } for (i = optind + 1; i < argc; ++i) { int tid, beg, end, result; bam_parse_region(in->header, argv[i], &tid, &beg, &end); // parse a region in the format like `chr2:100-200' if (tid < 0) { // reference name is not found fprintf(stderr, "[main_samview] region \"%s\" specifies an unknown reference name. Continue anyway.\n", argv[i]); continue; } // fetch alignments if (is_count) { count_func_data_t count_data = { in->header, &count }; result = bam_fetch(in->x.bam, idx, tid, beg, end, &count_data, count_func); } else result = bam_fetch(in->x.bam, idx, tid, beg, end, out, view_func); if (result < 0) { fprintf(stderr, "[main_samview] retrieval of region \"%s\" failed due to truncated file or corrupt BAM index file\n", argv[i]); ret = 1; break; } } bam_index_destroy(idx); // destroy the BAM index } view_end: if (is_count && ret == 0) printf("%" PRId64 "\n", count); // close files, free and return free(fn_list); free(fn_ref); free(fn_out); free(g_library); free(g_rg); free(fn_rg); if (g_bed) bed_destroy(g_bed); if (g_rghash) { khint_t k; for (k = 0; k < kh_end(g_rghash); ++k) if (kh_exist(g_rghash, k)) free((char*)kh_key(g_rghash, k)); kh_destroy(rg, g_rghash); } samclose(in); if (!is_count) samclose(out); return ret; } static int usage(int is_long_help) { fprintf(stderr, "\n"); fprintf(stderr, "Usage: samtools view [options] <in.bam>|<in.sam> [region1 [...]]\n\n"); fprintf(stderr, "Options: -b output BAM\n"); fprintf(stderr, " -h print header for the SAM output\n"); fprintf(stderr, " -H print header only (no alignments)\n"); fprintf(stderr, " -S input is SAM\n"); fprintf(stderr, " -u uncompressed BAM output (force -b)\n"); fprintf(stderr, " -1 fast compression (force -b)\n"); fprintf(stderr, " -x output FLAG in HEX (samtools-C specific)\n"); fprintf(stderr, " -X output FLAG in string (samtools-C specific)\n"); fprintf(stderr, " -c print only the count of matching records\n"); fprintf(stderr, " -B collapse the backward CIGAR operation\n"); fprintf(stderr, " -@ INT number of BAM compression threads [0]\n"); fprintf(stderr, " -L FILE output alignments overlapping the input BED FILE [null]\n"); fprintf(stderr, " -t FILE list of reference names and lengths (force -S) [null]\n"); fprintf(stderr, " -T FILE reference sequence file (force -S) [null]\n"); fprintf(stderr, " -o FILE output file name [stdout]\n"); fprintf(stderr, " -R FILE list of read groups to be outputted [null]\n"); fprintf(stderr, " -f INT required flag, 0 for unset [0]\n"); fprintf(stderr, " -F INT filtering flag, 0 for unset [0]\n"); fprintf(stderr, " -q INT minimum mapping quality [0]\n"); fprintf(stderr, " -l STR only output reads in library STR [null]\n"); fprintf(stderr, " -r STR only output reads in read group STR [null]\n"); fprintf(stderr, " -s FLOAT fraction of templates to subsample; integer part as seed [-1]\n"); fprintf(stderr, " -? longer help\n"); fprintf(stderr, "\n"); if (is_long_help) fprintf(stderr, "Notes:\n\ \n\ 1. By default, this command assumes the file on the command line is in\n\ the BAM format and it prints the alignments in SAM. If `-t' is\n\ applied, the input file is assumed to be in the SAM format. The\n\ file supplied with `-t' is SPACE/TAB delimited with the first two\n\ fields of each line consisting of the reference name and the\n\ corresponding sequence length. The `.fai' file generated by `faidx'\n\ can be used here. This file may be empty if reads are unaligned.\n\ \n\ 2. SAM->BAM conversion: `samtools view -bT ref.fa in.sam.gz'.\n\ \n\ 3. BAM->SAM conversion: `samtools view in.bam'.\n\ \n\ 4. A region should be presented in one of the following formats:\n\ `chr1', `chr2:1,000' and `chr3:1000-2,000'. When a region is\n\ specified, the input alignment file must be an indexed BAM file.\n\ \n\ 5. Option `-u' is preferred over `-b' when the output is piped to\n\ another samtools command.\n\ \n\ 6. In a string FLAG, each character represents one bit with\n\ p=0x1 (paired), P=0x2 (properly paired), u=0x4 (unmapped),\n\ U=0x8 (mate unmapped), r=0x10 (reverse), R=0x20 (mate reverse)\n\ 1=0x40 (first), 2=0x80 (second), s=0x100 (not primary), \n\ f=0x200 (failure) and d=0x400 (duplicate). Note that `-x' and\n\ `-X' are samtools-C specific. Picard and older samtools do not\n\ support HEX or string flags.\n\ \n"); return 1; } int main_import(int argc, char *argv[]) { int argc2, ret; char **argv2; if (argc != 4) { fprintf(stderr, "Usage: bamtk import <in.ref_list> <in.sam> <out.bam>\n"); return 1; } argc2 = 6; argv2 = calloc(6, sizeof(char*)); argv2[0] = "import", argv2[1] = "-o", argv2[2] = argv[3], argv2[3] = "-bt", argv2[4] = argv[1], argv2[5] = argv[2]; ret = main_samview(argc2, argv2); free(argv2); return ret; } int8_t seq_comp_table[16] = { 0, 8, 4, 12, 2, 10, 9, 14, 1, 6, 5, 13, 3, 11, 7, 15 }; int main_bam2fq(int argc, char *argv[]) { bamFile fp; bam_header_t *h; bam1_t *b; int8_t *buf; int max_buf, c, no12 = 0; while ((c = getopt(argc, argv, "n")) > 0) if (c == 'n') no12 = 1; if (argc == 1) { fprintf(stderr, "Usage: samtools bam2fq <in.bam>\n"); return 1; } fp = strcmp(argv[optind], "-")? bam_open(argv[optind], "r") : bam_dopen(fileno(stdin), "r"); if (fp == 0) return 1; h = bam_header_read(fp); b = bam_init1(); buf = 0; max_buf = 0; while (bam_read1(fp, b) >= 0) { int i, qlen = b->core.l_qseq; uint8_t *seq; putchar('@'); fputs(bam1_qname(b), stdout); if (no12) putchar('\n'); else { if ((b->core.flag & 0x40) && !(b->core.flag & 0x80)) puts("/1"); else if ((b->core.flag & 0x80) && !(b->core.flag & 0x40)) puts("/2"); else putchar('\n'); } if (max_buf < qlen + 1) { max_buf = qlen + 1; kroundup32(max_buf); buf = realloc(buf, max_buf); } buf[qlen] = 0; seq = bam1_seq(b); for (i = 0; i < qlen; ++i) buf[i] = bam1_seqi(seq, i); if (b->core.flag & 16) { // reverse complement for (i = 0; i < qlen>>1; ++i) { int8_t t = seq_comp_table[buf[qlen - 1 - i]]; buf[qlen - 1 - i] = seq_comp_table[buf[i]]; buf[i] = t; } if (qlen&1) buf[i] = seq_comp_table[buf[i]]; } for (i = 0; i < qlen; ++i) buf[i] = bam_nt16_rev_table[buf[i]]; puts((char*)buf); puts("+"); seq = bam1_qual(b); for (i = 0; i < qlen; ++i) buf[i] = 33 + seq[i]; if (b->core.flag & 16) { // reverse for (i = 0; i < qlen>>1; ++i) { int8_t t = buf[qlen - 1 - i]; buf[qlen - 1 - i] = buf[i]; buf[i] = t; } } puts((char*)buf); } free(buf); bam_destroy1(b); bam_header_destroy(h); bam_close(fp); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_stat.c
.c
3,202
78
#include <unistd.h> #include <assert.h> #include "bam.h" typedef struct { long long n_reads[2], n_mapped[2], n_pair_all[2], n_pair_map[2], n_pair_good[2]; long long n_sgltn[2], n_read1[2], n_read2[2]; long long n_dup[2]; long long n_diffchr[2], n_diffhigh[2]; } bam_flagstat_t; #define flagstat_loop(s, c) do { \ int w = ((c)->flag & BAM_FQCFAIL)? 1 : 0; \ ++(s)->n_reads[w]; \ if ((c)->flag & BAM_FPAIRED) { \ ++(s)->n_pair_all[w]; \ if ((c)->flag & BAM_FPROPER_PAIR) ++(s)->n_pair_good[w]; \ if ((c)->flag & BAM_FREAD1) ++(s)->n_read1[w]; \ if ((c)->flag & BAM_FREAD2) ++(s)->n_read2[w]; \ if (((c)->flag & BAM_FMUNMAP) && !((c)->flag & BAM_FUNMAP)) ++(s)->n_sgltn[w]; \ if (!((c)->flag & BAM_FUNMAP) && !((c)->flag & BAM_FMUNMAP)) { \ ++(s)->n_pair_map[w]; \ if ((c)->mtid != (c)->tid) { \ ++(s)->n_diffchr[w]; \ if ((c)->qual >= 5) ++(s)->n_diffhigh[w]; \ } \ } \ } \ if (!((c)->flag & BAM_FUNMAP)) ++(s)->n_mapped[w]; \ if ((c)->flag & BAM_FDUP) ++(s)->n_dup[w]; \ } while (0) bam_flagstat_t *bam_flagstat_core(bamFile fp) { bam_flagstat_t *s; bam1_t *b; bam1_core_t *c; int ret; s = (bam_flagstat_t*)calloc(1, sizeof(bam_flagstat_t)); b = bam_init1(); c = &b->core; while ((ret = bam_read1(fp, b)) >= 0) flagstat_loop(s, c); bam_destroy1(b); if (ret != -1) fprintf(stderr, "[bam_flagstat_core] Truncated file? Continue anyway.\n"); return s; } int bam_flagstat(int argc, char *argv[]) { bamFile fp; bam_header_t *header; bam_flagstat_t *s; if (argc == optind) { fprintf(stderr, "Usage: samtools flagstat <in.bam>\n"); return 1; } fp = strcmp(argv[optind], "-")? bam_open(argv[optind], "r") : bam_dopen(fileno(stdin), "r"); assert(fp); header = bam_header_read(fp); s = bam_flagstat_core(fp); printf("%lld + %lld in total (QC-passed reads + QC-failed reads)\n", s->n_reads[0], s->n_reads[1]); printf("%lld + %lld duplicates\n", s->n_dup[0], s->n_dup[1]); printf("%lld + %lld mapped (%.2f%%:%.2f%%)\n", s->n_mapped[0], s->n_mapped[1], (float)s->n_mapped[0] / s->n_reads[0] * 100.0, (float)s->n_mapped[1] / s->n_reads[1] * 100.0); printf("%lld + %lld paired in sequencing\n", s->n_pair_all[0], s->n_pair_all[1]); printf("%lld + %lld read1\n", s->n_read1[0], s->n_read1[1]); printf("%lld + %lld read2\n", s->n_read2[0], s->n_read2[1]); printf("%lld + %lld properly paired (%.2f%%:%.2f%%)\n", s->n_pair_good[0], s->n_pair_good[1], (float)s->n_pair_good[0] / s->n_pair_all[0] * 100.0, (float)s->n_pair_good[1] / s->n_pair_all[1] * 100.0); printf("%lld + %lld with itself and mate mapped\n", s->n_pair_map[0], s->n_pair_map[1]); printf("%lld + %lld singletons (%.2f%%:%.2f%%)\n", s->n_sgltn[0], s->n_sgltn[1], (float)s->n_sgltn[0] / s->n_pair_all[0] * 100.0, (float)s->n_sgltn[1] / s->n_pair_all[1] * 100.0); printf("%lld + %lld with mate mapped to a different chr\n", s->n_diffchr[0], s->n_diffchr[1]); printf("%lld + %lld with mate mapped to a different chr (mapQ>=5)\n", s->n_diffhigh[0], s->n_diffhigh[1]); free(s); bam_header_destroy(header); bam_close(fp); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_aux.c
.c
5,085
218
#include <ctype.h> #include "bam.h" #include "khash.h" typedef char *str_p; KHASH_MAP_INIT_STR(s, int) KHASH_MAP_INIT_STR(r2l, str_p) void bam_aux_append(bam1_t *b, const char tag[2], char type, int len, uint8_t *data) { int ori_len = b->data_len; b->data_len += 3 + len; b->l_aux += 3 + len; if (b->m_data < b->data_len) { b->m_data = b->data_len; kroundup32(b->m_data); b->data = (uint8_t*)realloc(b->data, b->m_data); } b->data[ori_len] = tag[0]; b->data[ori_len + 1] = tag[1]; b->data[ori_len + 2] = type; memcpy(b->data + ori_len + 3, data, len); } uint8_t *bam_aux_get_core(bam1_t *b, const char tag[2]) { return bam_aux_get(b, tag); } #define __skip_tag(s) do { \ int type = toupper(*(s)); \ ++(s); \ if (type == 'Z' || type == 'H') { while (*(s)) ++(s); ++(s); } \ else if (type == 'B') (s) += 5 + bam_aux_type2size(*(s)) * (*(int32_t*)((s)+1)); \ else (s) += bam_aux_type2size(type); \ } while(0) uint8_t *bam_aux_get(const bam1_t *b, const char tag[2]) { uint8_t *s; int y = tag[0]<<8 | tag[1]; s = bam1_aux(b); while (s < b->data + b->data_len) { int x = (int)s[0]<<8 | s[1]; s += 2; if (x == y) return s; __skip_tag(s); } return 0; } // s MUST BE returned by bam_aux_get() int bam_aux_del(bam1_t *b, uint8_t *s) { uint8_t *p, *aux; aux = bam1_aux(b); p = s - 2; __skip_tag(s); memmove(p, s, b->l_aux - (s - aux)); b->data_len -= s - p; b->l_aux -= s - p; return 0; } int bam_aux_drop_other(bam1_t *b, uint8_t *s) { if (s) { uint8_t *p, *aux; aux = bam1_aux(b); p = s - 2; __skip_tag(s); memmove(aux, p, s - p); b->data_len -= b->l_aux - (s - p); b->l_aux = s - p; } else { b->data_len -= b->l_aux; b->l_aux = 0; } return 0; } void bam_init_header_hash(bam_header_t *header) { if (header->hash == 0) { int ret, i; khiter_t iter; khash_t(s) *h; header->hash = h = kh_init(s); for (i = 0; i < header->n_targets; ++i) { iter = kh_put(s, h, header->target_name[i], &ret); kh_value(h, iter) = i; } } } void bam_destroy_header_hash(bam_header_t *header) { if (header->hash) kh_destroy(s, (khash_t(s)*)header->hash); } int32_t bam_get_tid(const bam_header_t *header, const char *seq_name) { khint_t k; khash_t(s) *h = (khash_t(s)*)header->hash; k = kh_get(s, h, seq_name); return k == kh_end(h)? -1 : kh_value(h, k); } int bam_parse_region(bam_header_t *header, const char *str, int *ref_id, int *beg, int *end) { char *s; int i, l, k, name_end; khiter_t iter; khash_t(s) *h; bam_init_header_hash(header); h = (khash_t(s)*)header->hash; *ref_id = *beg = *end = -1; name_end = l = strlen(str); s = (char*)malloc(l+1); // remove space for (i = k = 0; i < l; ++i) if (!isspace(str[i])) s[k++] = str[i]; s[k] = 0; l = k; // determine the sequence name for (i = l - 1; i >= 0; --i) if (s[i] == ':') break; // look for colon from the end if (i >= 0) name_end = i; if (name_end < l) { // check if this is really the end int n_hyphen = 0; for (i = name_end + 1; i < l; ++i) { if (s[i] == '-') ++n_hyphen; else if (!isdigit(s[i]) && s[i] != ',') break; } if (i < l || n_hyphen > 1) name_end = l; // malformated region string; then take str as the name s[name_end] = 0; iter = kh_get(s, h, s); if (iter == kh_end(h)) { // cannot find the sequence name iter = kh_get(s, h, str); // try str as the name if (iter == kh_end(h)) { if (bam_verbose >= 2) fprintf(stderr, "[%s] fail to determine the sequence name.\n", __func__); free(s); return -1; } else s[name_end] = ':', name_end = l; } } else iter = kh_get(s, h, str); if (iter == kh_end(h)) { free(s); return -1; } *ref_id = kh_val(h, iter); // parse the interval if (name_end < l) { for (i = k = name_end + 1; i < l; ++i) if (s[i] != ',') s[k++] = s[i]; s[k] = 0; *beg = atoi(s + name_end + 1); for (i = name_end + 1; i != k; ++i) if (s[i] == '-') break; *end = i < k? atoi(s + i + 1) : 1<<29; if (*beg > 0) --*beg; } else *beg = 0, *end = 1<<29; free(s); return *beg <= *end? 0 : -1; } int32_t bam_aux2i(const uint8_t *s) { int type; if (s == 0) return 0; type = *s++; if (type == 'c') return (int32_t)*(int8_t*)s; else if (type == 'C') return (int32_t)*(uint8_t*)s; else if (type == 's') return (int32_t)*(int16_t*)s; else if (type == 'S') return (int32_t)*(uint16_t*)s; else if (type == 'i' || type == 'I') return *(int32_t*)s; else return 0; } float bam_aux2f(const uint8_t *s) { int type; type = *s++; if (s == 0) return 0.0; if (type == 'f') return *(float*)s; else return 0.0; } double bam_aux2d(const uint8_t *s) { int type; type = *s++; if (s == 0) return 0.0; if (type == 'd') return *(double*)s; else return 0.0; } char bam_aux2A(const uint8_t *s) { int type; type = *s++; if (s == 0) return 0; if (type == 'A') return *(char*)s; else return 0; } char *bam_aux2Z(const uint8_t *s) { int type; type = *s++; if (s == 0) return 0; if (type == 'Z' || type == 'H') return (char*)s; else return 0; } #ifdef _WIN32 double drand48() { return (double)rand() / RAND_MAX; } #endif
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bedcov.c
.c
3,143
128
#include <zlib.h> #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "kstring.h" #include "bgzf.h" #include "bam.h" #include "kseq.h" KSTREAM_INIT(gzFile, gzread, 16384) typedef struct { bamFile fp; bam_iter_t iter; int min_mapQ; } aux_t; static int read_bam(void *data, bam1_t *b) { aux_t *aux = (aux_t*)data; int ret = bam_iter_read(aux->fp, aux->iter, b); if ((int)b->core.qual < aux->min_mapQ) b->core.flag |= BAM_FUNMAP; return ret; } int main_bedcov(int argc, char *argv[]) { extern void bam_init_header_hash(bam_header_t*); gzFile fp; kstring_t str; kstream_t *ks; bam_index_t **idx; bam_header_t *h = 0; aux_t **aux; int *n_plp, dret, i, n, c, min_mapQ = 0; int64_t *cnt; const bam_pileup1_t **plp; while ((c = getopt(argc, argv, "Q:")) >= 0) { switch (c) { case 'Q': min_mapQ = atoi(optarg); break; } } if (optind + 2 > argc) { fprintf(stderr, "Usage: samtools bedcov <in.bed> <in1.bam> [...]\n"); return 1; } memset(&str, 0, sizeof(kstring_t)); n = argc - optind - 1; aux = calloc(n, sizeof(void*)); idx = calloc(n, sizeof(void*)); for (i = 0; i < n; ++i) { aux[i] = calloc(1, sizeof(aux_t)); aux[i]->min_mapQ = min_mapQ; aux[i]->fp = bam_open(argv[i+optind+1], "r"); idx[i] = bam_index_load(argv[i+optind+1]); if (aux[i]->fp == 0 || idx[i] == 0) { fprintf(stderr, "ERROR: fail to open index BAM file '%s'\n", argv[i+optind+1]); return 2; } bgzf_set_cache_size(aux[i]->fp, 20); if (i == 0) h = bam_header_read(aux[0]->fp); } bam_init_header_hash(h); cnt = calloc(n, 8); fp = gzopen(argv[optind], "rb"); ks = ks_init(fp); n_plp = calloc(n, sizeof(int)); plp = calloc(n, sizeof(void*)); while (ks_getuntil(ks, KS_SEP_LINE, &str, &dret) >= 0) { char *p, *q; int tid, beg, end, pos; bam_mplp_t mplp; for (p = q = str.s; *p && *p != '\t'; ++p); if (*p != '\t') goto bed_error; *p = 0; tid = bam_get_tid(h, q); *p = '\t'; if (tid < 0) goto bed_error; for (q = p = p + 1; isdigit(*p); ++p); if (*p != '\t') goto bed_error; *p = 0; beg = atoi(q); *p = '\t'; for (q = p = p + 1; isdigit(*p); ++p); if (*p == '\t' || *p == 0) { int c = *p; *p = 0; end = atoi(q); *p = c; } else goto bed_error; for (i = 0; i < n; ++i) { if (aux[i]->iter) bam_iter_destroy(aux[i]->iter); aux[i]->iter = bam_iter_query(idx[i], tid, beg, end); } mplp = bam_mplp_init(n, read_bam, (void**)aux); bam_mplp_set_maxcnt(mplp, 64000); memset(cnt, 0, 8 * n); while (bam_mplp_auto(mplp, &tid, &pos, n_plp, plp) > 0) if (pos >= beg && pos < end) for (i = 0; i < n; ++i) cnt[i] += n_plp[i]; for (i = 0; i < n; ++i) { kputc('\t', &str); kputl(cnt[i], &str); } puts(str.s); bam_mplp_destroy(mplp); continue; bed_error: fprintf(stderr, "Errors in BED line '%s'\n", str.s); } free(n_plp); free(plp); ks_destroy(ks); gzclose(fp); free(cnt); for (i = 0; i < n; ++i) { if (aux[i]->iter) bam_iter_destroy(aux[i]->iter); bam_index_destroy(idx[i]); bam_close(aux[i]->fp); free(aux[i]); } bam_header_destroy(h); free(aux); free(idx); free(str.s); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/ksort.h
.h
10,125
286
/* The MIT License Copyright (c) 2008 Genome Research Ltd (GRL). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Contact: Heng Li <lh3@sanger.ac.uk> */ /* 2012-12-11 (0.1.4): * Defined __ks_insertsort_##name as static to compile with C99. 2008-11-16 (0.1.4): * Fixed a bug in introsort() that happens in rare cases. 2008-11-05 (0.1.3): * Fixed a bug in introsort() for complex comparisons. * Fixed a bug in mergesort(). The previous version is not stable. 2008-09-15 (0.1.2): * Accelerated introsort. On my Mac (not on another Linux machine), my implementation is as fast as std::sort on random input. * Added combsort and in introsort, switch to combsort if the recursion is too deep. 2008-09-13 (0.1.1): * Added k-small algorithm 2008-09-05 (0.1.0): * Initial version */ #ifndef AC_KSORT_H #define AC_KSORT_H #include <stdlib.h> #include <string.h> typedef struct { void *left, *right; int depth; } ks_isort_stack_t; #define KSORT_SWAP(type_t, a, b) { register type_t t=(a); (a)=(b); (b)=t; } #define KSORT_INIT(name, type_t, __sort_lt) \ void ks_mergesort_##name(size_t n, type_t array[], type_t temp[]) \ { \ type_t *a2[2], *a, *b; \ int curr, shift; \ \ a2[0] = array; \ a2[1] = temp? temp : (type_t*)malloc(sizeof(type_t) * n); \ for (curr = 0, shift = 0; (1ul<<shift) < n; ++shift) { \ a = a2[curr]; b = a2[1-curr]; \ if (shift == 0) { \ type_t *p = b, *i, *eb = a + n; \ for (i = a; i < eb; i += 2) { \ if (i == eb - 1) *p++ = *i; \ else { \ if (__sort_lt(*(i+1), *i)) { \ *p++ = *(i+1); *p++ = *i; \ } else { \ *p++ = *i; *p++ = *(i+1); \ } \ } \ } \ } else { \ size_t i, step = 1ul<<shift; \ for (i = 0; i < n; i += step<<1) { \ type_t *p, *j, *k, *ea, *eb; \ if (n < i + step) { \ ea = a + n; eb = a; \ } else { \ ea = a + i + step; \ eb = a + (n < i + (step<<1)? n : i + (step<<1)); \ } \ j = a + i; k = a + i + step; p = b + i; \ while (j < ea && k < eb) { \ if (__sort_lt(*k, *j)) *p++ = *k++; \ else *p++ = *j++; \ } \ while (j < ea) *p++ = *j++; \ while (k < eb) *p++ = *k++; \ } \ } \ curr = 1 - curr; \ } \ if (curr == 1) { \ type_t *p = a2[0], *i = a2[1], *eb = array + n; \ for (; p < eb; ++i) *p++ = *i; \ } \ if (temp == 0) free(a2[1]); \ } \ void ks_heapadjust_##name(size_t i, size_t n, type_t l[]) \ { \ size_t k = i; \ type_t tmp = l[i]; \ while ((k = (k << 1) + 1) < n) { \ if (k != n - 1 && __sort_lt(l[k], l[k+1])) ++k; \ if (__sort_lt(l[k], tmp)) break; \ l[i] = l[k]; i = k; \ } \ l[i] = tmp; \ } \ void ks_heapmake_##name(size_t lsize, type_t l[]) \ { \ size_t i; \ for (i = (lsize >> 1) - 1; i != (size_t)(-1); --i) \ ks_heapadjust_##name(i, lsize, l); \ } \ void ks_heapsort_##name(size_t lsize, type_t l[]) \ { \ size_t i; \ for (i = lsize - 1; i > 0; --i) { \ type_t tmp; \ tmp = *l; *l = l[i]; l[i] = tmp; ks_heapadjust_##name(0, i, l); \ } \ } \ static inline void __ks_insertsort_##name(type_t *s, type_t *t) \ { \ type_t *i, *j, swap_tmp; \ for (i = s + 1; i < t; ++i) \ for (j = i; j > s && __sort_lt(*j, *(j-1)); --j) { \ swap_tmp = *j; *j = *(j-1); *(j-1) = swap_tmp; \ } \ } \ void ks_combsort_##name(size_t n, type_t a[]) \ { \ const double shrink_factor = 1.2473309501039786540366528676643; \ int do_swap; \ size_t gap = n; \ type_t tmp, *i, *j; \ do { \ if (gap > 2) { \ gap = (size_t)(gap / shrink_factor); \ if (gap == 9 || gap == 10) gap = 11; \ } \ do_swap = 0; \ for (i = a; i < a + n - gap; ++i) { \ j = i + gap; \ if (__sort_lt(*j, *i)) { \ tmp = *i; *i = *j; *j = tmp; \ do_swap = 1; \ } \ } \ } while (do_swap || gap > 2); \ if (gap != 1) __ks_insertsort_##name(a, a + n); \ } \ void ks_introsort_##name(size_t n, type_t a[]) \ { \ int d; \ ks_isort_stack_t *top, *stack; \ type_t rp, swap_tmp; \ type_t *s, *t, *i, *j, *k; \ \ if (n < 1) return; \ else if (n == 2) { \ if (__sort_lt(a[1], a[0])) { swap_tmp = a[0]; a[0] = a[1]; a[1] = swap_tmp; } \ return; \ } \ for (d = 2; 1ul<<d < n; ++d); \ stack = (ks_isort_stack_t*)malloc(sizeof(ks_isort_stack_t) * ((sizeof(size_t)*d)+2)); \ top = stack; s = a; t = a + (n-1); d <<= 1; \ while (1) { \ if (s < t) { \ if (--d == 0) { \ ks_combsort_##name(t - s + 1, s); \ t = s; \ continue; \ } \ i = s; j = t; k = i + ((j-i)>>1) + 1; \ if (__sort_lt(*k, *i)) { \ if (__sort_lt(*k, *j)) k = j; \ } else k = __sort_lt(*j, *i)? i : j; \ rp = *k; \ if (k != t) { swap_tmp = *k; *k = *t; *t = swap_tmp; } \ for (;;) { \ do ++i; while (__sort_lt(*i, rp)); \ do --j; while (i <= j && __sort_lt(rp, *j)); \ if (j <= i) break; \ swap_tmp = *i; *i = *j; *j = swap_tmp; \ } \ swap_tmp = *i; *i = *t; *t = swap_tmp; \ if (i-s > t-i) { \ if (i-s > 16) { top->left = s; top->right = i-1; top->depth = d; ++top; } \ s = t-i > 16? i+1 : t; \ } else { \ if (t-i > 16) { top->left = i+1; top->right = t; top->depth = d; ++top; } \ t = i-s > 16? i-1 : s; \ } \ } else { \ if (top == stack) { \ free(stack); \ __ks_insertsort_##name(a, a+n); \ return; \ } else { --top; s = (type_t*)top->left; t = (type_t*)top->right; d = top->depth; } \ } \ } \ } \ /* This function is adapted from: http://ndevilla.free.fr/median/ */ \ /* 0 <= kk < n */ \ type_t ks_ksmall_##name(size_t n, type_t arr[], size_t kk) \ { \ type_t *low, *high, *k, *ll, *hh, *mid; \ low = arr; high = arr + n - 1; k = arr + kk; \ for (;;) { \ if (high <= low) return *k; \ if (high == low + 1) { \ if (__sort_lt(*high, *low)) KSORT_SWAP(type_t, *low, *high); \ return *k; \ } \ mid = low + (high - low) / 2; \ if (__sort_lt(*high, *mid)) KSORT_SWAP(type_t, *mid, *high); \ if (__sort_lt(*high, *low)) KSORT_SWAP(type_t, *low, *high); \ if (__sort_lt(*low, *mid)) KSORT_SWAP(type_t, *mid, *low); \ KSORT_SWAP(type_t, *mid, *(low+1)); \ ll = low + 1; hh = high; \ for (;;) { \ do ++ll; while (__sort_lt(*ll, *low)); \ do --hh; while (__sort_lt(*low, *hh)); \ if (hh < ll) break; \ KSORT_SWAP(type_t, *ll, *hh); \ } \ KSORT_SWAP(type_t, *low, *hh); \ if (hh <= k) low = ll; \ if (hh >= k) high = hh - 1; \ } \ } \ void ks_shuffle_##name(size_t n, type_t a[]) \ { \ int i, j; \ for (i = n; i > 1; --i) { \ type_t tmp; \ j = (int)(drand48() * i); \ tmp = a[j]; a[j] = a[i-1]; a[i-1] = tmp; \ } \ } #define ks_mergesort(name, n, a, t) ks_mergesort_##name(n, a, t) #define ks_introsort(name, n, a) ks_introsort_##name(n, a) #define ks_combsort(name, n, a) ks_combsort_##name(n, a) #define ks_heapsort(name, n, a) ks_heapsort_##name(n, a) #define ks_heapmake(name, n, a) ks_heapmake_##name(n, a) #define ks_heapadjust(name, i, n, a) ks_heapadjust_##name(i, n, a) #define ks_ksmall(name, n, a, k) ks_ksmall_##name(n, a, k) #define ks_shuffle(name, n, a) ks_shuffle_##name(n, a) #define ks_lt_generic(a, b) ((a) < (b)) #define ks_lt_str(a, b) (strcmp((a), (b)) < 0) typedef const char *ksstr_t; #define KSORT_INIT_GENERIC(type_t) KSORT_INIT(type_t, type_t, ks_lt_generic) #define KSORT_INIT_STR KSORT_INIT(str, ksstr_t, ks_lt_str) #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/sam.h
.h
2,688
100
#ifndef BAM_SAM_H #define BAM_SAM_H #include "bam.h" /*! @header This file provides higher level of I/O routines and unifies the APIs for SAM and BAM formats. These APIs are more convenient and recommended. @copyright Genome Research Ltd. */ /*! @typedef @abstract SAM/BAM file handler @field type type of the handler; bit 1 for BAM, 2 for reading and bit 3-4 for flag format @field bam BAM file handler; valid if (type&1) == 1 @field tamr SAM file handler for reading; valid if type == 2 @field tamw SAM file handler for writing; valid if type == 0 @field header header struct */ typedef struct { int type; union { tamFile tamr; bamFile bam; FILE *tamw; } x; bam_header_t *header; } samfile_t; #ifdef __cplusplus extern "C" { #endif /*! @abstract Open a SAM/BAM file @param fn SAM/BAM file name; "-" is recognized as stdin (for reading) or stdout (for writing). @param mode open mode /[rw](b?)(u?)(h?)([xX]?)/: 'r' for reading, 'w' for writing, 'b' for BAM I/O, 'u' for uncompressed BAM output, 'h' for outputing header in SAM, 'x' for HEX flag and 'X' for string flag. If 'b' present, it must immediately follow 'r' or 'w'. Valid modes are "r", "w", "wh", "wx", "whx", "wX", "whX", "rb", "wb" and "wbu" exclusively. @param aux auxiliary data; if mode[0]=='w', aux points to bam_header_t; if strcmp(mode, "rb")!=0 and @SQ header lines in SAM are absent, aux points the file name of the list of the reference; aux is not used otherwise. If @SQ header lines are present in SAM, aux is not used, either. @return SAM/BAM file handler */ samfile_t *samopen(const char *fn, const char *mode, const void *aux); /*! @abstract Close a SAM/BAM handler @param fp file handler to be closed */ void samclose(samfile_t *fp); /*! @abstract Read one alignment @param fp file handler @param b alignment @return bytes read */ int samread(samfile_t *fp, bam1_t *b); /*! @abstract Write one alignment @param fp file handler @param b alignment @return bytes written */ int samwrite(samfile_t *fp, const bam1_t *b); /*! @abstract Get the pileup for a whole alignment file @param fp file handler @param mask mask transferred to bam_plbuf_set_mask() @param func user defined function called in the pileup process #param data user provided data for func() */ int sampileup(samfile_t *fp, int mask, bam_pileup_f func, void *data); char *samfaipath(const char *fn_ref); int samthreads(samfile_t *fp, int n_threads, int n_sub_blks); #ifdef __cplusplus } #endif #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/kstring.h
.h
4,459
170
/* The MIT License Copyright (c) by Attractive Chaos <attractor@live.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef KSTRING_H #define KSTRING_H #include <stdlib.h> #include <string.h> #include <stdint.h> #ifndef kroundup32 #define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x)) #endif #ifndef KSTRING_T #define KSTRING_T kstring_t typedef struct __kstring_t { size_t l, m; char *s; } kstring_t; #endif typedef struct { uint64_t tab[4]; int sep, finished; const char *p; // end of the current token } ks_tokaux_t; #ifdef __cplusplus extern "C" { #endif int ksprintf(kstring_t *s, const char *fmt, ...); int ksplit_core(char *s, int delimiter, int *_max, int **_offsets); char *kstrstr(const char *str, const char *pat, int **_prep); char *kstrnstr(const char *str, const char *pat, int n, int **_prep); void *kmemmem(const void *_str, int n, const void *_pat, int m, int **_prep); /* kstrtok() is similar to strtok_r() except that str is not * modified and both str and sep can be NULL. For efficiency, it is * actually recommended to set both to NULL in the subsequent calls * if sep is not changed. */ char *kstrtok(const char *str, const char *sep, ks_tokaux_t *aux); #ifdef __cplusplus } #endif static inline void ks_resize(kstring_t *s, size_t size) { if (s->m < size) { s->m = size; kroundup32(s->m); s->s = (char*)realloc(s->s, s->m); } } static inline int kputsn(const char *p, int l, kstring_t *s) { if (s->l + l + 1 >= s->m) { s->m = s->l + l + 2; kroundup32(s->m); s->s = (char*)realloc(s->s, s->m); } memcpy(s->s + s->l, p, l); s->l += l; s->s[s->l] = 0; return l; } static inline int kputs(const char *p, kstring_t *s) { return kputsn(p, strlen(p), s); } static inline int kputc(int c, kstring_t *s) { if (s->l + 1 >= s->m) { s->m = s->l + 2; kroundup32(s->m); s->s = (char*)realloc(s->s, s->m); } s->s[s->l++] = c; s->s[s->l] = 0; return c; } static inline int kputw(int c, kstring_t *s) { char buf[16]; int l, x; if (c == 0) return kputc('0', s); if(c < 0) for (l = 0, x = c; x < 0; x /= 10) buf[l++] = '0' - (x%10); else for (l = 0, x = c; x > 0; x /= 10) buf[l++] = x%10 + '0'; if (c < 0) buf[l++] = '-'; if (s->l + l + 1 >= s->m) { s->m = s->l + l + 2; kroundup32(s->m); s->s = (char*)realloc(s->s, s->m); } for (x = l - 1; x >= 0; --x) s->s[s->l++] = buf[x]; s->s[s->l] = 0; return 0; } static inline int kputuw(unsigned c, kstring_t *s) { char buf[16]; int l, i; unsigned x; if (c == 0) return kputc('0', s); for (l = 0, x = c; x > 0; x /= 10) buf[l++] = x%10 + '0'; if (s->l + l + 1 >= s->m) { s->m = s->l + l + 2; kroundup32(s->m); s->s = (char*)realloc(s->s, s->m); } for (i = l - 1; i >= 0; --i) s->s[s->l++] = buf[i]; s->s[s->l] = 0; return 0; } static inline int kputl(long c, kstring_t *s) { char buf[32]; long l, x; if (c == 0) return kputc('0', s); for (l = 0, x = c < 0? -c : c; x > 0; x /= 10) buf[l++] = x%10 + '0'; if (c < 0) buf[l++] = '-'; if (s->l + l + 1 >= s->m) { s->m = s->l + l + 2; kroundup32(s->m); s->s = (char*)realloc(s->s, s->m); } for (x = l - 1; x >= 0; --x) s->s[s->l++] = buf[x]; s->s[s->l] = 0; return 0; } static inline int *ksplit(kstring_t *s, int delimiter, int *n) { int max = 0, *offsets = 0; *n = ksplit_core(s->s, delimiter, &max, &offsets); return offsets; } #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/kstring.c
.c
5,388
213
#include <stdarg.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdint.h> #include "kstring.h" int ksprintf(kstring_t *s, const char *fmt, ...) { va_list ap; int l; va_start(ap, fmt); l = vsnprintf(s->s + s->l, s->m - s->l, fmt, ap); // This line does not work with glibc 2.0. See `man snprintf'. va_end(ap); if (l + 1 > s->m - s->l) { s->m = s->l + l + 2; kroundup32(s->m); s->s = (char*)realloc(s->s, s->m); va_start(ap, fmt); l = vsnprintf(s->s + s->l, s->m - s->l, fmt, ap); } va_end(ap); s->l += l; return l; } char *kstrtok(const char *str, const char *sep, ks_tokaux_t *aux) { const char *p, *start; if (sep) { // set up the table if (str == 0 && (aux->tab[0]&1)) return 0; // no need to set up if we have finished aux->finished = 0; if (sep[1]) { aux->sep = -1; aux->tab[0] = aux->tab[1] = aux->tab[2] = aux->tab[3] = 0; for (p = sep; *p; ++p) aux->tab[*p>>6] |= 1ull<<(*p&0x3f); } else aux->sep = sep[0]; } if (aux->finished) return 0; else if (str) aux->p = str - 1, aux->finished = 0; if (aux->sep < 0) { for (p = start = aux->p + 1; *p; ++p) if (aux->tab[*p>>6]>>(*p&0x3f)&1) break; } else { for (p = start = aux->p + 1; *p; ++p) if (*p == aux->sep) break; } aux->p = p; // end of token if (*p == 0) aux->finished = 1; // no more tokens return (char*)start; } // s MUST BE a null terminated string; l = strlen(s) int ksplit_core(char *s, int delimiter, int *_max, int **_offsets) { int i, n, max, last_char, last_start, *offsets, l; n = 0; max = *_max; offsets = *_offsets; l = strlen(s); #define __ksplit_aux do { \ if (_offsets) { \ s[i] = 0; \ if (n == max) { \ max = max? max<<1 : 2; \ offsets = (int*)realloc(offsets, sizeof(int) * max); \ } \ offsets[n++] = last_start; \ } else ++n; \ } while (0) for (i = 0, last_char = last_start = 0; i <= l; ++i) { if (delimiter == 0) { if (isspace(s[i]) || s[i] == 0) { if (isgraph(last_char)) __ksplit_aux; // the end of a field } else { if (isspace(last_char) || last_char == 0) last_start = i; } } else { if (s[i] == delimiter || s[i] == 0) { if (last_char != 0 && last_char != delimiter) __ksplit_aux; // the end of a field } else { if (last_char == delimiter || last_char == 0) last_start = i; } } last_char = s[i]; } *_max = max; *_offsets = offsets; return n; } /********************** * Boyer-Moore search * **********************/ typedef unsigned char ubyte_t; // reference: http://www-igm.univ-mlv.fr/~lecroq/string/node14.html static int *ksBM_prep(const ubyte_t *pat, int m) { int i, *suff, *prep, *bmGs, *bmBc; prep = (int*)calloc(m + 256, sizeof(int)); bmGs = prep; bmBc = prep + m; { // preBmBc() for (i = 0; i < 256; ++i) bmBc[i] = m; for (i = 0; i < m - 1; ++i) bmBc[pat[i]] = m - i - 1; } suff = (int*)calloc(m, sizeof(int)); { // suffixes() int f = 0, g; suff[m - 1] = m; g = m - 1; for (i = m - 2; i >= 0; --i) { if (i > g && suff[i + m - 1 - f] < i - g) suff[i] = suff[i + m - 1 - f]; else { if (i < g) g = i; f = i; while (g >= 0 && pat[g] == pat[g + m - 1 - f]) --g; suff[i] = f - g; } } } { // preBmGs() int j = 0; for (i = 0; i < m; ++i) bmGs[i] = m; for (i = m - 1; i >= 0; --i) if (suff[i] == i + 1) for (; j < m - 1 - i; ++j) if (bmGs[j] == m) bmGs[j] = m - 1 - i; for (i = 0; i <= m - 2; ++i) bmGs[m - 1 - suff[i]] = m - 1 - i; } free(suff); return prep; } void *kmemmem(const void *_str, int n, const void *_pat, int m, int **_prep) { int i, j, *prep = 0, *bmGs, *bmBc; const ubyte_t *str, *pat; str = (const ubyte_t*)_str; pat = (const ubyte_t*)_pat; prep = (_prep == 0 || *_prep == 0)? ksBM_prep(pat, m) : *_prep; if (_prep && *_prep == 0) *_prep = prep; bmGs = prep; bmBc = prep + m; j = 0; while (j <= n - m) { for (i = m - 1; i >= 0 && pat[i] == str[i+j]; --i); if (i >= 0) { int max = bmBc[str[i+j]] - m + 1 + i; if (max < bmGs[i]) max = bmGs[i]; j += max; } else return (void*)(str + j); } if (_prep == 0) free(prep); return 0; } char *kstrstr(const char *str, const char *pat, int **_prep) { return (char*)kmemmem(str, strlen(str), pat, strlen(pat), _prep); } char *kstrnstr(const char *str, const char *pat, int n, int **_prep) { return (char*)kmemmem(str, n, pat, strlen(pat), _prep); } /*********************** * The main() function * ***********************/ #ifdef KSTRING_MAIN #include <stdio.h> int main() { kstring_t *s; int *fields, n, i; ks_tokaux_t aux; char *p; s = (kstring_t*)calloc(1, sizeof(kstring_t)); // test ksprintf() ksprintf(s, " abcdefg: %d ", 100); printf("'%s'\n", s->s); // test ksplit() fields = ksplit(s, 0, &n); for (i = 0; i < n; ++i) printf("field[%d] = '%s'\n", i, s->s + fields[i]); // test kstrtok() s->l = 0; for (p = kstrtok("ab:cde:fg/hij::k", ":/", &aux); p; p = kstrtok(0, 0, &aux)) { kputsn(p, aux.p - p, s); kputc('\n', s); } printf("%s", s->s); // free free(s->s); free(s); free(fields); { static char *str = "abcdefgcdgcagtcakcdcd"; static char *pat = "cd"; char *ret, *s = str; int *prep = 0; while ((ret = kstrstr(s, pat, &prep)) != 0) { printf("match: %s\n", ret); s = ret + prep[0]; } free(prep); } return 0; } #endif
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_index.c
.c
21,491
727
#include <ctype.h> #include <assert.h> #include "bam.h" #include "khash.h" #include "ksort.h" #include "bam_endian.h" #ifdef _USE_KNETFILE #include "knetfile.h" #endif /*! @header Alignment indexing. Before indexing, BAM must be sorted based on the leftmost coordinate of alignments. In indexing, BAM uses two indices: a UCSC binning index and a simple linear index. The binning index is efficient for alignments spanning long distance, while the auxiliary linear index helps to reduce unnecessary seek calls especially for short alignments. The UCSC binning scheme was suggested by Richard Durbin and Lincoln Stein and is explained by Kent et al. (2002). In this scheme, each bin represents a contiguous genomic region which can be fully contained in another bin; each alignment is associated with a bin which represents the smallest region containing the entire alignment. The binning scheme is essentially another representation of R-tree. A distinct bin uniquely corresponds to a distinct internal node in a R-tree. Bin A is a child of Bin B if region A is contained in B. In BAM, each bin may span 2^29, 2^26, 2^23, 2^20, 2^17 or 2^14 bp. Bin 0 spans a 512Mbp region, bins 1-8 span 64Mbp, 9-72 8Mbp, 73-584 1Mbp, 585-4680 128Kbp and bins 4681-37449 span 16Kbp regions. If we want to find the alignments overlapped with a region [rbeg,rend), we need to calculate the list of bins that may be overlapped the region and test the alignments in the bins to confirm the overlaps. If the specified region is short, typically only a few alignments in six bins need to be retrieved. The overlapping alignments can be quickly fetched. */ #define BAM_MIN_CHUNK_GAP 32768 // 1<<14 is the size of minimum bin. #define BAM_LIDX_SHIFT 14 #define BAM_MAX_BIN 37450 // =(8^6-1)/7+1 typedef struct { uint64_t u, v; } pair64_t; #define pair64_lt(a,b) ((a).u < (b).u) KSORT_INIT(off, pair64_t, pair64_lt) typedef struct { uint32_t m, n; pair64_t *list; } bam_binlist_t; typedef struct { int32_t n, m; uint64_t *offset; } bam_lidx_t; KHASH_MAP_INIT_INT(i, bam_binlist_t) struct __bam_index_t { int32_t n; uint64_t n_no_coor; // unmapped reads without coordinate khash_t(i) **index; bam_lidx_t *index2; }; // requirement: len <= LEN_MASK static inline void insert_offset(khash_t(i) *h, int bin, uint64_t beg, uint64_t end) { khint_t k; bam_binlist_t *l; int ret; k = kh_put(i, h, bin, &ret); l = &kh_value(h, k); if (ret) { // not present l->m = 1; l->n = 0; l->list = (pair64_t*)calloc(l->m, 16); } if (l->n == l->m) { l->m <<= 1; l->list = (pair64_t*)realloc(l->list, l->m * 16); } l->list[l->n].u = beg; l->list[l->n++].v = end; } static inline void insert_offset2(bam_lidx_t *index2, bam1_t *b, uint64_t offset) { int i, beg, end; beg = b->core.pos >> BAM_LIDX_SHIFT; end = (bam_calend(&b->core, bam1_cigar(b)) - 1) >> BAM_LIDX_SHIFT; if (index2->m < end + 1) { int old_m = index2->m; index2->m = end + 1; kroundup32(index2->m); index2->offset = (uint64_t*)realloc(index2->offset, index2->m * 8); memset(index2->offset + old_m, 0, 8 * (index2->m - old_m)); } if (beg == end) { if (index2->offset[beg] == 0) index2->offset[beg] = offset; } else { for (i = beg; i <= end; ++i) if (index2->offset[i] == 0) index2->offset[i] = offset; } index2->n = end + 1; } static void merge_chunks(bam_index_t *idx) { #if defined(BAM_TRUE_OFFSET) || defined(BAM_VIRTUAL_OFFSET16) khash_t(i) *index; int i, l, m; khint_t k; for (i = 0; i < idx->n; ++i) { index = idx->index[i]; for (k = kh_begin(index); k != kh_end(index); ++k) { bam_binlist_t *p; if (!kh_exist(index, k) || kh_key(index, k) == BAM_MAX_BIN) continue; p = &kh_value(index, k); m = 0; for (l = 1; l < p->n; ++l) { #ifdef BAM_TRUE_OFFSET if (p->list[m].v + BAM_MIN_CHUNK_GAP > p->list[l].u) p->list[m].v = p->list[l].v; #else if (p->list[m].v>>16 == p->list[l].u>>16) p->list[m].v = p->list[l].v; #endif else p->list[++m] = p->list[l]; } // ~for(l) p->n = m + 1; } // ~for(k) } // ~for(i) #endif // defined(BAM_TRUE_OFFSET) || defined(BAM_BGZF) } static void fill_missing(bam_index_t *idx) { int i, j; for (i = 0; i < idx->n; ++i) { bam_lidx_t *idx2 = &idx->index2[i]; for (j = 1; j < idx2->n; ++j) if (idx2->offset[j] == 0) idx2->offset[j] = idx2->offset[j-1]; } } bam_index_t *bam_index_core(bamFile fp) { bam1_t *b; bam_header_t *h; int i, ret; bam_index_t *idx; uint32_t last_bin, save_bin; int32_t last_coor, last_tid, save_tid; bam1_core_t *c; uint64_t save_off, last_off, n_mapped, n_unmapped, off_beg, off_end, n_no_coor; h = bam_header_read(fp); if(h == 0) { fprintf(stderr, "[bam_index_core] Invalid BAM header."); return NULL; } idx = (bam_index_t*)calloc(1, sizeof(bam_index_t)); b = (bam1_t*)calloc(1, sizeof(bam1_t)); c = &b->core; idx->n = h->n_targets; bam_header_destroy(h); idx->index = (khash_t(i)**)calloc(idx->n, sizeof(void*)); for (i = 0; i < idx->n; ++i) idx->index[i] = kh_init(i); idx->index2 = (bam_lidx_t*)calloc(idx->n, sizeof(bam_lidx_t)); save_bin = save_tid = last_tid = last_bin = 0xffffffffu; save_off = last_off = bam_tell(fp); last_coor = 0xffffffffu; n_mapped = n_unmapped = n_no_coor = off_end = 0; off_beg = off_end = bam_tell(fp); while ((ret = bam_read1(fp, b)) >= 0) { if (c->tid < 0) ++n_no_coor; if (last_tid < c->tid || (last_tid >= 0 && c->tid < 0)) { // change of chromosomes last_tid = c->tid; last_bin = 0xffffffffu; } else if ((uint32_t)last_tid > (uint32_t)c->tid) { fprintf(stderr, "[bam_index_core] the alignment is not sorted (%s): %d-th chr > %d-th chr\n", bam1_qname(b), last_tid+1, c->tid+1); return NULL; } else if ((int32_t)c->tid >= 0 && last_coor > c->pos) { fprintf(stderr, "[bam_index_core] the alignment is not sorted (%s): %u > %u in %d-th chr\n", bam1_qname(b), last_coor, c->pos, c->tid+1); return NULL; } if (c->tid >= 0 && !(c->flag & BAM_FUNMAP)) insert_offset2(&idx->index2[b->core.tid], b, last_off); if (c->bin != last_bin) { // then possibly write the binning index if (save_bin != 0xffffffffu) // save_bin==0xffffffffu only happens to the first record insert_offset(idx->index[save_tid], save_bin, save_off, last_off); if (last_bin == 0xffffffffu && save_tid != 0xffffffffu) { // write the meta element off_end = last_off; insert_offset(idx->index[save_tid], BAM_MAX_BIN, off_beg, off_end); insert_offset(idx->index[save_tid], BAM_MAX_BIN, n_mapped, n_unmapped); n_mapped = n_unmapped = 0; off_beg = off_end; } save_off = last_off; save_bin = last_bin = c->bin; save_tid = c->tid; if (save_tid < 0) break; } if (bam_tell(fp) <= last_off) { fprintf(stderr, "[bam_index_core] bug in BGZF/RAZF: %llx < %llx\n", (unsigned long long)bam_tell(fp), (unsigned long long)last_off); return NULL; } if (c->flag & BAM_FUNMAP) ++n_unmapped; else ++n_mapped; last_off = bam_tell(fp); last_coor = b->core.pos; } if (save_tid >= 0) { insert_offset(idx->index[save_tid], save_bin, save_off, bam_tell(fp)); insert_offset(idx->index[save_tid], BAM_MAX_BIN, off_beg, bam_tell(fp)); insert_offset(idx->index[save_tid], BAM_MAX_BIN, n_mapped, n_unmapped); } merge_chunks(idx); fill_missing(idx); if (ret >= 0) { while ((ret = bam_read1(fp, b)) >= 0) { ++n_no_coor; if (c->tid >= 0 && n_no_coor) { fprintf(stderr, "[bam_index_core] the alignment is not sorted: reads without coordinates prior to reads with coordinates.\n"); return NULL; } } } if (ret < -1) fprintf(stderr, "[bam_index_core] truncated file? Continue anyway. (%d)\n", ret); free(b->data); free(b); idx->n_no_coor = n_no_coor; return idx; } void bam_index_destroy(bam_index_t *idx) { khint_t k; int i; if (idx == 0) return; for (i = 0; i < idx->n; ++i) { khash_t(i) *index = idx->index[i]; bam_lidx_t *index2 = idx->index2 + i; for (k = kh_begin(index); k != kh_end(index); ++k) { if (kh_exist(index, k)) free(kh_value(index, k).list); } kh_destroy(i, index); free(index2->offset); } free(idx->index); free(idx->index2); free(idx); } void bam_index_save(const bam_index_t *idx, FILE *fp) { int32_t i, size; khint_t k; fwrite("BAI\1", 1, 4, fp); if (bam_is_be) { uint32_t x = idx->n; fwrite(bam_swap_endian_4p(&x), 4, 1, fp); } else fwrite(&idx->n, 4, 1, fp); for (i = 0; i < idx->n; ++i) { khash_t(i) *index = idx->index[i]; bam_lidx_t *index2 = idx->index2 + i; // write binning index size = kh_size(index); if (bam_is_be) { // big endian uint32_t x = size; fwrite(bam_swap_endian_4p(&x), 4, 1, fp); } else fwrite(&size, 4, 1, fp); for (k = kh_begin(index); k != kh_end(index); ++k) { if (kh_exist(index, k)) { bam_binlist_t *p = &kh_value(index, k); if (bam_is_be) { // big endian uint32_t x; x = kh_key(index, k); fwrite(bam_swap_endian_4p(&x), 4, 1, fp); x = p->n; fwrite(bam_swap_endian_4p(&x), 4, 1, fp); for (x = 0; (int)x < p->n; ++x) { bam_swap_endian_8p(&p->list[x].u); bam_swap_endian_8p(&p->list[x].v); } fwrite(p->list, 16, p->n, fp); for (x = 0; (int)x < p->n; ++x) { bam_swap_endian_8p(&p->list[x].u); bam_swap_endian_8p(&p->list[x].v); } } else { fwrite(&kh_key(index, k), 4, 1, fp); fwrite(&p->n, 4, 1, fp); fwrite(p->list, 16, p->n, fp); } } } // write linear index (index2) if (bam_is_be) { int x = index2->n; fwrite(bam_swap_endian_4p(&x), 4, 1, fp); } else fwrite(&index2->n, 4, 1, fp); if (bam_is_be) { // big endian int x; for (x = 0; (int)x < index2->n; ++x) bam_swap_endian_8p(&index2->offset[x]); fwrite(index2->offset, 8, index2->n, fp); for (x = 0; (int)x < index2->n; ++x) bam_swap_endian_8p(&index2->offset[x]); } else fwrite(index2->offset, 8, index2->n, fp); } { // write the number of reads coor-less records. uint64_t x = idx->n_no_coor; if (bam_is_be) bam_swap_endian_8p(&x); fwrite(&x, 8, 1, fp); } fflush(fp); } static bam_index_t *bam_index_load_core(FILE *fp) { int i; char magic[4]; bam_index_t *idx; if (fp == 0) { fprintf(stderr, "[bam_index_load_core] fail to load index.\n"); return 0; } fread(magic, 1, 4, fp); if (strncmp(magic, "BAI\1", 4)) { fprintf(stderr, "[bam_index_load] wrong magic number.\n"); fclose(fp); return 0; } idx = (bam_index_t*)calloc(1, sizeof(bam_index_t)); fread(&idx->n, 4, 1, fp); if (bam_is_be) bam_swap_endian_4p(&idx->n); idx->index = (khash_t(i)**)calloc(idx->n, sizeof(void*)); idx->index2 = (bam_lidx_t*)calloc(idx->n, sizeof(bam_lidx_t)); for (i = 0; i < idx->n; ++i) { khash_t(i) *index; bam_lidx_t *index2 = idx->index2 + i; uint32_t key, size; khint_t k; int j, ret; bam_binlist_t *p; index = idx->index[i] = kh_init(i); // load binning index fread(&size, 4, 1, fp); if (bam_is_be) bam_swap_endian_4p(&size); for (j = 0; j < (int)size; ++j) { fread(&key, 4, 1, fp); if (bam_is_be) bam_swap_endian_4p(&key); k = kh_put(i, index, key, &ret); p = &kh_value(index, k); fread(&p->n, 4, 1, fp); if (bam_is_be) bam_swap_endian_4p(&p->n); p->m = p->n; p->list = (pair64_t*)malloc(p->m * 16); fread(p->list, 16, p->n, fp); if (bam_is_be) { int x; for (x = 0; x < p->n; ++x) { bam_swap_endian_8p(&p->list[x].u); bam_swap_endian_8p(&p->list[x].v); } } } // load linear index fread(&index2->n, 4, 1, fp); if (bam_is_be) bam_swap_endian_4p(&index2->n); index2->m = index2->n; index2->offset = (uint64_t*)calloc(index2->m, 8); fread(index2->offset, index2->n, 8, fp); if (bam_is_be) for (j = 0; j < index2->n; ++j) bam_swap_endian_8p(&index2->offset[j]); } if (fread(&idx->n_no_coor, 8, 1, fp) == 0) idx->n_no_coor = 0; if (bam_is_be) bam_swap_endian_8p(&idx->n_no_coor); return idx; } bam_index_t *bam_index_load_local(const char *_fn) { FILE *fp; char *fnidx, *fn; if (strstr(_fn, "ftp://") == _fn || strstr(_fn, "http://") == _fn) { const char *p; int l = strlen(_fn); for (p = _fn + l - 1; p >= _fn; --p) if (*p == '/') break; fn = strdup(p + 1); } else fn = strdup(_fn); fnidx = (char*)calloc(strlen(fn) + 5, 1); strcpy(fnidx, fn); strcat(fnidx, ".bai"); fp = fopen(fnidx, "rb"); if (fp == 0) { // try "{base}.bai" char *s = strstr(fn, "bam"); if (s == fn + strlen(fn) - 3) { strcpy(fnidx, fn); fnidx[strlen(fn)-1] = 'i'; fp = fopen(fnidx, "rb"); } } free(fnidx); free(fn); if (fp) { bam_index_t *idx = bam_index_load_core(fp); fclose(fp); return idx; } else return 0; } #ifdef _USE_KNETFILE static void download_from_remote(const char *url) { const int buf_size = 1 * 1024 * 1024; char *fn; FILE *fp; uint8_t *buf; knetFile *fp_remote; int l; if (strstr(url, "ftp://") != url && strstr(url, "http://") != url) return; l = strlen(url); for (fn = (char*)url + l - 1; fn >= url; --fn) if (*fn == '/') break; ++fn; // fn now points to the file name fp_remote = knet_open(url, "r"); if (fp_remote == 0) { fprintf(stderr, "[download_from_remote] fail to open remote file.\n"); return; } if ((fp = fopen(fn, "wb")) == 0) { fprintf(stderr, "[download_from_remote] fail to create file in the working directory.\n"); knet_close(fp_remote); return; } buf = (uint8_t*)calloc(buf_size, 1); while ((l = knet_read(fp_remote, buf, buf_size)) != 0) fwrite(buf, 1, l, fp); free(buf); fclose(fp); knet_close(fp_remote); } #else static void download_from_remote(const char *url) { return; } #endif bam_index_t *bam_index_load(const char *fn) { bam_index_t *idx; idx = bam_index_load_local(fn); if (idx == 0 && (strstr(fn, "ftp://") == fn || strstr(fn, "http://") == fn)) { char *fnidx = calloc(strlen(fn) + 5, 1); strcat(strcpy(fnidx, fn), ".bai"); fprintf(stderr, "[bam_index_load] attempting to download the remote index file.\n"); download_from_remote(fnidx); free(fnidx); idx = bam_index_load_local(fn); } if (idx == 0) fprintf(stderr, "[bam_index_load] fail to load BAM index.\n"); return idx; } int bam_index_build2(const char *fn, const char *_fnidx) { char *fnidx; FILE *fpidx; bamFile fp; bam_index_t *idx; if ((fp = bam_open(fn, "r")) == 0) { fprintf(stderr, "[bam_index_build2] fail to open the BAM file.\n"); return -1; } idx = bam_index_core(fp); bam_close(fp); if(idx == 0) { fprintf(stderr, "[bam_index_build2] fail to index the BAM file.\n"); return -1; } if (_fnidx == 0) { fnidx = (char*)calloc(strlen(fn) + 5, 1); strcpy(fnidx, fn); strcat(fnidx, ".bai"); } else fnidx = strdup(_fnidx); fpidx = fopen(fnidx, "wb"); if (fpidx == 0) { fprintf(stderr, "[bam_index_build2] fail to create the index file.\n"); free(fnidx); bam_index_destroy(idx); return -1; } bam_index_save(idx, fpidx); bam_index_destroy(idx); fclose(fpidx); free(fnidx); return 0; } int bam_index_build(const char *fn) { return bam_index_build2(fn, 0); } int bam_index(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: samtools index <in.bam> [out.index]\n"); return 1; } if (argc >= 3) bam_index_build2(argv[1], argv[2]); else bam_index_build(argv[1]); return 0; } int bam_idxstats(int argc, char *argv[]) { bam_index_t *idx; bam_header_t *header; bamFile fp; int i; if (argc < 2) { fprintf(stderr, "Usage: samtools idxstats <in.bam>\n"); return 1; } fp = bam_open(argv[1], "r"); if (fp == 0) { fprintf(stderr, "[%s] fail to open BAM.\n", __func__); return 1; } header = bam_header_read(fp); bam_close(fp); idx = bam_index_load(argv[1]); if (idx == 0) { fprintf(stderr, "[%s] fail to load the index.\n", __func__); return 1; } for (i = 0; i < idx->n; ++i) { khint_t k; khash_t(i) *h = idx->index[i]; printf("%s\t%d", header->target_name[i], header->target_len[i]); k = kh_get(i, h, BAM_MAX_BIN); if (k != kh_end(h)) printf("\t%llu\t%llu", (long long)kh_val(h, k).list[1].u, (long long)kh_val(h, k).list[1].v); else printf("\t0\t0"); putchar('\n'); } printf("*\t0\t0\t%llu\n", (long long)idx->n_no_coor); bam_header_destroy(header); bam_index_destroy(idx); return 0; } static inline int reg2bins(uint32_t beg, uint32_t end, uint16_t list[BAM_MAX_BIN]) { int i = 0, k; if (beg >= end) return 0; if (end >= 1u<<29) end = 1u<<29; --end; list[i++] = 0; for (k = 1 + (beg>>26); k <= 1 + (end>>26); ++k) list[i++] = k; for (k = 9 + (beg>>23); k <= 9 + (end>>23); ++k) list[i++] = k; for (k = 73 + (beg>>20); k <= 73 + (end>>20); ++k) list[i++] = k; for (k = 585 + (beg>>17); k <= 585 + (end>>17); ++k) list[i++] = k; for (k = 4681 + (beg>>14); k <= 4681 + (end>>14); ++k) list[i++] = k; return i; } static inline int is_overlap(uint32_t beg, uint32_t end, const bam1_t *b) { uint32_t rbeg = b->core.pos; uint32_t rend = b->core.n_cigar? bam_calend(&b->core, bam1_cigar(b)) : b->core.pos + 1; return (rend > beg && rbeg < end); } struct __bam_iter_t { int from_first; // read from the first record; no random access int tid, beg, end, n_off, i, finished; uint64_t curr_off; pair64_t *off; }; // bam_fetch helper function retrieves bam_iter_t bam_iter_query(const bam_index_t *idx, int tid, int beg, int end) { uint16_t *bins; int i, n_bins, n_off; pair64_t *off; khint_t k; khash_t(i) *index; uint64_t min_off; bam_iter_t iter = 0; if (beg < 0) beg = 0; if (end < beg) return 0; // initialize iter iter = calloc(1, sizeof(struct __bam_iter_t)); iter->tid = tid, iter->beg = beg, iter->end = end; iter->i = -1; // bins = (uint16_t*)calloc(BAM_MAX_BIN, 2); n_bins = reg2bins(beg, end, bins); index = idx->index[tid]; if (idx->index2[tid].n > 0) { min_off = (beg>>BAM_LIDX_SHIFT >= idx->index2[tid].n)? idx->index2[tid].offset[idx->index2[tid].n-1] : idx->index2[tid].offset[beg>>BAM_LIDX_SHIFT]; if (min_off == 0) { // improvement for index files built by tabix prior to 0.1.4 int n = beg>>BAM_LIDX_SHIFT; if (n > idx->index2[tid].n) n = idx->index2[tid].n; for (i = n - 1; i >= 0; --i) if (idx->index2[tid].offset[i] != 0) break; if (i >= 0) min_off = idx->index2[tid].offset[i]; } } else min_off = 0; // tabix 0.1.2 may produce such index files for (i = n_off = 0; i < n_bins; ++i) { if ((k = kh_get(i, index, bins[i])) != kh_end(index)) n_off += kh_value(index, k).n; } if (n_off == 0) { free(bins); return iter; } off = (pair64_t*)calloc(n_off, 16); for (i = n_off = 0; i < n_bins; ++i) { if ((k = kh_get(i, index, bins[i])) != kh_end(index)) { int j; bam_binlist_t *p = &kh_value(index, k); for (j = 0; j < p->n; ++j) if (p->list[j].v > min_off) off[n_off++] = p->list[j]; } } free(bins); if (n_off == 0) { free(off); return iter; } { bam1_t *b = (bam1_t*)calloc(1, sizeof(bam1_t)); int l; ks_introsort(off, n_off, off); // resolve completely contained adjacent blocks for (i = 1, l = 0; i < n_off; ++i) if (off[l].v < off[i].v) off[++l] = off[i]; n_off = l + 1; // resolve overlaps between adjacent blocks; this may happen due to the merge in indexing for (i = 1; i < n_off; ++i) if (off[i-1].v >= off[i].u) off[i-1].v = off[i].u; { // merge adjacent blocks #if defined(BAM_TRUE_OFFSET) || defined(BAM_VIRTUAL_OFFSET16) for (i = 1, l = 0; i < n_off; ++i) { #ifdef BAM_TRUE_OFFSET if (off[l].v + BAM_MIN_CHUNK_GAP > off[i].u) off[l].v = off[i].v; #else if (off[l].v>>16 == off[i].u>>16) off[l].v = off[i].v; #endif else off[++l] = off[i]; } n_off = l + 1; #endif } bam_destroy1(b); } iter->n_off = n_off; iter->off = off; return iter; } pair64_t *get_chunk_coordinates(const bam_index_t *idx, int tid, int beg, int end, int *cnt_off) { // for pysam compatibility bam_iter_t iter; pair64_t *off; iter = bam_iter_query(idx, tid, beg, end); off = iter->off; *cnt_off = iter->n_off; free(iter); return off; } void bam_iter_destroy(bam_iter_t iter) { if (iter) { free(iter->off); free(iter); } } int bam_iter_read(bamFile fp, bam_iter_t iter, bam1_t *b) { int ret; if (iter && iter->finished) return -1; if (iter == 0 || iter->from_first) { ret = bam_read1(fp, b); if (ret < 0 && iter) iter->finished = 1; return ret; } if (iter->off == 0) return -1; for (;;) { if (iter->curr_off == 0 || iter->curr_off >= iter->off[iter->i].v) { // then jump to the next chunk if (iter->i == iter->n_off - 1) { ret = -1; break; } // no more chunks if (iter->i >= 0) assert(iter->curr_off == iter->off[iter->i].v); // otherwise bug if (iter->i < 0 || iter->off[iter->i].v != iter->off[iter->i+1].u) { // not adjacent chunks; then seek bam_seek(fp, iter->off[iter->i+1].u, SEEK_SET); iter->curr_off = bam_tell(fp); } ++iter->i; } if ((ret = bam_read1(fp, b)) >= 0) { iter->curr_off = bam_tell(fp); if (b->core.tid != iter->tid || b->core.pos >= iter->end) { // no need to proceed ret = bam_validate1(NULL, b)? -1 : -5; // determine whether end of region or error break; } else if (is_overlap(iter->beg, iter->end, b)) return ret; } else break; // end of file or error } iter->finished = 1; return ret; } int bam_fetch(bamFile fp, const bam_index_t *idx, int tid, int beg, int end, void *data, bam_fetch_f func) { int ret; bam_iter_t iter; bam1_t *b; b = bam_init1(); iter = bam_iter_query(idx, tid, beg, end); while ((ret = bam_iter_read(fp, iter, b)) >= 0) func(b, data); bam_iter_destroy(iter); bam_destroy1(b); return (ret == -1)? 0 : ret; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_tview.c
.c
11,391
369
#include <assert.h> #include "bam_tview.h" int base_tv_init(tview_t* tv,const char *fn, const char *fn_fa, const char *samples) { assert(tv!=NULL); assert(fn!=NULL); tv->mrow = 24; tv->mcol = 80; tv->color_for = TV_COLOR_MAPQ; tv->is_dot = 1; tv->fp = bam_open(fn, "r"); if(tv->fp==0) { fprintf(stderr,"bam_open %s. %s\n", fn,fn_fa); exit(EXIT_FAILURE); } bgzf_set_cache_size(tv->fp, 8 * 1024 *1024); assert(tv->fp); tv->header = bam_header_read(tv->fp); if(tv->header==0) { fprintf(stderr,"Cannot read '%s'.\n", fn); exit(EXIT_FAILURE); } tv->idx = bam_index_load(fn); if (tv->idx == 0) { fprintf(stderr,"Cannot read index for '%s'.\n", fn); exit(EXIT_FAILURE); } tv->lplbuf = bam_lplbuf_init(tv_pl_func, tv); if (fn_fa) tv->fai = fai_load(fn_fa); tv->bca = bcf_call_init(0.83, 13); tv->ins = 1; if ( samples ) { if ( !tv->header->dict ) tv->header->dict = sam_header_parse2(tv->header->text); void *iter = tv->header->dict; const char *key, *val; int n = 0; tv->rg_hash = kh_init(kh_rg); while ( (iter = sam_header2key_val(iter, "RG","ID","SM", &key, &val)) ) { if ( !strcmp(samples,key) || (val && !strcmp(samples,val)) ) { khiter_t k = kh_get(kh_rg, tv->rg_hash, key); if ( k != kh_end(tv->rg_hash) ) continue; int ret; k = kh_put(kh_rg, tv->rg_hash, key, &ret); kh_value(tv->rg_hash, k) = val; n++; } } if ( !n ) { fprintf(stderr,"The sample or read group \"%s\" not present.\n", samples); exit(EXIT_FAILURE); } } return 0; } void base_tv_destroy(tview_t* tv) { bam_lplbuf_destroy(tv->lplbuf); bcf_call_destroy(tv->bca); bam_index_destroy(tv->idx); if (tv->fai) fai_destroy(tv->fai); free(tv->ref); bam_header_destroy(tv->header); bam_close(tv->fp); } int tv_pl_func(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pl, void *data) { extern unsigned char bam_nt16_table[256]; tview_t *tv = (tview_t*)data; int i, j, c, rb, attr, max_ins = 0; uint32_t call = 0; if (pos < tv->left_pos || tv->ccol > tv->mcol) return 0; // out of screen // print referece rb = (tv->ref && pos - tv->left_pos < tv->l_ref)? tv->ref[pos - tv->left_pos] : 'N'; for (i = tv->last_pos + 1; i < pos; ++i) { if (i%10 == 0 && tv->mcol - tv->ccol >= 10) tv->my_mvprintw(tv,0, tv->ccol, "%-d", i+1); c = tv->ref? tv->ref[i - tv->left_pos] : 'N'; tv->my_mvaddch(tv,1, tv->ccol++, c); } if (pos%10 == 0 && tv->mcol - tv->ccol >= 10) tv->my_mvprintw(tv,0, tv->ccol, "%-d", pos+1); { // call consensus bcf_callret1_t bcr; int qsum[4], a1, a2, tmp; double p[3], prior = 30; bcf_call_glfgen(n, pl, bam_nt16_table[rb], tv->bca, &bcr); for (i = 0; i < 4; ++i) qsum[i] = bcr.qsum[i]<<2 | i; for (i = 1; i < 4; ++i) // insertion sort for (j = i; j > 0 && qsum[j] > qsum[j-1]; --j) tmp = qsum[j], qsum[j] = qsum[j-1], qsum[j-1] = tmp; a1 = qsum[0]&3; a2 = qsum[1]&3; p[0] = bcr.p[a1*5+a1]; p[1] = bcr.p[a1*5+a2] + prior; p[2] = bcr.p[a2*5+a2]; if ("ACGT"[a1] != toupper(rb)) p[0] += prior + 3; if ("ACGT"[a2] != toupper(rb)) p[2] += prior + 3; if (p[0] < p[1] && p[0] < p[2]) call = (1<<a1)<<16 | (int)((p[1]<p[2]?p[1]:p[2]) - p[0] + .499); else if (p[2] < p[1] && p[2] < p[0]) call = (1<<a2)<<16 | (int)((p[0]<p[1]?p[0]:p[1]) - p[2] + .499); else call = (1<<a1|1<<a2)<<16 | (int)((p[0]<p[2]?p[0]:p[2]) - p[1] + .499); } attr = tv->my_underline(tv); c = ",ACMGRSVTWYHKDBN"[call>>16&0xf]; i = (call&0xffff)/10+1; if (i > 4) i = 4; attr |= tv->my_colorpair(tv,i); if (c == toupper(rb)) c = '.'; tv->my_attron(tv,attr); tv->my_mvaddch(tv,2, tv->ccol, c); tv->my_attroff(tv,attr); if(tv->ins) { // calculate maximum insert for (i = 0; i < n; ++i) { const bam_pileup1_t *p = pl + i; if (p->indel > 0 && max_ins < p->indel) max_ins = p->indel; } } // core loop for (j = 0; j <= max_ins; ++j) { for (i = 0; i < n; ++i) { const bam_pileup1_t *p = pl + i; int row = TV_MIN_ALNROW + p->level - tv->row_shift; if (j == 0) { if (!p->is_del) { if (tv->base_for == TV_BASE_COLOR_SPACE && (c = bam_aux_getCSi(p->b, p->qpos))) { // assume that if we found one color, we will be able to get the color error if (tv->is_dot && '-' == bam_aux_getCEi(p->b, p->qpos)) c = bam1_strand(p->b)? ',' : '.'; } else { if (tv->show_name) { char *name = bam1_qname(p->b); c = (p->qpos + 1 >= p->b->core.l_qname)? ' ' : name[p->qpos]; } else { c = bam_nt16_rev_table[bam1_seqi(bam1_seq(p->b), p->qpos)]; if (tv->is_dot && toupper(c) == toupper(rb)) c = bam1_strand(p->b)? ',' : '.'; } } } else c = p->is_refskip? (bam1_strand(p->b)? '<' : '>') : '*'; } else { // padding if (j > p->indel) c = '*'; else { // insertion if (tv->base_for == TV_BASE_NUCL) { if (tv->show_name) { char *name = bam1_qname(p->b); c = (p->qpos + j + 1 >= p->b->core.l_qname)? ' ' : name[p->qpos + j]; } else { c = bam_nt16_rev_table[bam1_seqi(bam1_seq(p->b), p->qpos + j)]; if (j == 0 && tv->is_dot && toupper(c) == toupper(rb)) c = bam1_strand(p->b)? ',' : '.'; } } else { c = bam_aux_getCSi(p->b, p->qpos + j); if (tv->is_dot && '-' == bam_aux_getCEi(p->b, p->qpos + j)) c = bam1_strand(p->b)? ',' : '.'; } } } if (row > TV_MIN_ALNROW && row < tv->mrow) { int x; attr = 0; if (((p->b->core.flag&BAM_FPAIRED) && !(p->b->core.flag&BAM_FPROPER_PAIR)) || (p->b->core.flag & BAM_FSECONDARY)) attr |= tv->my_underline(tv); if (tv->color_for == TV_COLOR_BASEQ) { x = bam1_qual(p->b)[p->qpos]/10 + 1; if (x > 4) x = 4; attr |= tv->my_colorpair(tv,x); } else if (tv->color_for == TV_COLOR_MAPQ) { x = p->b->core.qual/10 + 1; if (x > 4) x = 4; attr |= tv->my_colorpair(tv,x); } else if (tv->color_for == TV_COLOR_NUCL) { x = bam_nt16_nt4_table[bam1_seqi(bam1_seq(p->b), p->qpos)] + 5; attr |= tv->my_colorpair(tv,x); } else if(tv->color_for == TV_COLOR_COL) { x = 0; switch(bam_aux_getCSi(p->b, p->qpos)) { case '0': x = 0; break; case '1': x = 1; break; case '2': x = 2; break; case '3': x = 3; break; case '4': x = 4; break; default: x = bam_nt16_nt4_table[bam1_seqi(bam1_seq(p->b), p->qpos)]; break; } x+=5; attr |= tv->my_colorpair(tv,x); } else if(tv->color_for == TV_COLOR_COLQ) { x = bam_aux_getCQi(p->b, p->qpos); if(0 == x) x = bam1_qual(p->b)[p->qpos]; x = x/10 + 1; if (x > 4) x = 4; attr |= tv->my_colorpair(tv,x); } tv->my_attron(tv,attr); tv->my_mvaddch(tv,row, tv->ccol, bam1_strand(p->b)? tolower(c) : toupper(c)); tv->my_attroff(tv,attr); } } c = j? '*' : rb; if (c == '*') { attr = tv->my_colorpair(tv,8); tv->my_attron(tv,attr); tv->my_mvaddch(tv,1, tv->ccol++, c); tv->my_attroff(tv,attr); } else tv->my_mvaddch(tv,1, tv->ccol++, c); } tv->last_pos = pos; return 0; } int tv_fetch_func(const bam1_t *b, void *data) { tview_t *tv = (tview_t*)data; if ( tv->rg_hash ) { const uint8_t *rg = bam_aux_get(b, "RG"); if ( !rg ) return 0; khiter_t k = kh_get(kh_rg, tv->rg_hash, (const char*)(rg + 1)); if ( k == kh_end(tv->rg_hash) ) return 0; } if (tv->no_skip) { uint32_t *cigar = bam1_cigar(b); // this is cheating... int i; for (i = 0; i <b->core.n_cigar; ++i) { if ((cigar[i]&0xf) == BAM_CREF_SKIP) cigar[i] = cigar[i]>>4<<4 | BAM_CDEL; } } bam_lplbuf_push(b, tv->lplbuf); return 0; } int base_draw_aln(tview_t *tv, int tid, int pos) { assert(tv!=NULL); // reset tv->my_clear(tv); tv->curr_tid = tid; tv->left_pos = pos; tv->last_pos = tv->left_pos - 1; tv->ccol = 0; // print ref and consensus if (tv->fai) { char *str; if (tv->ref) free(tv->ref); assert(tv->curr_tid>=0); str = (char*)calloc(strlen(tv->header->target_name[tv->curr_tid]) + 30, 1); assert(str!=NULL); sprintf(str, "%s:%d-%d", tv->header->target_name[tv->curr_tid], tv->left_pos + 1, tv->left_pos + tv->mcol); tv->ref = fai_fetch(tv->fai, str, &tv->l_ref); free(str); } // draw aln bam_lplbuf_reset(tv->lplbuf); bam_fetch(tv->fp, tv->idx, tv->curr_tid, tv->left_pos, tv->left_pos + tv->mcol, tv, tv_fetch_func); bam_lplbuf_push(0, tv->lplbuf); while (tv->ccol < tv->mcol) { int pos = tv->last_pos + 1; if (pos%10 == 0 && tv->mcol - tv->ccol >= 10) tv->my_mvprintw(tv,0, tv->ccol, "%-d", pos+1); tv->my_mvaddch(tv,1, tv->ccol++, (tv->ref && pos < tv->l_ref)? tv->ref[pos - tv->left_pos] : 'N'); ++tv->last_pos; } return 0; } static void error(const char *format, ...) { if ( !format ) { fprintf(stderr, "\n"); fprintf(stderr, "Usage: bamtk tview [options] <aln.bam> [ref.fasta]\n"); fprintf(stderr, "Options:\n"); fprintf(stderr, " -d display output as (H)tml or (C)urses or (T)ext \n"); fprintf(stderr, " -p chr:pos go directly to this position\n"); fprintf(stderr, " -s STR display only reads from this sample or group\n"); fprintf(stderr, "\n\n"); } else { va_list ap; va_start(ap, format); vfprintf(stderr, format, ap); va_end(ap); } exit(-1); } enum dipsay_mode {display_ncurses,display_html,display_text}; extern tview_t* curses_tv_init(const char *fn, const char *fn_fa, const char *samples); extern tview_t* html_tv_init(const char *fn, const char *fn_fa, const char *samples); extern tview_t* text_tv_init(const char *fn, const char *fn_fa, const char *samples); int bam_tview_main(int argc, char *argv[]) { int view_mode=display_ncurses; tview_t* tv=NULL; char *samples=NULL, *position=NULL; int c; while ((c = getopt(argc, argv, "s:p:d:")) >= 0) { switch (c) { case 's': samples=optarg; break; case 'p': position=optarg; break; case 'd': { switch(optarg[0]) { case 'H': case 'h': view_mode=display_html;break; case 'T': case 't': view_mode=display_text;break; case 'C': case 'c': view_mode=display_ncurses;break; default: view_mode=display_ncurses;break; } break; } default: error(NULL); } } if (argc==optind) error(NULL); switch(view_mode) { case display_ncurses: { tv = curses_tv_init(argv[optind], (optind+1>=argc)? 0 : argv[optind+1], samples); break; } case display_text: { tv = text_tv_init(argv[optind], (optind+1>=argc)? 0 : argv[optind+1], samples); break; } case display_html: { tv = html_tv_init(argv[optind], (optind+1>=argc)? 0 : argv[optind+1], samples); break; } } if(tv==NULL) { error("cannot create view"); return EXIT_FAILURE; } if ( position ) { int _tid = -1, _beg, _end; bam_parse_region(tv->header, position, &_tid, &_beg, &_end); if (_tid >= 0) { tv->curr_tid = _tid; tv->left_pos = _beg; } } tv->my_drawaln(tv, tv->curr_tid, tv->left_pos); tv->my_loop(tv); tv->my_destroy(tv); return EXIT_SUCCESS; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/kaln.c
.c
15,230
487
/* The MIT License Copyright (c) 2003-2006, 2008, 2009, by Heng Li <lh3lh3@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include <math.h> #include "kaln.h" #define FROM_M 0 #define FROM_I 1 #define FROM_D 2 typedef struct { int i, j; unsigned char ctype; } path_t; int aln_sm_blosum62[] = { /* A R N D C Q E G H I L K M F P S T W Y V * X */ 4,-1,-2,-2, 0,-1,-1, 0,-2,-1,-1,-1,-1,-2,-1, 1, 0,-3,-2, 0,-4, 0, -1, 5, 0,-2,-3, 1, 0,-2, 0,-3,-2, 2,-1,-3,-2,-1,-1,-3,-2,-3,-4,-1, -2, 0, 6, 1,-3, 0, 0, 0, 1,-3,-3, 0,-2,-3,-2, 1, 0,-4,-2,-3,-4,-1, -2,-2, 1, 6,-3, 0, 2,-1,-1,-3,-4,-1,-3,-3,-1, 0,-1,-4,-3,-3,-4,-1, 0,-3,-3,-3, 9,-3,-4,-3,-3,-1,-1,-3,-1,-2,-3,-1,-1,-2,-2,-1,-4,-2, -1, 1, 0, 0,-3, 5, 2,-2, 0,-3,-2, 1, 0,-3,-1, 0,-1,-2,-1,-2,-4,-1, -1, 0, 0, 2,-4, 2, 5,-2, 0,-3,-3, 1,-2,-3,-1, 0,-1,-3,-2,-2,-4,-1, 0,-2, 0,-1,-3,-2,-2, 6,-2,-4,-4,-2,-3,-3,-2, 0,-2,-2,-3,-3,-4,-1, -2, 0, 1,-1,-3, 0, 0,-2, 8,-3,-3,-1,-2,-1,-2,-1,-2,-2, 2,-3,-4,-1, -1,-3,-3,-3,-1,-3,-3,-4,-3, 4, 2,-3, 1, 0,-3,-2,-1,-3,-1, 3,-4,-1, -1,-2,-3,-4,-1,-2,-3,-4,-3, 2, 4,-2, 2, 0,-3,-2,-1,-2,-1, 1,-4,-1, -1, 2, 0,-1,-3, 1, 1,-2,-1,-3,-2, 5,-1,-3,-1, 0,-1,-3,-2,-2,-4,-1, -1,-1,-2,-3,-1, 0,-2,-3,-2, 1, 2,-1, 5, 0,-2,-1,-1,-1,-1, 1,-4,-1, -2,-3,-3,-3,-2,-3,-3,-3,-1, 0, 0,-3, 0, 6,-4,-2,-2, 1, 3,-1,-4,-1, -1,-2,-2,-1,-3,-1,-1,-2,-2,-3,-3,-1,-2,-4, 7,-1,-1,-4,-3,-2,-4,-2, 1,-1, 1, 0,-1, 0, 0, 0,-1,-2,-2, 0,-1,-2,-1, 4, 1,-3,-2,-2,-4, 0, 0,-1, 0,-1,-1,-1,-1,-2,-2,-1,-1,-1,-1,-2,-1, 1, 5,-2,-2, 0,-4, 0, -3,-3,-4,-4,-2,-2,-3,-2,-2,-3,-2,-3,-1, 1,-4,-3,-2,11, 2,-3,-4,-2, -2,-2,-2,-3,-2,-1,-2,-3, 2,-1,-1,-2,-1, 3,-3,-2,-2, 2, 7,-1,-4,-1, 0,-3,-3,-3,-1,-2,-2,-3,-3, 3, 1,-2, 1,-1,-2,-2, 0,-3,-1, 4,-4,-1, -4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4, 1,-4, 0,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-2, 0, 0,-2,-1,-1,-4,-1 }; int aln_sm_blast[] = { 1, -3, -3, -3, -2, -3, 1, -3, -3, -2, -3, -3, 1, -3, -2, -3, -3, -3, 1, -2, -2, -2, -2, -2, -2 }; int aln_sm_qual[] = { 0, -23, -23, -23, 0, -23, 0, -23, -23, 0, -23, -23, 0, -23, 0, -23, -23, -23, 0, 0, 0, 0, 0, 0, 0 }; ka_param_t ka_param_blast = { 5, 2, 5, 2, aln_sm_blast, 5, 50 }; ka_param_t ka_param_aa2aa = { 10, 2, 10, 2, aln_sm_blosum62, 22, 50 }; ka_param2_t ka_param2_qual = { 37, 11, 37, 11, 37, 11, 0, 0, aln_sm_qual, 5, 50 }; static uint32_t *ka_path2cigar32(const path_t *path, int path_len, int *n_cigar) { int i, n; uint32_t *cigar; unsigned char last_type; if (path_len == 0 || path == 0) { *n_cigar = 0; return 0; } last_type = path->ctype; for (i = n = 1; i < path_len; ++i) { if (last_type != path[i].ctype) ++n; last_type = path[i].ctype; } *n_cigar = n; cigar = (uint32_t*)calloc(*n_cigar, 4); cigar[0] = 1u << 4 | path[path_len-1].ctype; last_type = path[path_len-1].ctype; for (i = path_len - 2, n = 0; i >= 0; --i) { if (path[i].ctype == last_type) cigar[n] += 1u << 4; else { cigar[++n] = 1u << 4 | path[i].ctype; last_type = path[i].ctype; } } return cigar; } /***************************/ /* START OF common_align.c */ /***************************/ #define SET_INF(s) (s).M = (s).I = (s).D = MINOR_INF; #define set_M(MM, cur, p, sc) \ { \ if ((p)->M >= (p)->I) { \ if ((p)->M >= (p)->D) { \ (MM) = (p)->M + (sc); (cur)->Mt = FROM_M; \ } else { \ (MM) = (p)->D + (sc); (cur)->Mt = FROM_D; \ } \ } else { \ if ((p)->I > (p)->D) { \ (MM) = (p)->I + (sc); (cur)->Mt = FROM_I; \ } else { \ (MM) = (p)->D + (sc); (cur)->Mt = FROM_D; \ } \ } \ } #define set_I(II, cur, p) \ { \ if ((p)->M - gap_open > (p)->I) { \ (cur)->It = FROM_M; \ (II) = (p)->M - gap_open - gap_ext; \ } else { \ (cur)->It = FROM_I; \ (II) = (p)->I - gap_ext; \ } \ } #define set_end_I(II, cur, p) \ { \ if (gap_end_ext >= 0) { \ if ((p)->M - gap_end_open > (p)->I) { \ (cur)->It = FROM_M; \ (II) = (p)->M - gap_end_open - gap_end_ext; \ } else { \ (cur)->It = FROM_I; \ (II) = (p)->I - gap_end_ext; \ } \ } else set_I(II, cur, p); \ } #define set_D(DD, cur, p) \ { \ if ((p)->M - gap_open > (p)->D) { \ (cur)->Dt = FROM_M; \ (DD) = (p)->M - gap_open - gap_ext; \ } else { \ (cur)->Dt = FROM_D; \ (DD) = (p)->D - gap_ext; \ } \ } #define set_end_D(DD, cur, p) \ { \ if (gap_end_ext >= 0) { \ if ((p)->M - gap_end_open > (p)->D) { \ (cur)->Dt = FROM_M; \ (DD) = (p)->M - gap_end_open - gap_end_ext; \ } else { \ (cur)->Dt = FROM_D; \ (DD) = (p)->D - gap_end_ext; \ } \ } else set_D(DD, cur, p); \ } typedef struct { uint8_t Mt:3, It:2, Dt:3; } dpcell_t; typedef struct { int M, I, D; } dpscore_t; /*************************** * banded global alignment * ***************************/ uint32_t *ka_global_core(uint8_t *seq1, int len1, uint8_t *seq2, int len2, const ka_param_t *ap, int *_score, int *n_cigar) { int i, j; dpcell_t **dpcell, *q; dpscore_t *curr, *last, *s; int b1, b2, tmp_end; int *mat, end, max = 0; uint8_t type, ctype; uint32_t *cigar = 0; int gap_open, gap_ext, gap_end_open, gap_end_ext, b; int *score_matrix, N_MATRIX_ROW; /* initialize some align-related parameters. just for compatibility */ gap_open = ap->gap_open; gap_ext = ap->gap_ext; gap_end_open = ap->gap_end_open; gap_end_ext = ap->gap_end_ext; b = ap->band_width; score_matrix = ap->matrix; N_MATRIX_ROW = ap->row; if (n_cigar) *n_cigar = 0; if (len1 == 0 || len2 == 0) return 0; /* calculate b1 and b2 */ if (len1 > len2) { b1 = len1 - len2 + b; b2 = b; } else { b1 = b; b2 = len2 - len1 + b; } if (b1 > len1) b1 = len1; if (b2 > len2) b2 = len2; --seq1; --seq2; /* allocate memory */ end = (b1 + b2 <= len1)? (b1 + b2 + 1) : (len1 + 1); dpcell = (dpcell_t**)malloc(sizeof(dpcell_t*) * (len2 + 1)); for (j = 0; j <= len2; ++j) dpcell[j] = (dpcell_t*)malloc(sizeof(dpcell_t) * end); for (j = b2 + 1; j <= len2; ++j) dpcell[j] -= j - b2; curr = (dpscore_t*)malloc(sizeof(dpscore_t) * (len1 + 1)); last = (dpscore_t*)malloc(sizeof(dpscore_t) * (len1 + 1)); /* set first row */ SET_INF(*curr); curr->M = 0; for (i = 1, s = curr + 1; i < b1; ++i, ++s) { SET_INF(*s); set_end_D(s->D, dpcell[0] + i, s - 1); } s = curr; curr = last; last = s; /* core dynamic programming, part 1 */ tmp_end = (b2 < len2)? b2 : len2 - 1; for (j = 1; j <= tmp_end; ++j) { q = dpcell[j]; s = curr; SET_INF(*s); set_end_I(s->I, q, last); end = (j + b1 <= len1 + 1)? (j + b1 - 1) : len1; mat = score_matrix + seq2[j] * N_MATRIX_ROW; ++s; ++q; for (i = 1; i != end; ++i, ++s, ++q) { set_M(s->M, q, last + i - 1, mat[seq1[i]]); /* this will change s->M ! */ set_I(s->I, q, last + i); set_D(s->D, q, s - 1); } set_M(s->M, q, last + i - 1, mat[seq1[i]]); set_D(s->D, q, s - 1); if (j + b1 - 1 > len1) { /* bug fixed, 040227 */ set_end_I(s->I, q, last + i); } else s->I = MINOR_INF; s = curr; curr = last; last = s; } /* last row for part 1, use set_end_D() instead of set_D() */ if (j == len2 && b2 != len2 - 1) { q = dpcell[j]; s = curr; SET_INF(*s); set_end_I(s->I, q, last); end = (j + b1 <= len1 + 1)? (j + b1 - 1) : len1; mat = score_matrix + seq2[j] * N_MATRIX_ROW; ++s; ++q; for (i = 1; i != end; ++i, ++s, ++q) { set_M(s->M, q, last + i - 1, mat[seq1[i]]); /* this will change s->M ! */ set_I(s->I, q, last + i); set_end_D(s->D, q, s - 1); } set_M(s->M, q, last + i - 1, mat[seq1[i]]); set_end_D(s->D, q, s - 1); if (j + b1 - 1 > len1) { /* bug fixed, 040227 */ set_end_I(s->I, q, last + i); } else s->I = MINOR_INF; s = curr; curr = last; last = s; ++j; } /* core dynamic programming, part 2 */ for (; j <= len2 - b2 + 1; ++j) { SET_INF(curr[j - b2]); mat = score_matrix + seq2[j] * N_MATRIX_ROW; end = j + b1 - 1; for (i = j - b2 + 1, q = dpcell[j] + i, s = curr + i; i != end; ++i, ++s, ++q) { set_M(s->M, q, last + i - 1, mat[seq1[i]]); set_I(s->I, q, last + i); set_D(s->D, q, s - 1); } set_M(s->M, q, last + i - 1, mat[seq1[i]]); set_D(s->D, q, s - 1); s->I = MINOR_INF; s = curr; curr = last; last = s; } /* core dynamic programming, part 3 */ for (; j < len2; ++j) { SET_INF(curr[j - b2]); mat = score_matrix + seq2[j] * N_MATRIX_ROW; for (i = j - b2 + 1, q = dpcell[j] + i, s = curr + i; i < len1; ++i, ++s, ++q) { set_M(s->M, q, last + i - 1, mat[seq1[i]]); set_I(s->I, q, last + i); set_D(s->D, q, s - 1); } set_M(s->M, q, last + len1 - 1, mat[seq1[i]]); set_end_I(s->I, q, last + i); set_D(s->D, q, s - 1); s = curr; curr = last; last = s; } /* last row */ if (j == len2) { SET_INF(curr[j - b2]); mat = score_matrix + seq2[j] * N_MATRIX_ROW; for (i = j - b2 + 1, q = dpcell[j] + i, s = curr + i; i < len1; ++i, ++s, ++q) { set_M(s->M, q, last + i - 1, mat[seq1[i]]); set_I(s->I, q, last + i); set_end_D(s->D, q, s - 1); } set_M(s->M, q, last + len1 - 1, mat[seq1[i]]); set_end_I(s->I, q, last + i); set_end_D(s->D, q, s - 1); s = curr; curr = last; last = s; } *_score = last[len1].M; if (n_cigar) { /* backtrace */ path_t *p, *path = (path_t*)malloc(sizeof(path_t) * (len1 + len2 + 2)); i = len1; j = len2; q = dpcell[j] + i; s = last + len1; max = s->M; type = q->Mt; ctype = FROM_M; if (s->I > max) { max = s->I; type = q->It; ctype = FROM_I; } if (s->D > max) { max = s->D; type = q->Dt; ctype = FROM_D; } p = path; p->ctype = ctype; p->i = i; p->j = j; /* bug fixed 040408 */ ++p; do { switch (ctype) { case FROM_M: --i; --j; break; case FROM_I: --j; break; case FROM_D: --i; break; } q = dpcell[j] + i; ctype = type; switch (type) { case FROM_M: type = q->Mt; break; case FROM_I: type = q->It; break; case FROM_D: type = q->Dt; break; } p->ctype = ctype; p->i = i; p->j = j; ++p; } while (i || j); cigar = ka_path2cigar32(path, p - path - 1, n_cigar); free(path); } /* free memory */ for (j = b2 + 1; j <= len2; ++j) dpcell[j] += j - b2; for (j = 0; j <= len2; ++j) free(dpcell[j]); free(dpcell); free(curr); free(last); return cigar; } typedef struct { int M, I, D; } score_aux_t; #define MINUS_INF -0x40000000 // matrix: len2 rows and len1 columns int ka_global_score(const uint8_t *_seq1, int len1, const uint8_t *_seq2, int len2, const ka_param2_t *ap) { #define __score_aux(_p, _q0, _sc, _io, _ie, _do, _de) { \ int t1, t2; \ score_aux_t *_q; \ _q = _q0; \ _p->M = _q->M >= _q->I? _q->M : _q->I; \ _p->M = _p->M >= _q->D? _p->M : _q->D; \ _p->M += (_sc); \ ++_q; t1 = _q->M - _io - _ie; t2 = _q->I - _ie; _p->I = t1 >= t2? t1 : t2; \ _q = _p-1; t1 = _q->M - _do - _de; t2 = _q->D - _de; _p->D = t1 >= t2? t1 : t2; \ } int i, j, bw, scmat_size = ap->row, *scmat = ap->matrix, ret; const uint8_t *seq1, *seq2; score_aux_t *curr, *last, *swap; bw = abs(len1 - len2) + ap->band_width; i = len1 > len2? len1 : len2; if (bw > i + 1) bw = i + 1; seq1 = _seq1 - 1; seq2 = _seq2 - 1; curr = calloc(len1 + 2, sizeof(score_aux_t)); last = calloc(len1 + 2, sizeof(score_aux_t)); { // the zero-th row int x, end = len1; score_aux_t *p; j = 0; x = j + bw; end = len1 < x? len1 : x; // band end p = curr; p->M = 0; p->I = p->D = MINUS_INF; for (i = 1, p = &curr[1]; i <= end; ++i, ++p) p->M = p->I = MINUS_INF, p->D = -(ap->edo + ap->ede * i); p->M = p->I = p->D = MINUS_INF; swap = curr; curr = last; last = swap; } for (j = 1; j < len2; ++j) { int x, beg = 0, end = len1, *scrow, col_end; score_aux_t *p; x = j - bw; beg = 0 > x? 0 : x; // band start x = j + bw; end = len1 < x? len1 : x; // band end if (beg == 0) { // from zero-th column p = curr; p->M = p->D = MINUS_INF; p->I = -(ap->eio + ap->eie * j); ++beg; // then beg = 1 } scrow = scmat + seq2[j] * scmat_size; if (end == len1) col_end = 1, --end; else col_end = 0; for (i = beg, p = &curr[beg]; i <= end; ++i, ++p) __score_aux(p, &last[i-1], scrow[(int)seq1[i]], ap->iio, ap->iie, ap->ido, ap->ide); if (col_end) { __score_aux(p, &last[i-1], scrow[(int)seq1[i]], ap->eio, ap->eie, ap->ido, ap->ide); ++p; } p->M = p->I = p->D = MINUS_INF; // for (i = 0; i <= len1; ++i) printf("(%d,%d,%d) ", curr[i].M, curr[i].I, curr[i].D); putchar('\n'); swap = curr; curr = last; last = swap; } { // the last row int x, beg = 0, *scrow; score_aux_t *p; j = len2; x = j - bw; beg = 0 > x? 0 : x; // band start if (beg == 0) { // from zero-th column p = curr; p->M = p->D = MINUS_INF; p->I = -(ap->eio + ap->eie * j); ++beg; // then beg = 1 } scrow = scmat + seq2[j] * scmat_size; for (i = beg, p = &curr[beg]; i < len1; ++i, ++p) __score_aux(p, &last[i-1], scrow[(int)seq1[i]], ap->iio, ap->iie, ap->edo, ap->ede); __score_aux(p, &last[i-1], scrow[(int)seq1[i]], ap->eio, ap->eie, ap->edo, ap->ede); // for (i = 0; i <= len1; ++i) printf("(%d,%d,%d) ", curr[i].M, curr[i].I, curr[i].D); putchar('\n'); } ret = curr[len1].M >= curr[len1].I? curr[len1].M : curr[len1].I; ret = ret >= curr[len1].D? ret : curr[len1].D; free(curr); free(last); return ret; } #ifdef _MAIN int main(int argc, char *argv[]) { // int len1 = 35, len2 = 35; // uint8_t *seq1 = (uint8_t*)"\0\0\3\3\2\0\0\0\1\0\2\1\2\1\3\2\3\3\3\0\2\3\2\1\1\3\3\3\2\3\3\1\0\0\1"; // uint8_t *seq2 = (uint8_t*)"\0\0\3\3\2\0\0\0\1\0\2\1\2\1\3\2\3\3\3\0\2\3\2\1\1\3\3\3\2\3\3\1\0\1\0"; int len1 = 4, len2 = 4; uint8_t *seq1 = (uint8_t*)"\1\0\0\1"; uint8_t *seq2 = (uint8_t*)"\1\0\1\0"; int sc; // ka_global_core(seq1, 2, seq2, 1, &ka_param_qual, &sc, 0); sc = ka_global_score(seq1, len1, seq2, len2, &ka_param2_qual); printf("%d\n", sc); return 0; } #endif
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/kseq.h
.h
8,811
236
/* The MIT License Copyright (c) 2008, 2009, 2011 Attractive Chaos <attractor@live.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Last Modified: 05MAR2012 */ #ifndef AC_KSEQ_H #define AC_KSEQ_H #include <ctype.h> #include <string.h> #include <stdlib.h> #define KS_SEP_SPACE 0 // isspace(): \t, \n, \v, \f, \r #define KS_SEP_TAB 1 // isspace() && !' ' #define KS_SEP_LINE 2 // line separator: "\n" (Unix) or "\r\n" (Windows) #define KS_SEP_MAX 2 #define __KS_TYPE(type_t) \ typedef struct __kstream_t { \ unsigned char *buf; \ int begin, end, is_eof; \ type_t f; \ } kstream_t; #define ks_eof(ks) ((ks)->is_eof && (ks)->begin >= (ks)->end) #define ks_rewind(ks) ((ks)->is_eof = (ks)->begin = (ks)->end = 0) #define __KS_BASIC(type_t, __bufsize) \ static inline kstream_t *ks_init(type_t f) \ { \ kstream_t *ks = (kstream_t*)calloc(1, sizeof(kstream_t)); \ ks->f = f; \ ks->buf = (unsigned char*)malloc(__bufsize); \ return ks; \ } \ static inline void ks_destroy(kstream_t *ks) \ { \ if (ks) { \ free(ks->buf); \ free(ks); \ } \ } #define __KS_GETC(__read, __bufsize) \ static inline int ks_getc(kstream_t *ks) \ { \ if (ks->is_eof && ks->begin >= ks->end) return -1; \ if (ks->begin >= ks->end) { \ ks->begin = 0; \ ks->end = __read(ks->f, ks->buf, __bufsize); \ if (ks->end < __bufsize) ks->is_eof = 1; \ if (ks->end == 0) return -1; \ } \ return (int)ks->buf[ks->begin++]; \ } #ifndef KSTRING_T #define KSTRING_T kstring_t typedef struct __kstring_t { size_t l, m; char *s; } kstring_t; #endif #ifndef kroundup32 #define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x)) #endif #define __KS_GETUNTIL(__read, __bufsize) \ static int ks_getuntil2(kstream_t *ks, int delimiter, kstring_t *str, int *dret, int append) \ { \ if (dret) *dret = 0; \ str->l = append? str->l : 0; \ if (ks->begin >= ks->end && ks->is_eof) return -1; \ for (;;) { \ int i; \ if (ks->begin >= ks->end) { \ if (!ks->is_eof) { \ ks->begin = 0; \ ks->end = __read(ks->f, ks->buf, __bufsize); \ if (ks->end < __bufsize) ks->is_eof = 1; \ if (ks->end == 0) break; \ } else break; \ } \ if (delimiter == KS_SEP_LINE) { \ for (i = ks->begin; i < ks->end; ++i) \ if (ks->buf[i] == '\n') break; \ } else if (delimiter > KS_SEP_MAX) { \ for (i = ks->begin; i < ks->end; ++i) \ if (ks->buf[i] == delimiter) break; \ } else if (delimiter == KS_SEP_SPACE) { \ for (i = ks->begin; i < ks->end; ++i) \ if (isspace(ks->buf[i])) break; \ } else if (delimiter == KS_SEP_TAB) { \ for (i = ks->begin; i < ks->end; ++i) \ if (isspace(ks->buf[i]) && ks->buf[i] != ' ') break; \ } else i = 0; /* never come to here! */ \ if (str->m - str->l < (size_t)(i - ks->begin + 1)) { \ str->m = str->l + (i - ks->begin) + 1; \ kroundup32(str->m); \ str->s = (char*)realloc(str->s, str->m); \ } \ memcpy(str->s + str->l, ks->buf + ks->begin, i - ks->begin); \ str->l = str->l + (i - ks->begin); \ ks->begin = i + 1; \ if (i < ks->end) { \ if (dret) *dret = ks->buf[i]; \ break; \ } \ } \ if (str->s == 0) { \ str->m = 1; \ str->s = (char*)calloc(1, 1); \ } else if (delimiter == KS_SEP_LINE && str->l > 1 && str->s[str->l-1] == '\r') --str->l; \ str->s[str->l] = '\0'; \ return str->l; \ } \ static inline int ks_getuntil(kstream_t *ks, int delimiter, kstring_t *str, int *dret) \ { return ks_getuntil2(ks, delimiter, str, dret, 0); } #define KSTREAM_INIT(type_t, __read, __bufsize) \ __KS_TYPE(type_t) \ __KS_BASIC(type_t, __bufsize) \ __KS_GETC(__read, __bufsize) \ __KS_GETUNTIL(__read, __bufsize) #define kseq_rewind(ks) ((ks)->last_char = (ks)->f->is_eof = (ks)->f->begin = (ks)->f->end = 0) #define __KSEQ_BASIC(SCOPE, type_t) \ SCOPE kseq_t *kseq_init(type_t fd) \ { \ kseq_t *s = (kseq_t*)calloc(1, sizeof(kseq_t)); \ s->f = ks_init(fd); \ return s; \ } \ SCOPE void kseq_destroy(kseq_t *ks) \ { \ if (!ks) return; \ free(ks->name.s); free(ks->comment.s); free(ks->seq.s); free(ks->qual.s); \ ks_destroy(ks->f); \ free(ks); \ } /* Return value: >=0 length of the sequence (normal) -1 end-of-file -2 truncated quality string */ #define __KSEQ_READ(SCOPE) \ SCOPE int kseq_read(kseq_t *seq) \ { \ int c; \ kstream_t *ks = seq->f; \ if (seq->last_char == 0) { /* then jump to the next header line */ \ while ((c = ks_getc(ks)) != -1 && c != '>' && c != '@'); \ if (c == -1) return -1; /* end of file */ \ seq->last_char = c; \ } /* else: the first header char has been read in the previous call */ \ seq->comment.l = seq->seq.l = seq->qual.l = 0; /* reset all members */ \ if (ks_getuntil(ks, 0, &seq->name, &c) < 0) return -1; /* normal exit: EOF */ \ if (c != '\n') ks_getuntil(ks, KS_SEP_LINE, &seq->comment, 0); /* read FASTA/Q comment */ \ if (seq->seq.s == 0) { /* we can do this in the loop below, but that is slower */ \ seq->seq.m = 256; \ seq->seq.s = (char*)malloc(seq->seq.m); \ } \ while ((c = ks_getc(ks)) != -1 && c != '>' && c != '+' && c != '@') { \ if (c == '\n') continue; /* skip empty lines */ \ seq->seq.s[seq->seq.l++] = c; /* this is safe: we always have enough space for 1 char */ \ ks_getuntil2(ks, KS_SEP_LINE, &seq->seq, 0, 1); /* read the rest of the line */ \ } \ if (c == '>' || c == '@') seq->last_char = c; /* the first header char has been read */ \ if (seq->seq.l + 1 >= seq->seq.m) { /* seq->seq.s[seq->seq.l] below may be out of boundary */ \ seq->seq.m = seq->seq.l + 2; \ kroundup32(seq->seq.m); /* rounded to the next closest 2^k */ \ seq->seq.s = (char*)realloc(seq->seq.s, seq->seq.m); \ } \ seq->seq.s[seq->seq.l] = 0; /* null terminated string */ \ if (c != '+') return seq->seq.l; /* FASTA */ \ if (seq->qual.m < seq->seq.m) { /* allocate memory for qual in case insufficient */ \ seq->qual.m = seq->seq.m; \ seq->qual.s = (char*)realloc(seq->qual.s, seq->qual.m); \ } \ while ((c = ks_getc(ks)) != -1 && c != '\n'); /* skip the rest of '+' line */ \ if (c == -1) return -2; /* error: no quality string */ \ while (ks_getuntil2(ks, KS_SEP_LINE, &seq->qual, 0, 1) >= 0 && seq->qual.l < seq->seq.l); \ seq->last_char = 0; /* we have not come to the next header line */ \ if (seq->seq.l != seq->qual.l) return -2; /* error: qual string is of a different length */ \ return seq->seq.l; \ } #define __KSEQ_TYPE(type_t) \ typedef struct { \ kstring_t name, comment, seq, qual; \ int last_char; \ kstream_t *f; \ } kseq_t; #define KSEQ_INIT2(SCOPE, type_t, __read) \ KSTREAM_INIT(type_t, __read, 16384) \ __KSEQ_TYPE(type_t) \ __KSEQ_BASIC(SCOPE, type_t) \ __KSEQ_READ(SCOPE) #define KSEQ_INIT(type_t, __read) KSEQ_INIT2(static, type_t, __read) #define KSEQ_DECLARE(type_t) \ __KS_TYPE(type_t) \ __KSEQ_TYPE(type_t) \ extern kseq_t *kseq_init(type_t fd); \ void kseq_destroy(kseq_t *ks); \ int kseq_read(kseq_t *seq); #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/cut_target.c
.c
5,667
194
#include <unistd.h> #include <stdlib.h> #include <string.h> #include "bam.h" #include "errmod.h" #include "faidx.h" #define ERR_DEP 0.83f typedef struct { int e[2][3], p[2][2]; } score_param_t; /* Note that although the two matrics have 10 parameters in total, only 4 * (probably 3) are free. Changing the scoring matrices in a sort of symmetric * way will not change the result. */ static score_param_t g_param = { {{0,0,0},{-4,1,6}}, {{0,-14000}, {0,0}} }; typedef struct { int min_baseQ, tid, max_bases; uint16_t *bases; bamFile fp; bam_header_t *h; char *ref; faidx_t *fai; errmod_t *em; } ct_t; static uint16_t gencns(ct_t *g, int n, const bam_pileup1_t *plp) { int i, j, ret, tmp, k, sum[4], qual; float q[16]; if (n > g->max_bases) { // enlarge g->bases g->max_bases = n; kroundup32(g->max_bases); g->bases = realloc(g->bases, g->max_bases * 2); } for (i = k = 0; i < n; ++i) { const bam_pileup1_t *p = plp + i; uint8_t *seq; int q, baseQ, b; if (p->is_refskip || p->is_del) continue; baseQ = bam1_qual(p->b)[p->qpos]; if (baseQ < g->min_baseQ) continue; seq = bam1_seq(p->b); b = bam_nt16_nt4_table[bam1_seqi(seq, p->qpos)]; if (b > 3) continue; q = baseQ < p->b->core.qual? baseQ : p->b->core.qual; if (q < 4) q = 4; if (q > 63) q = 63; g->bases[k++] = q<<5 | bam1_strand(p->b)<<4 | b; } if (k == 0) return 0; errmod_cal(g->em, k, 4, g->bases, q); for (i = 0; i < 4; ++i) sum[i] = (int)(q[i<<2|i] + .499) << 2 | i; for (i = 1; i < 4; ++i) // insertion sort for (j = i; j > 0 && sum[j] < sum[j-1]; --j) tmp = sum[j], sum[j] = sum[j-1], sum[j-1] = tmp; qual = (sum[1]>>2) - (sum[0]>>2); k = k < 256? k : 255; ret = (qual < 63? qual : 63) << 2 | (sum[0]&3); return ret<<8|k; } static void process_cns(bam_header_t *h, int tid, int l, uint16_t *cns) { int i, f[2][2], *prev, *curr, *swap_tmp, s; uint8_t *b; // backtrack array b = calloc(l, 1); f[0][0] = f[0][1] = 0; prev = f[0]; curr = f[1]; // fill the backtrack matrix for (i = 0; i < l; ++i) { int c = (cns[i] == 0)? 0 : (cns[i]>>8 == 0)? 1 : 2; int tmp0, tmp1; // compute f[0] tmp0 = prev[0] + g_param.e[0][c] + g_param.p[0][0]; // (s[i+1],s[i])=(0,0) tmp1 = prev[1] + g_param.e[0][c] + g_param.p[1][0]; // (0,1) if (tmp0 > tmp1) curr[0] = tmp0, b[i] = 0; else curr[0] = tmp1, b[i] = 1; // compute f[1] tmp0 = prev[0] + g_param.e[1][c] + g_param.p[0][1]; // (s[i+1],s[i])=(1,0) tmp1 = prev[1] + g_param.e[1][c] + g_param.p[1][1]; // (1,1) if (tmp0 > tmp1) curr[1] = tmp0, b[i] |= 0<<1; else curr[1] = tmp1, b[i] |= 1<<1; // swap swap_tmp = prev; prev = curr; curr = swap_tmp; } // backtrack s = prev[0] > prev[1]? 0 : 1; for (i = l - 1; i > 0; --i) { b[i] |= s<<2; s = b[i]>>s&1; } // print for (i = 0, s = -1; i <= l; ++i) { if (i == l || ((b[i]>>2&3) == 0 && s >= 0)) { if (s >= 0) { int j; printf("%s:%d-%d\t0\t%s\t%d\t60\t%dM\t*\t0\t0\t", h->target_name[tid], s+1, i, h->target_name[tid], s+1, i-s); for (j = s; j < i; ++j) { int c = cns[j]>>8; if (c == 0) putchar('N'); else putchar("ACGT"[c&3]); } putchar('\t'); for (j = s; j < i; ++j) putchar(33 + (cns[j]>>8>>2)); putchar('\n'); } //if (s >= 0) printf("%s\t%d\t%d\t%d\n", h->target_name[tid], s, i, i - s); s = -1; } else if ((b[i]>>2&3) && s < 0) s = i; } free(b); } static int read_aln(void *data, bam1_t *b) { extern int bam_prob_realn_core(bam1_t *b, const char *ref, int flag); ct_t *g = (ct_t*)data; int ret, len; ret = bam_read1(g->fp, b); if (ret >= 0 && g->fai && b->core.tid >= 0 && (b->core.flag&4) == 0) { if (b->core.tid != g->tid) { // then load the sequence free(g->ref); g->ref = fai_fetch(g->fai, g->h->target_name[b->core.tid], &len); g->tid = b->core.tid; } bam_prob_realn_core(b, g->ref, 1<<1|1); } return ret; } int main_cut_target(int argc, char *argv[]) { int c, tid, pos, n, lasttid = -1, lastpos = -1, l, max_l; const bam_pileup1_t *p; bam_plp_t plp; uint16_t *cns; ct_t g; memset(&g, 0, sizeof(ct_t)); g.min_baseQ = 13; g.tid = -1; while ((c = getopt(argc, argv, "f:Q:i:o:0:1:2:")) >= 0) { switch (c) { case 'Q': g.min_baseQ = atoi(optarg); break; // quality cutoff case 'i': g_param.p[0][1] = -atoi(optarg); break; // 0->1 transition (in) PENALTY case '0': g_param.e[1][0] = atoi(optarg); break; // emission SCORE case '1': g_param.e[1][1] = atoi(optarg); break; case '2': g_param.e[1][2] = atoi(optarg); break; case 'f': g.fai = fai_load(optarg); if (g.fai == 0) fprintf(stderr, "[%s] fail to load the fasta index.\n", __func__); break; } } if (argc == optind) { fprintf(stderr, "Usage: samtools targetcut [-Q minQ] [-i inPen] [-0 em0] [-1 em1] [-2 em2] [-f ref] <in.bam>\n"); return 1; } l = max_l = 0; cns = 0; g.fp = strcmp(argv[optind], "-")? bam_open(argv[optind], "r") : bam_dopen(fileno(stdin), "r"); g.h = bam_header_read(g.fp); g.em = errmod_init(1 - ERR_DEP); plp = bam_plp_init(read_aln, &g); while ((p = bam_plp_auto(plp, &tid, &pos, &n)) != 0) { if (tid < 0) break; if (tid != lasttid) { // change of chromosome if (cns) process_cns(g.h, lasttid, l, cns); if (max_l < g.h->target_len[tid]) { max_l = g.h->target_len[tid]; kroundup32(max_l); cns = realloc(cns, max_l * 2); } l = g.h->target_len[tid]; memset(cns, 0, max_l * 2); lasttid = tid; } cns[pos] = gencns(&g, n, p); lastpos = pos; } process_cns(g.h, lasttid, l, cns); free(cns); bam_header_destroy(g.h); bam_plp_destroy(plp); bam_close(g.fp); if (g.fai) { fai_destroy(g.fai); free(g.ref); } errmod_destroy(g.em); free(g.bases); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/klist.h
.h
3,472
97
#ifndef _LH3_KLIST_H #define _LH3_KLIST_H #include <stdlib.h> #define KMEMPOOL_INIT(name, kmptype_t, kmpfree_f) \ typedef struct { \ size_t cnt, n, max; \ kmptype_t **buf; \ } kmp_##name##_t; \ static inline kmp_##name##_t *kmp_init_##name() { \ return calloc(1, sizeof(kmp_##name##_t)); \ } \ static inline void kmp_destroy_##name(kmp_##name##_t *mp) { \ size_t k; \ for (k = 0; k < mp->n; ++k) { \ kmpfree_f(mp->buf[k]); free(mp->buf[k]); \ } \ free(mp->buf); free(mp); \ } \ static inline kmptype_t *kmp_alloc_##name(kmp_##name##_t *mp) { \ ++mp->cnt; \ if (mp->n == 0) return calloc(1, sizeof(kmptype_t)); \ return mp->buf[--mp->n]; \ } \ static inline void kmp_free_##name(kmp_##name##_t *mp, kmptype_t *p) { \ --mp->cnt; \ if (mp->n == mp->max) { \ mp->max = mp->max? mp->max<<1 : 16; \ mp->buf = realloc(mp->buf, sizeof(void*) * mp->max); \ } \ mp->buf[mp->n++] = p; \ } #define kmempool_t(name) kmp_##name##_t #define kmp_init(name) kmp_init_##name() #define kmp_destroy(name, mp) kmp_destroy_##name(mp) #define kmp_alloc(name, mp) kmp_alloc_##name(mp) #define kmp_free(name, mp, p) kmp_free_##name(mp, p) #define KLIST_INIT(name, kltype_t, kmpfree_t) \ struct __kl1_##name { \ kltype_t data; \ struct __kl1_##name *next; \ }; \ typedef struct __kl1_##name kl1_##name; \ KMEMPOOL_INIT(name, kl1_##name, kmpfree_t) \ typedef struct { \ kl1_##name *head, *tail; \ kmp_##name##_t *mp; \ size_t size; \ } kl_##name##_t; \ static inline kl_##name##_t *kl_init_##name() { \ kl_##name##_t *kl = calloc(1, sizeof(kl_##name##_t)); \ kl->mp = kmp_init(name); \ kl->head = kl->tail = kmp_alloc(name, kl->mp); \ kl->head->next = 0; \ return kl; \ } \ static inline void kl_destroy_##name(kl_##name##_t *kl) { \ kl1_##name *p; \ for (p = kl->head; p != kl->tail; p = p->next) \ kmp_free(name, kl->mp, p); \ kmp_free(name, kl->mp, p); \ kmp_destroy(name, kl->mp); \ free(kl); \ } \ static inline kltype_t *kl_pushp_##name(kl_##name##_t *kl) { \ kl1_##name *q, *p = kmp_alloc(name, kl->mp); \ q = kl->tail; p->next = 0; kl->tail->next = p; kl->tail = p; \ ++kl->size; \ return &q->data; \ } \ static inline int kl_shift_##name(kl_##name##_t *kl, kltype_t *d) { \ kl1_##name *p; \ if (kl->head->next == 0) return -1; \ --kl->size; \ p = kl->head; kl->head = kl->head->next; \ if (d) *d = p->data; \ kmp_free(name, kl->mp, p); \ return 0; \ } #define kliter_t(name) kl1_##name #define klist_t(name) kl_##name##_t #define kl_val(iter) ((iter)->data) #define kl_next(iter) ((iter)->next) #define kl_begin(kl) ((kl)->head) #define kl_end(kl) ((kl)->tail) #define kl_init(name) kl_init_##name() #define kl_destroy(name, kl) kl_destroy_##name(kl) #define kl_pushp(name, kl) kl_pushp_##name(kl) #define kl_shift(name, kl, d) kl_shift_##name(kl, d) #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/phase.c
.c
20,819
688
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdint.h> #include <math.h> #include <zlib.h> #include "bam.h" #include "errmod.h" #include "kseq.h" KSTREAM_INIT(gzFile, gzread, 16384) #define MAX_VARS 256 #define FLIP_PENALTY 2 #define FLIP_THRES 4 #define MASK_THRES 3 #define FLAG_FIX_CHIMERA 0x1 #define FLAG_LIST_EXCL 0x4 #define FLAG_DROP_AMBI 0x8 typedef struct { // configurations, initialized in the main function int flag, k, min_baseQ, min_varLOD, max_depth; // other global variables int vpos_shift; bamFile fp; char *pre; bamFile out[3]; // alignment queue int n, m; bam1_t **b; } phaseg_t; typedef struct { int8_t seq[MAX_VARS]; // TODO: change to dynamic memory allocation! int vpos, beg, end; uint32_t vlen:16, single:1, flip:1, phase:1, phased:1, ambig:1; uint32_t in:16, out:16; // in-phase and out-phase } frag_t, *frag_p; #define rseq_lt(a,b) ((a)->vpos < (b)->vpos) #include "khash.h" KHASH_SET_INIT_INT64(set64) KHASH_MAP_INIT_INT64(64, frag_t) typedef khash_t(64) nseq_t; #include "ksort.h" KSORT_INIT(rseq, frag_p, rseq_lt) static char nt16_nt4_table[] = { 4, 0, 1, 4, 2, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4 }; static inline uint64_t X31_hash_string(const char *s) { uint64_t h = *s; if (h) for (++s ; *s; ++s) h = (h << 5) - h + *s; return h; } static void count1(int l, const uint8_t *seq, int *cnt) { int i, j, n_ambi; uint32_t z, x; if (seq[l-1] == 0) return; // do nothing is the last base is ambiguous for (i = n_ambi = 0; i < l; ++i) // collect ambiguous bases if (seq[i] == 0) ++n_ambi; if (l - n_ambi <= 1) return; // only one SNP for (x = 0; x < 1u<<n_ambi; ++x) { // count for (i = j = 0, z = 0; i < l; ++i) { int c; if (seq[i]) c = seq[i] - 1; else { c = x>>j&1; ++j; } z = z<<1 | c; } ++cnt[z]; } } static int **count_all(int l, int vpos, nseq_t *hash) { khint_t k; int i, j, **cnt; uint8_t *seq; seq = calloc(l, 1); cnt = calloc(vpos, sizeof(void*)); for (i = 0; i < vpos; ++i) cnt[i] = calloc(1<<l, sizeof(int)); for (k = 0; k < kh_end(hash); ++k) { if (kh_exist(hash, k)) { frag_t *f = &kh_val(hash, k); if (f->vpos >= vpos || f->single) continue; // out of region; or singleton if (f->vlen == 1) { // such reads should be flagged as deleted previously if everything is right f->single = 1; continue; } for (j = 1; j < f->vlen; ++j) { for (i = 0; i < l; ++i) seq[i] = j < l - 1 - i? 0 : f->seq[j - (l - 1 - i)]; count1(l, seq, cnt[f->vpos + j]); } } } free(seq); return cnt; } // phasing static int8_t *dynaprog(int l, int vpos, int **w) { int *f[2], *curr, *prev, max, i; int8_t **b, *h = 0; uint32_t x, z = 1u<<(l-1), mask = (1u<<l) - 1; f[0] = calloc(z, sizeof(int)); f[1] = calloc(z, sizeof(int)); b = calloc(vpos, sizeof(void*)); prev = f[0]; curr = f[1]; // fill the backtrack matrix for (i = 0; i < vpos; ++i) { int *wi = w[i], *tmp; int8_t *bi; bi = b[i] = calloc(z, 1); /* In the following, x is the current state, which is the * lexicographically smaller local haplotype. xc is the complement of * x, or the larger local haplotype; y0 and y1 are the two predecessors * of x. */ for (x = 0; x < z; ++x) { // x0 is the smaller uint32_t y0, y1, xc; int c0, c1; xc = ~x&mask; y0 = x>>1; y1 = xc>>1; c0 = prev[y0] + wi[x] + wi[xc]; c1 = prev[y1] + wi[x] + wi[xc]; if (c0 > c1) bi[x] = 0, curr[x] = c0; else bi[x] = 1, curr[x] = c1; } tmp = prev; prev = curr; curr = tmp; // swap } { // backtrack uint32_t max_x = 0; int which = 0; h = calloc(vpos, 1); for (x = 0, max = 0, max_x = 0; x < z; ++x) if (prev[x] > max) max = prev[x], max_x = x; for (i = vpos - 1, x = max_x; i >= 0; --i) { h[i] = which? (~x&1) : (x&1); which = b[i][x]? !which : which; x = b[i][x]? (~x&mask)>>1 : x>>1; } } // free for (i = 0; i < vpos; ++i) free(b[i]); free(f[0]); free(f[1]); free(b); return h; } // phase each fragment static uint64_t *fragphase(int vpos, const int8_t *path, nseq_t *hash, int flip) { khint_t k; uint64_t *pcnt; uint32_t *left, *rght, max; left = rght = 0; max = 0; pcnt = calloc(vpos, 8); for (k = 0; k < kh_end(hash); ++k) { if (kh_exist(hash, k)) { int i, c[2]; frag_t *f = &kh_val(hash, k); if (f->vpos >= vpos) continue; // get the phase c[0] = c[1] = 0; for (i = 0; i < f->vlen; ++i) { if (f->seq[i] == 0) continue; ++c[f->seq[i] == path[f->vpos + i] + 1? 0 : 1]; } f->phase = c[0] > c[1]? 0 : 1; f->in = c[f->phase]; f->out = c[1 - f->phase]; f->phased = f->in == f->out? 0 : 1; f->ambig = (f->in && f->out && f->out < 3 && f->in <= f->out + 1)? 1 : 0; // fix chimera f->flip = 0; if (flip && c[0] >= 3 && c[1] >= 3) { int sum[2], m, mi, md; if (f->vlen > max) { // enlarge the array max = f->vlen; kroundup32(max); left = realloc(left, max * 4); rght = realloc(rght, max * 4); } for (i = 0, sum[0] = sum[1] = 0; i < f->vlen; ++i) { // get left counts if (f->seq[i]) { int c = f->phase? 2 - f->seq[i] : f->seq[i] - 1; ++sum[c == path[f->vpos + i]? 0 : 1]; } left[i] = sum[1]<<16 | sum[0]; } for (i = f->vlen - 1, sum[0] = sum[1] = 0; i >= 0; --i) { // get right counts if (f->seq[i]) { int c = f->phase? 2 - f->seq[i] : f->seq[i] - 1; ++sum[c == path[f->vpos + i]? 0 : 1]; } rght[i] = sum[1]<<16 | sum[0]; } // find the best flip point for (i = m = 0, mi = -1, md = -1; i < f->vlen - 1; ++i) { int a[2]; a[0] = (left[i]&0xffff) + (rght[i+1]>>16&0xffff) - (rght[i+1]&0xffff) * FLIP_PENALTY; a[1] = (left[i]>>16&0xffff) + (rght[i+1]&0xffff) - (rght[i+1]>>16&0xffff) * FLIP_PENALTY; if (a[0] > a[1]) { if (a[0] > m) m = a[0], md = 0, mi = i; } else { if (a[1] > m) m = a[1], md = 1, mi = i; } } if (m - c[0] >= FLIP_THRES && m - c[1] >= FLIP_THRES) { // then flip f->flip = 1; if (md == 0) { // flip the tail for (i = mi + 1; i < f->vlen; ++i) if (f->seq[i] == 1) f->seq[i] = 2; else if (f->seq[i] == 2) f->seq[i] = 1; } else { // flip the head for (i = 0; i <= mi; ++i) if (f->seq[i] == 1) f->seq[i] = 2; else if (f->seq[i] == 2) f->seq[i] = 1; } } } // update pcnt[] if (!f->single) { for (i = 0; i < f->vlen; ++i) { int c; if (f->seq[i] == 0) continue; c = f->phase? 2 - f->seq[i] : f->seq[i] - 1; if (c == path[f->vpos + i]) { if (f->phase == 0) ++pcnt[f->vpos + i]; else pcnt[f->vpos + i] += 1ull<<32; } else { if (f->phase == 0) pcnt[f->vpos + i] += 1<<16; else pcnt[f->vpos + i] += 1ull<<48; } } } } } free(left); free(rght); return pcnt; } static uint64_t *genmask(int vpos, const uint64_t *pcnt, int *_n) { int i, max = 0, max_i = -1, m = 0, n = 0, beg = 0, score = 0; uint64_t *list = 0; for (i = 0; i < vpos; ++i) { uint64_t x = pcnt[i]; int c[4], pre = score, s; c[0] = x&0xffff; c[1] = x>>16&0xffff; c[2] = x>>32&0xffff; c[3] = x>>48&0xffff; s = (c[1] + c[3] == 0)? -(c[0] + c[2]) : (c[1] + c[3] - 1); if (c[3] > c[2]) s += c[3] - c[2]; if (c[1] > c[0]) s += c[1] - c[0]; score += s; if (score < 0) score = 0; if (pre == 0 && score > 0) beg = i; // change from zero to non-zero if ((i == vpos - 1 || score == 0) && max >= MASK_THRES) { if (n == m) { m = m? m<<1 : 4; list = realloc(list, m * 8); } list[n++] = (uint64_t)beg<<32 | max_i; i = max_i; // reset i to max_i score = 0; } else if (score > max) max = score, max_i = i; if (score == 0) max = 0; } *_n = n; return list; } // trim heading and tailing ambiguous bases; mark deleted and remove sequence static int clean_seqs(int vpos, nseq_t *hash) { khint_t k; int ret = 0; for (k = 0; k < kh_end(hash); ++k) { if (kh_exist(hash, k)) { frag_t *f = &kh_val(hash, k); int beg, end, i; if (f->vpos >= vpos) { ret = 1; continue; } for (i = 0; i < f->vlen; ++i) if (f->seq[i] != 0) break; beg = i; for (i = f->vlen - 1; i >= 0; --i) if (f->seq[i] != 0) break; end = i + 1; if (end - beg <= 0) kh_del(64, hash, k); else { if (beg != 0) memmove(f->seq, f->seq + beg, end - beg); f->vpos += beg; f->vlen = end - beg; f->single = f->vlen == 1? 1 : 0; } } } return ret; } static void dump_aln(phaseg_t *g, int min_pos, const nseq_t *hash) { int i, is_flip, drop_ambi; drop_ambi = g->flag & FLAG_DROP_AMBI; is_flip = (drand48() < 0.5); for (i = 0; i < g->n; ++i) { int end, which; uint64_t key; khint_t k; bam1_t *b = g->b[i]; key = X31_hash_string(bam1_qname(b)); end = bam_calend(&b->core, bam1_cigar(b)); if (end > min_pos) break; k = kh_get(64, hash, key); if (k == kh_end(hash)) which = 3; else { frag_t *f = &kh_val(hash, k); if (f->ambig) which = drop_ambi? 2 : 3; else if (f->phased && f->flip) which = 2; else if (f->phased == 0) which = 3; else { // phased and not flipped char c = 'Y'; which = f->phase; bam_aux_append(b, "ZP", 'A', 1, (uint8_t*)&c); } if (which < 2 && is_flip) which = 1 - which; // increase the randomness } if (which == 3) which = (drand48() < 0.5); bam_write1(g->out[which], b); bam_destroy1(b); g->b[i] = 0; } memmove(g->b, g->b + i, (g->n - i) * sizeof(void*)); g->n -= i; } static int phase(phaseg_t *g, const char *chr, int vpos, uint64_t *cns, nseq_t *hash) { int i, j, n_seqs = kh_size(hash), n_masked = 0, min_pos; khint_t k; frag_t **seqs; int8_t *path, *sitemask; uint64_t *pcnt, *regmask; if (vpos == 0) return 0; i = clean_seqs(vpos, hash); // i is true if hash has an element with its vpos >= vpos min_pos = i? cns[vpos]>>32 : 0x7fffffff; if (vpos == 1) { printf("PS\t%s\t%d\t%d\n", chr, (int)(cns[0]>>32) + 1, (int)(cns[0]>>32) + 1); printf("M0\t%s\t%d\t%d\t%c\t%c\t%d\t0\t0\t0\t0\n//\n", chr, (int)(cns[0]>>32) + 1, (int)(cns[0]>>32) + 1, "ACGTX"[cns[0]&3], "ACGTX"[cns[0]>>16&3], g->vpos_shift + 1); for (k = 0; k < kh_end(hash); ++k) { if (kh_exist(hash, k)) { frag_t *f = &kh_val(hash, k); if (f->vpos) continue; f->flip = 0; if (f->seq[0] == 0) f->phased = 0; else f->phased = 1, f->phase = f->seq[0] - 1; } } dump_aln(g, min_pos, hash); ++g->vpos_shift; return 1; } { // phase int **cnt; uint64_t *mask; printf("PS\t%s\t%d\t%d\n", chr, (int)(cns[0]>>32) + 1, (int)(cns[vpos-1]>>32) + 1); sitemask = calloc(vpos, 1); cnt = count_all(g->k, vpos, hash); path = dynaprog(g->k, vpos, cnt); for (i = 0; i < vpos; ++i) free(cnt[i]); free(cnt); pcnt = fragphase(vpos, path, hash, 0); // do not fix chimeras when masking mask = genmask(vpos, pcnt, &n_masked); regmask = calloc(n_masked, 8); for (i = 0; i < n_masked; ++i) { regmask[i] = cns[mask[i]>>32]>>32<<32 | cns[(uint32_t)mask[i]]>>32; for (j = mask[i]>>32; j <= (int32_t)mask[i]; ++j) sitemask[j] = 1; } free(mask); if (g->flag & FLAG_FIX_CHIMERA) { free(pcnt); pcnt = fragphase(vpos, path, hash, 1); } } for (i = 0; i < n_masked; ++i) printf("FL\t%s\t%d\t%d\n", chr, (int)(regmask[i]>>32) + 1, (int)regmask[i] + 1); for (i = 0; i < vpos; ++i) { uint64_t x = pcnt[i]; int8_t c[2]; c[0] = (cns[i]&0xffff)>>2 == 0? 4 : (cns[i]&3); c[1] = (cns[i]>>16&0xffff)>>2 == 0? 4 : (cns[i]>>16&3); printf("M%d\t%s\t%d\t%d\t%c\t%c\t%d\t%d\t%d\t%d\t%d\n", sitemask[i]+1, chr, (int)(cns[0]>>32) + 1, (int)(cns[i]>>32) + 1, "ACGTX"[c[path[i]]], "ACGTX"[c[1-path[i]]], i + g->vpos_shift + 1, (int)(x&0xffff), (int)(x>>16&0xffff), (int)(x>>32&0xffff), (int)(x>>48&0xffff)); } free(path); free(pcnt); free(regmask); free(sitemask); seqs = calloc(n_seqs, sizeof(void*)); for (k = 0, i = 0; k < kh_end(hash); ++k) if (kh_exist(hash, k) && kh_val(hash, k).vpos < vpos && !kh_val(hash, k).single) seqs[i++] = &kh_val(hash, k); n_seqs = i; ks_introsort_rseq(n_seqs, seqs); for (i = 0; i < n_seqs; ++i) { frag_t *f = seqs[i]; printf("EV\t0\t%s\t%d\t40\t%dM\t*\t0\t0\t", chr, f->vpos + 1 + g->vpos_shift, f->vlen); for (j = 0; j < f->vlen; ++j) { uint32_t c = cns[f->vpos + j]; if (f->seq[j] == 0) putchar('N'); else putchar("ACGT"[f->seq[j] == 1? (c&3) : (c>>16&3)]); } printf("\t*\tYP:i:%d\tYF:i:%d\tYI:i:%d\tYO:i:%d\tYS:i:%d\n", f->phase, f->flip, f->in, f->out, f->beg+1); } free(seqs); printf("//\n"); fflush(stdout); g->vpos_shift += vpos; dump_aln(g, min_pos, hash); return vpos; } static void update_vpos(int vpos, nseq_t *hash) { khint_t k; for (k = 0; k < kh_end(hash); ++k) { if (kh_exist(hash, k)) { frag_t *f = &kh_val(hash, k); if (f->vpos < vpos) kh_del(64, hash, k); // TODO: if frag_t::seq is allocated dynamically, free it else f->vpos -= vpos; } } } static nseq_t *shrink_hash(nseq_t *hash) // TODO: to implement { return hash; } static int readaln(void *data, bam1_t *b) { phaseg_t *g = (phaseg_t*)data; int ret; ret = bam_read1(g->fp, b); if (ret < 0) return ret; if (!(b->core.flag & (BAM_FUNMAP|BAM_FSECONDARY|BAM_FQCFAIL|BAM_FDUP)) && g->pre) { if (g->n == g->m) { g->m = g->m? g->m<<1 : 16; g->b = realloc(g->b, g->m * sizeof(void*)); } g->b[g->n++] = bam_dup1(b); } return ret; } static khash_t(set64) *loadpos(const char *fn, bam_header_t *h) { gzFile fp; kstream_t *ks; int ret, dret; kstring_t *str; khash_t(set64) *hash; hash = kh_init(set64); str = calloc(1, sizeof(kstring_t)); fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r"); ks = ks_init(fp); while (ks_getuntil(ks, 0, str, &dret) >= 0) { int tid = bam_get_tid(h, str->s); if (tid >= 0 && dret != '\n') { if (ks_getuntil(ks, 0, str, &dret) >= 0) { uint64_t x = (uint64_t)tid<<32 | (atoi(str->s) - 1); kh_put(set64, hash, x, &ret); } else break; } if (dret != '\n') while ((dret = ks_getc(ks)) > 0 && dret != '\n'); if (dret < 0) break; } ks_destroy(ks); gzclose(fp); free(str->s); free(str); return hash; } static int gl2cns(float q[16]) { int i, j, min_ij; float min, min2; min = min2 = 1e30; min_ij = -1; for (i = 0; i < 4; ++i) { for (j = i; j < 4; ++j) { if (q[i<<2|j] < min) min_ij = i<<2|j, min2 = min, min = q[i<<2|j]; else if (q[i<<2|j] < min2) min2 = q[i<<2|j]; } } return (min_ij>>2&3) == (min_ij&3)? 0 : 1<<18 | (min_ij>>2&3)<<16 | (min_ij&3) | (int)(min2 - min + .499) << 2; } int main_phase(int argc, char *argv[]) { extern void bam_init_header_hash(bam_header_t *header); int c, tid, pos, vpos = 0, n, lasttid = -1, max_vpos = 0; const bam_pileup1_t *plp; bam_plp_t iter; bam_header_t *h; nseq_t *seqs; uint64_t *cns = 0; phaseg_t g; char *fn_list = 0; khash_t(set64) *set = 0; errmod_t *em; uint16_t *bases; memset(&g, 0, sizeof(phaseg_t)); g.flag = FLAG_FIX_CHIMERA; g.min_varLOD = 37; g.k = 13; g.min_baseQ = 13; g.max_depth = 256; while ((c = getopt(argc, argv, "Q:eFq:k:b:l:D:A:")) >= 0) { switch (c) { case 'D': g.max_depth = atoi(optarg); break; case 'q': g.min_varLOD = atoi(optarg); break; case 'Q': g.min_baseQ = atoi(optarg); break; case 'k': g.k = atoi(optarg); break; case 'F': g.flag &= ~FLAG_FIX_CHIMERA; break; case 'e': g.flag |= FLAG_LIST_EXCL; break; case 'A': g.flag |= FLAG_DROP_AMBI; break; case 'b': g.pre = strdup(optarg); break; case 'l': fn_list = strdup(optarg); break; } } if (argc == optind) { fprintf(stderr, "\n"); fprintf(stderr, "Usage: samtools phase [options] <in.bam>\n\n"); fprintf(stderr, "Options: -k INT block length [%d]\n", g.k); fprintf(stderr, " -b STR prefix of BAMs to output [null]\n"); fprintf(stderr, " -q INT min het phred-LOD [%d]\n", g.min_varLOD); fprintf(stderr, " -Q INT min base quality in het calling [%d]\n", g.min_baseQ); fprintf(stderr, " -D INT max read depth [%d]\n", g.max_depth); // fprintf(stderr, " -l FILE list of sites to phase [null]\n"); fprintf(stderr, " -F do not attempt to fix chimeras\n"); fprintf(stderr, " -A drop reads with ambiguous phase\n"); // fprintf(stderr, " -e do not discover SNPs (effective with -l)\n"); fprintf(stderr, "\n"); return 1; } g.fp = strcmp(argv[optind], "-")? bam_open(argv[optind], "r") : bam_dopen(fileno(stdin), "r"); h = bam_header_read(g.fp); if (fn_list) { // read the list of sites to phase bam_init_header_hash(h); set = loadpos(fn_list, h); free(fn_list); } else g.flag &= ~FLAG_LIST_EXCL; if (g.pre) { // open BAMs to write char *s = malloc(strlen(g.pre) + 20); strcpy(s, g.pre); strcat(s, ".0.bam"); g.out[0] = bam_open(s, "w"); strcpy(s, g.pre); strcat(s, ".1.bam"); g.out[1] = bam_open(s, "w"); strcpy(s, g.pre); strcat(s, ".chimera.bam"); g.out[2] = bam_open(s, "w"); for (c = 0; c <= 2; ++c) bam_header_write(g.out[c], h); free(s); } iter = bam_plp_init(readaln, &g); g.vpos_shift = 0; seqs = kh_init(64); em = errmod_init(1. - 0.83); bases = calloc(g.max_depth, 2); printf("CC\n"); printf("CC\tDescriptions:\nCC\n"); printf("CC\t CC comments\n"); printf("CC\t PS start of a phase set\n"); printf("CC\t FL filtered region\n"); printf("CC\t M[012] markers; 0 for singletons, 1 for phased and 2 for filtered\n"); printf("CC\t EV supporting reads; SAM format\n"); printf("CC\t // end of a phase set\nCC\n"); printf("CC\tFormats of PS, FL and M[012] lines (1-based coordinates):\nCC\n"); printf("CC\t PS chr phaseSetStart phaseSetEnd\n"); printf("CC\t FL chr filterStart filterEnd\n"); printf("CC\t M? chr PS pos allele0 allele1 hetIndex #supports0 #errors0 #supp1 #err1\n"); printf("CC\nCC\n"); fflush(stdout); while ((plp = bam_plp_auto(iter, &tid, &pos, &n)) != 0) { int i, k, c, tmp, dophase = 1, in_set = 0; float q[16]; if (tid < 0) break; if (tid != lasttid) { // change of chromosome g.vpos_shift = 0; if (lasttid >= 0) { seqs = shrink_hash(seqs); phase(&g, h->target_name[lasttid], vpos, cns, seqs); update_vpos(0x7fffffff, seqs); } lasttid = tid; vpos = 0; } if (set && kh_get(set64, set, (uint64_t)tid<<32 | pos) != kh_end(set)) in_set = 1; if (n > g.max_depth) continue; // do not proceed if the depth is too high // fill the bases array and check if there is a variant for (i = k = 0; i < n; ++i) { const bam_pileup1_t *p = plp + i; uint8_t *seq; int q, baseQ, b; if (p->is_del || p->is_refskip) continue; baseQ = bam1_qual(p->b)[p->qpos]; if (baseQ < g.min_baseQ) continue; seq = bam1_seq(p->b); b = bam_nt16_nt4_table[bam1_seqi(seq, p->qpos)]; if (b > 3) continue; q = baseQ < p->b->core.qual? baseQ : p->b->core.qual; if (q < 4) q = 4; if (q > 63) q = 63; bases[k++] = q<<5 | (int)bam1_strand(p->b)<<4 | b; } if (k == 0) continue; errmod_cal(em, k, 4, bases, q); // compute genotype likelihood c = gl2cns(q); // get the consensus // tell if to proceed if (set && (g.flag&FLAG_LIST_EXCL) && !in_set) continue; // not in the list if (!in_set && (c&0xffff)>>2 < g.min_varLOD) continue; // not a variant // add the variant if (vpos == max_vpos) { max_vpos = max_vpos? max_vpos<<1 : 128; cns = realloc(cns, max_vpos * 8); } cns[vpos] = (uint64_t)pos<<32 | c; for (i = 0; i < n; ++i) { const bam_pileup1_t *p = plp + i; uint64_t key; khint_t k; uint8_t *seq = bam1_seq(p->b); frag_t *f; if (p->is_del || p->is_refskip) continue; if (p->b->core.qual == 0) continue; // get the base code c = nt16_nt4_table[(int)bam1_seqi(seq, p->qpos)]; if (c == (cns[vpos]&3)) c = 1; else if (c == (cns[vpos]>>16&3)) c = 2; else c = 0; // write to seqs key = X31_hash_string(bam1_qname(p->b)); k = kh_put(64, seqs, key, &tmp); f = &kh_val(seqs, k); if (tmp == 0) { // present in the hash table if (vpos - f->vpos + 1 < MAX_VARS) { f->vlen = vpos - f->vpos + 1; f->seq[f->vlen-1] = c; f->end = bam_calend(&p->b->core, bam1_cigar(p->b)); } dophase = 0; } else { // absent memset(f->seq, 0, MAX_VARS); f->beg = p->b->core.pos; f->end = bam_calend(&p->b->core, bam1_cigar(p->b)); f->vpos = vpos, f->vlen = 1, f->seq[0] = c, f->single = f->phased = f->flip = f->ambig = 0; } } if (dophase) { seqs = shrink_hash(seqs); phase(&g, h->target_name[tid], vpos, cns, seqs); update_vpos(vpos, seqs); cns[0] = cns[vpos]; vpos = 0; } ++vpos; } if (tid >= 0) phase(&g, h->target_name[tid], vpos, cns, seqs); bam_header_destroy(h); bam_plp_destroy(iter); bam_close(g.fp); kh_destroy(64, seqs); kh_destroy(set64, set); free(cns); errmod_destroy(em); free(bases); if (g.pre) { for (c = 0; c <= 2; ++c) bam_close(g.out[c]); free(g.pre); free(g.b); } return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam.c
.c
15,981
475
#include <stdio.h> #include <ctype.h> #include <errno.h> #include <assert.h> #include "bam.h" #include "bam_endian.h" #include "kstring.h" #include "sam_header.h" int bam_is_be = 0, bam_verbose = 2, bam_no_B = 0; char *bam_flag2char_table = "pPuUrR12sfd\0\0\0\0\0"; /************************** * CIGAR related routines * **************************/ uint32_t bam_calend(const bam1_core_t *c, const uint32_t *cigar) { int k, end = c->pos; for (k = 0; k < c->n_cigar; ++k) { int op = bam_cigar_op(cigar[k]); int len = bam_cigar_oplen(cigar[k]); if (op == BAM_CBACK) { // move backward int l, u, v; if (k == c->n_cigar - 1) break; // skip trailing 'B' for (l = k - 1, u = v = 0; l >= 0; --l) { int op1 = bam_cigar_op(cigar[l]); int len1 = bam_cigar_oplen(cigar[l]); if (bam_cigar_type(op1)&1) { // consume query if (u + len1 >= len) { // stop if (bam_cigar_type(op1)&2) v += len - u; break; } else u += len1; } if (bam_cigar_type(op1)&2) v += len1; } end = l < 0? c->pos : end - v; } else if (bam_cigar_type(op)&2) end += bam_cigar_oplen(cigar[k]); } return end; } int32_t bam_cigar2qlen(const bam1_core_t *c, const uint32_t *cigar) { uint32_t k; int32_t l = 0; for (k = 0; k < c->n_cigar; ++k) if (bam_cigar_type(bam_cigar_op(cigar[k]))&1) l += bam_cigar_oplen(cigar[k]); return l; } /******************** * BAM I/O routines * ********************/ bam_header_t *bam_header_init() { bam_is_be = bam_is_big_endian(); return (bam_header_t*)calloc(1, sizeof(bam_header_t)); } void bam_header_destroy(bam_header_t *header) { int32_t i; extern void bam_destroy_header_hash(bam_header_t *header); if (header == 0) return; if (header->target_name) { for (i = 0; i < header->n_targets; ++i) free(header->target_name[i]); free(header->target_name); free(header->target_len); } free(header->text); if (header->dict) sam_header_free(header->dict); if (header->rg2lib) sam_tbl_destroy(header->rg2lib); bam_destroy_header_hash(header); free(header); } bam_header_t *bam_header_read(bamFile fp) { bam_header_t *header; char buf[4]; int magic_len; int32_t i = 1, name_len; // check EOF i = bgzf_check_EOF(fp); if (i < 0) { // If the file is a pipe, checking the EOF marker will *always* fail // with ESPIPE. Suppress the error message in this case. if (errno != ESPIPE) perror("[bam_header_read] bgzf_check_EOF"); } else if (i == 0) fprintf(stderr, "[bam_header_read] EOF marker is absent. The input is probably truncated.\n"); // read "BAM1" magic_len = bam_read(fp, buf, 4); if (magic_len != 4 || strncmp(buf, "BAM\001", 4) != 0) { fprintf(stderr, "[bam_header_read] invalid BAM binary header (this is not a BAM file).\n"); return 0; } header = bam_header_init(); // read plain text and the number of reference sequences bam_read(fp, &header->l_text, 4); if (bam_is_be) bam_swap_endian_4p(&header->l_text); header->text = (char*)calloc(header->l_text + 1, 1); bam_read(fp, header->text, header->l_text); bam_read(fp, &header->n_targets, 4); if (bam_is_be) bam_swap_endian_4p(&header->n_targets); // read reference sequence names and lengths header->target_name = (char**)calloc(header->n_targets, sizeof(char*)); header->target_len = (uint32_t*)calloc(header->n_targets, 4); for (i = 0; i != header->n_targets; ++i) { bam_read(fp, &name_len, 4); if (bam_is_be) bam_swap_endian_4p(&name_len); header->target_name[i] = (char*)calloc(name_len, 1); bam_read(fp, header->target_name[i], name_len); bam_read(fp, &header->target_len[i], 4); if (bam_is_be) bam_swap_endian_4p(&header->target_len[i]); } return header; } int bam_header_write(bamFile fp, const bam_header_t *header) { char buf[4]; int32_t i, name_len, x; // write "BAM1" strncpy(buf, "BAM\001", 4); bam_write(fp, buf, 4); // write plain text and the number of reference sequences if (bam_is_be) { x = bam_swap_endian_4(header->l_text); bam_write(fp, &x, 4); if (header->l_text) bam_write(fp, header->text, header->l_text); x = bam_swap_endian_4(header->n_targets); bam_write(fp, &x, 4); } else { bam_write(fp, &header->l_text, 4); if (header->l_text) bam_write(fp, header->text, header->l_text); bam_write(fp, &header->n_targets, 4); } // write sequence names and lengths for (i = 0; i != header->n_targets; ++i) { char *p = header->target_name[i]; name_len = strlen(p) + 1; if (bam_is_be) { x = bam_swap_endian_4(name_len); bam_write(fp, &x, 4); } else bam_write(fp, &name_len, 4); bam_write(fp, p, name_len); if (bam_is_be) { x = bam_swap_endian_4(header->target_len[i]); bam_write(fp, &x, 4); } else bam_write(fp, &header->target_len[i], 4); } bgzf_flush(fp); return 0; } static void swap_endian_data(const bam1_core_t *c, int data_len, uint8_t *data) { uint8_t *s; uint32_t i, *cigar = (uint32_t*)(data + c->l_qname); s = data + c->n_cigar*4 + c->l_qname + c->l_qseq + (c->l_qseq + 1)/2; for (i = 0; i < c->n_cigar; ++i) bam_swap_endian_4p(&cigar[i]); while (s < data + data_len) { uint8_t type; s += 2; // skip key type = toupper(*s); ++s; // skip type if (type == 'C' || type == 'A') ++s; else if (type == 'S') { bam_swap_endian_2p(s); s += 2; } else if (type == 'I' || type == 'F') { bam_swap_endian_4p(s); s += 4; } else if (type == 'D') { bam_swap_endian_8p(s); s += 8; } else if (type == 'Z' || type == 'H') { while (*s) ++s; ++s; } else if (type == 'B') { int32_t n, Bsize = bam_aux_type2size(*s); memcpy(&n, s + 1, 4); if (1 == Bsize) { } else if (2 == Bsize) { for (i = 0; i < n; i += 2) bam_swap_endian_2p(s + 5 + i); } else if (4 == Bsize) { for (i = 0; i < n; i += 4) bam_swap_endian_4p(s + 5 + i); } bam_swap_endian_4p(s+1); } } } int bam_read1(bamFile fp, bam1_t *b) { bam1_core_t *c = &b->core; int32_t block_len, ret, i; uint32_t x[8]; assert(BAM_CORE_SIZE == 32); if ((ret = bam_read(fp, &block_len, 4)) != 4) { if (ret == 0) return -1; // normal end-of-file else return -2; // truncated } if (bam_read(fp, x, BAM_CORE_SIZE) != BAM_CORE_SIZE) return -3; if (bam_is_be) { bam_swap_endian_4p(&block_len); for (i = 0; i < 8; ++i) bam_swap_endian_4p(x + i); } c->tid = x[0]; c->pos = x[1]; c->bin = x[2]>>16; c->qual = x[2]>>8&0xff; c->l_qname = x[2]&0xff; c->flag = x[3]>>16; c->n_cigar = x[3]&0xffff; c->l_qseq = x[4]; c->mtid = x[5]; c->mpos = x[6]; c->isize = x[7]; b->data_len = block_len - BAM_CORE_SIZE; if (b->m_data < b->data_len) { b->m_data = b->data_len; kroundup32(b->m_data); b->data = (uint8_t*)realloc(b->data, b->m_data); } if (bam_read(fp, b->data, b->data_len) != b->data_len) return -4; b->l_aux = b->data_len - c->n_cigar * 4 - c->l_qname - c->l_qseq - (c->l_qseq+1)/2; if (bam_is_be) swap_endian_data(c, b->data_len, b->data); if (bam_no_B) bam_remove_B(b); return 4 + block_len; } inline int bam_write1_core(bamFile fp, const bam1_core_t *c, int data_len, uint8_t *data) { uint32_t x[8], block_len = data_len + BAM_CORE_SIZE, y; int i; assert(BAM_CORE_SIZE == 32); x[0] = c->tid; x[1] = c->pos; x[2] = (uint32_t)c->bin<<16 | c->qual<<8 | c->l_qname; x[3] = (uint32_t)c->flag<<16 | c->n_cigar; x[4] = c->l_qseq; x[5] = c->mtid; x[6] = c->mpos; x[7] = c->isize; bgzf_flush_try(fp, 4 + block_len); if (bam_is_be) { for (i = 0; i < 8; ++i) bam_swap_endian_4p(x + i); y = block_len; bam_write(fp, bam_swap_endian_4p(&y), 4); swap_endian_data(c, data_len, data); } else bam_write(fp, &block_len, 4); bam_write(fp, x, BAM_CORE_SIZE); bam_write(fp, data, data_len); if (bam_is_be) swap_endian_data(c, data_len, data); return 4 + block_len; } int bam_write1(bamFile fp, const bam1_t *b) { return bam_write1_core(fp, &b->core, b->data_len, b->data); } char *bam_format1_core(const bam_header_t *header, const bam1_t *b, int of) { uint8_t *s = bam1_seq(b), *t = bam1_qual(b); int i; const bam1_core_t *c = &b->core; kstring_t str; str.l = str.m = 0; str.s = 0; kputsn(bam1_qname(b), c->l_qname-1, &str); kputc('\t', &str); if (of == BAM_OFDEC) { kputw(c->flag, &str); kputc('\t', &str); } else if (of == BAM_OFHEX) ksprintf(&str, "0x%x\t", c->flag); else { // BAM_OFSTR for (i = 0; i < 16; ++i) if ((c->flag & 1<<i) && bam_flag2char_table[i]) kputc(bam_flag2char_table[i], &str); kputc('\t', &str); } if (c->tid < 0) kputsn("*\t", 2, &str); else { if (header) kputs(header->target_name[c->tid] , &str); else kputw(c->tid, &str); kputc('\t', &str); } kputw(c->pos + 1, &str); kputc('\t', &str); kputw(c->qual, &str); kputc('\t', &str); if (c->n_cigar == 0) kputc('*', &str); else { uint32_t *cigar = bam1_cigar(b); for (i = 0; i < c->n_cigar; ++i) { kputw(bam1_cigar(b)[i]>>BAM_CIGAR_SHIFT, &str); kputc(bam_cigar_opchr(cigar[i]), &str); } } kputc('\t', &str); if (c->mtid < 0) kputsn("*\t", 2, &str); else if (c->mtid == c->tid) kputsn("=\t", 2, &str); else { if (header) kputs(header->target_name[c->mtid], &str); else kputw(c->mtid, &str); kputc('\t', &str); } kputw(c->mpos + 1, &str); kputc('\t', &str); kputw(c->isize, &str); kputc('\t', &str); if (c->l_qseq) { for (i = 0; i < c->l_qseq; ++i) kputc(bam_nt16_rev_table[bam1_seqi(s, i)], &str); kputc('\t', &str); if (t[0] == 0xff) kputc('*', &str); else for (i = 0; i < c->l_qseq; ++i) kputc(t[i] + 33, &str); } else kputsn("*\t*", 3, &str); s = bam1_aux(b); while (s < b->data + b->data_len) { uint8_t type, key[2]; key[0] = s[0]; key[1] = s[1]; s += 2; type = *s; ++s; kputc('\t', &str); kputsn((char*)key, 2, &str); kputc(':', &str); if (type == 'A') { kputsn("A:", 2, &str); kputc(*s, &str); ++s; } else if (type == 'C') { kputsn("i:", 2, &str); kputw(*s, &str); ++s; } else if (type == 'c') { kputsn("i:", 2, &str); kputw(*(int8_t*)s, &str); ++s; } else if (type == 'S') { kputsn("i:", 2, &str); kputw(*(uint16_t*)s, &str); s += 2; } else if (type == 's') { kputsn("i:", 2, &str); kputw(*(int16_t*)s, &str); s += 2; } else if (type == 'I') { kputsn("i:", 2, &str); kputuw(*(uint32_t*)s, &str); s += 4; } else if (type == 'i') { kputsn("i:", 2, &str); kputw(*(int32_t*)s, &str); s += 4; } else if (type == 'f') { ksprintf(&str, "f:%g", *(float*)s); s += 4; } else if (type == 'd') { ksprintf(&str, "d:%lg", *(double*)s); s += 8; } else if (type == 'Z' || type == 'H') { kputc(type, &str); kputc(':', &str); while (*s) kputc(*s++, &str); ++s; } else if (type == 'B') { uint8_t sub_type = *(s++); int32_t n; memcpy(&n, s, 4); s += 4; // no point to the start of the array kputc(type, &str); kputc(':', &str); kputc(sub_type, &str); // write the typing for (i = 0; i < n; ++i) { kputc(',', &str); if ('c' == sub_type || 'c' == sub_type) { kputw(*(int8_t*)s, &str); ++s; } else if ('C' == sub_type) { kputw(*(uint8_t*)s, &str); ++s; } else if ('s' == sub_type) { kputw(*(int16_t*)s, &str); s += 2; } else if ('S' == sub_type) { kputw(*(uint16_t*)s, &str); s += 2; } else if ('i' == sub_type) { kputw(*(int32_t*)s, &str); s += 4; } else if ('I' == sub_type) { kputuw(*(uint32_t*)s, &str); s += 4; } else if ('f' == sub_type) { ksprintf(&str, "%g", *(float*)s); s += 4; } } } } return str.s; } char *bam_format1(const bam_header_t *header, const bam1_t *b) { return bam_format1_core(header, b, BAM_OFDEC); } void bam_view1(const bam_header_t *header, const bam1_t *b) { char *s = bam_format1(header, b); puts(s); free(s); } int bam_validate1(const bam_header_t *header, const bam1_t *b) { char *s; if (b->core.tid < -1 || b->core.mtid < -1) return 0; if (header && (b->core.tid >= header->n_targets || b->core.mtid >= header->n_targets)) return 0; if (b->data_len < b->core.l_qname) return 0; s = memchr(bam1_qname(b), '\0', b->core.l_qname); if (s != &bam1_qname(b)[b->core.l_qname-1]) return 0; // FIXME: Other fields could also be checked, especially the auxiliary data return 1; } // FIXME: we should also check the LB tag associated with each alignment const char *bam_get_library(bam_header_t *h, const bam1_t *b) { const uint8_t *rg; if (h->dict == 0) h->dict = sam_header_parse2(h->text); if (h->rg2lib == 0) h->rg2lib = sam_header2tbl(h->dict, "RG", "ID", "LB"); rg = bam_aux_get(b, "RG"); return (rg == 0)? 0 : sam_tbl_get(h->rg2lib, (const char*)(rg + 1)); } /************ * Remove B * ************/ int bam_remove_B(bam1_t *b) { int i, j, end_j, k, l, no_qual; uint32_t *cigar, *new_cigar; uint8_t *seq, *qual, *p; // test if removal is necessary if (b->core.flag & BAM_FUNMAP) return 0; // unmapped; do nothing cigar = bam1_cigar(b); for (k = 0; k < b->core.n_cigar; ++k) if (bam_cigar_op(cigar[k]) == BAM_CBACK) break; if (k == b->core.n_cigar) return 0; // no 'B' if (bam_cigar_op(cigar[0]) == BAM_CBACK) goto rmB_err; // cannot be removed // allocate memory for the new CIGAR if (b->data_len + (b->core.n_cigar + 1) * 4 > b->m_data) { // not enough memory b->m_data = b->data_len + b->core.n_cigar * 4; kroundup32(b->m_data); b->data = (uint8_t*)realloc(b->data, b->m_data); cigar = bam1_cigar(b); // after realloc, cigar may be changed } new_cigar = (uint32_t*)(b->data + (b->m_data - b->core.n_cigar * 4)); // from the end of b->data // the core loop seq = bam1_seq(b); qual = bam1_qual(b); no_qual = (qual[0] == 0xff); // test whether base quality is available i = j = 0; end_j = -1; for (k = l = 0; k < b->core.n_cigar; ++k) { int op = bam_cigar_op(cigar[k]); int len = bam_cigar_oplen(cigar[k]); if (op == BAM_CBACK) { // the backward operation int t, u; if (k == b->core.n_cigar - 1) break; // ignore 'B' at the end of CIGAR if (len > j) goto rmB_err; // an excessively long backward for (t = l - 1, u = 0; t >= 0; --t) { // look back int op1 = bam_cigar_op(new_cigar[t]); int len1 = bam_cigar_oplen(new_cigar[t]); if (bam_cigar_type(op1)&1) { // consume the query if (u + len1 >= len) { // stop new_cigar[t] -= (len - u) << BAM_CIGAR_SHIFT; break; } else u += len1; } } if (bam_cigar_oplen(new_cigar[t]) == 0) --t; // squeeze out the zero-length operation l = t + 1; end_j = j; j -= len; } else { // other CIGAR operations new_cigar[l++] = cigar[k]; if (bam_cigar_type(op)&1) { // consume the query if (i != j) { // no need to copy if i == j int u, c, c0; for (u = 0; u < len; ++u) { // construct the consensus c = bam1_seqi(seq, i+u); if (j + u < end_j) { // in an overlap c0 = bam1_seqi(seq, j+u); if (c != c0) { // a mismatch; choose the better base if (qual[j+u] < qual[i+u]) { // the base in the 2nd segment is better bam1_seq_seti(seq, j+u, c); qual[j+u] = qual[i+u] - qual[j+u]; } else qual[j+u] -= qual[i+u]; // the 1st is better; reduce base quality } else qual[j+u] = qual[j+u] > qual[i+u]? qual[j+u] : qual[i+u]; } else { // not in an overlap; copy over bam1_seq_seti(seq, j+u, c); qual[j+u] = qual[i+u]; } } } i += len, j += len; } } } if (no_qual) qual[0] = 0xff; // in very rare cases, this may be modified // merge adjacent operations if possible for (k = 1; k < l; ++k) if (bam_cigar_op(new_cigar[k]) == bam_cigar_op(new_cigar[k-1])) new_cigar[k] += new_cigar[k-1] >> BAM_CIGAR_SHIFT << BAM_CIGAR_SHIFT, new_cigar[k-1] &= 0xf; // kill zero length operations for (k = i = 0; k < l; ++k) if (new_cigar[k] >> BAM_CIGAR_SHIFT) new_cigar[i++] = new_cigar[k]; l = i; // update b memcpy(cigar, new_cigar, l * 4); // set CIGAR p = b->data + b->core.l_qname + l * 4; memmove(p, seq, (j+1)>>1); p += (j+1)>>1; // set SEQ memmove(p, qual, j); p += j; // set QUAL memmove(p, bam1_aux(b), b->l_aux); p += b->l_aux; // set optional fields b->core.n_cigar = l, b->core.l_qseq = j; // update CIGAR length and query length b->data_len = p - b->data; // update record length return 0; rmB_err: b->core.flag |= BAM_FUNMAP; return -1; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bgzf.c
.c
21,127
695
/* The MIT License Copyright (c) 2008 Broad Institute / Massachusetts Institute of Technology 2011 Attractive Chaos <attractor@live.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <assert.h> #include <pthread.h> #include <sys/types.h> #include "bgzf.h" #ifdef _USE_KNETFILE #include "knetfile.h" typedef knetFile *_bgzf_file_t; #define _bgzf_open(fn, mode) knet_open(fn, mode) #define _bgzf_dopen(fp, mode) knet_dopen(fp, mode) #define _bgzf_close(fp) knet_close(fp) #define _bgzf_fileno(fp) ((fp)->fd) #define _bgzf_tell(fp) knet_tell(fp) #define _bgzf_seek(fp, offset, whence) knet_seek(fp, offset, whence) #define _bgzf_read(fp, buf, len) knet_read(fp, buf, len) #define _bgzf_write(fp, buf, len) knet_write(fp, buf, len) #else // ~defined(_USE_KNETFILE) #if defined(_WIN32) || defined(_MSC_VER) #define ftello(fp) ftell(fp) #define fseeko(fp, offset, whence) fseek(fp, offset, whence) #else // ~defined(_WIN32) extern off_t ftello(FILE *stream); extern int fseeko(FILE *stream, off_t offset, int whence); #endif // ~defined(_WIN32) typedef FILE *_bgzf_file_t; #define _bgzf_open(fn, mode) fopen(fn, mode) #define _bgzf_dopen(fp, mode) fdopen(fp, mode) #define _bgzf_close(fp) fclose(fp) #define _bgzf_fileno(fp) fileno(fp) #define _bgzf_tell(fp) ftello(fp) #define _bgzf_seek(fp, offset, whence) fseeko(fp, offset, whence) #define _bgzf_read(fp, buf, len) fread(buf, 1, len, fp) #define _bgzf_write(fp, buf, len) fwrite(buf, 1, len, fp) #endif // ~define(_USE_KNETFILE) #define BLOCK_HEADER_LENGTH 18 #define BLOCK_FOOTER_LENGTH 8 /* BGZF/GZIP header (speciallized from RFC 1952; little endian): +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ | 31|139| 8| 4| 0| 0|255| 6| 66| 67| 2|BLK_LEN| +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ */ static const uint8_t g_magic[19] = "\037\213\010\4\0\0\0\0\0\377\6\0\102\103\2\0\0\0"; #ifdef BGZF_CACHE typedef struct { int size; uint8_t *block; int64_t end_offset; } cache_t; #include "khash.h" KHASH_MAP_INIT_INT64(cache, cache_t) #endif static inline void packInt16(uint8_t *buffer, uint16_t value) { buffer[0] = value; buffer[1] = value >> 8; } static inline int unpackInt16(const uint8_t *buffer) { return buffer[0] | buffer[1] << 8; } static inline void packInt32(uint8_t *buffer, uint32_t value) { buffer[0] = value; buffer[1] = value >> 8; buffer[2] = value >> 16; buffer[3] = value >> 24; } static BGZF *bgzf_read_init() { BGZF *fp; fp = calloc(1, sizeof(BGZF)); fp->is_write = 0; fp->uncompressed_block = malloc(BGZF_MAX_BLOCK_SIZE); fp->compressed_block = malloc(BGZF_MAX_BLOCK_SIZE); #ifdef BGZF_CACHE fp->cache = kh_init(cache); #endif return fp; } static BGZF *bgzf_write_init(int compress_level) // compress_level==-1 for the default level { BGZF *fp; fp = calloc(1, sizeof(BGZF)); fp->is_write = 1; fp->uncompressed_block = malloc(BGZF_MAX_BLOCK_SIZE); fp->compressed_block = malloc(BGZF_MAX_BLOCK_SIZE); fp->compress_level = compress_level < 0? Z_DEFAULT_COMPRESSION : compress_level; // Z_DEFAULT_COMPRESSION==-1 if (fp->compress_level > 9) fp->compress_level = Z_DEFAULT_COMPRESSION; return fp; } // get the compress level from the mode string static int mode2level(const char *__restrict mode) { int i, compress_level = -1; for (i = 0; mode[i]; ++i) if (mode[i] >= '0' && mode[i] <= '9') break; if (mode[i]) compress_level = (int)mode[i] - '0'; if (strchr(mode, 'u')) compress_level = 0; return compress_level; } BGZF *bgzf_open(const char *path, const char *mode) { BGZF *fp = 0; assert(compressBound(BGZF_BLOCK_SIZE) < BGZF_MAX_BLOCK_SIZE); if (strchr(mode, 'r') || strchr(mode, 'R')) { _bgzf_file_t fpr; if ((fpr = _bgzf_open(path, "r")) == 0) return 0; fp = bgzf_read_init(); fp->fp = fpr; } else if (strchr(mode, 'w') || strchr(mode, 'W')) { FILE *fpw; if ((fpw = fopen(path, "w")) == 0) return 0; fp = bgzf_write_init(mode2level(mode)); fp->fp = fpw; } return fp; } BGZF *bgzf_dopen(int fd, const char *mode) { BGZF *fp = 0; assert(compressBound(BGZF_BLOCK_SIZE) < BGZF_MAX_BLOCK_SIZE); if (strchr(mode, 'r') || strchr(mode, 'R')) { _bgzf_file_t fpr; if ((fpr = _bgzf_dopen(fd, "r")) == 0) return 0; fp = bgzf_read_init(); fp->fp = fpr; } else if (strchr(mode, 'w') || strchr(mode, 'W')) { FILE *fpw; if ((fpw = fdopen(fd, "w")) == 0) return 0; fp = bgzf_write_init(mode2level(mode)); fp->fp = fpw; } return fp; } static int bgzf_compress(void *_dst, int *dlen, void *src, int slen, int level) { uint32_t crc; z_stream zs; uint8_t *dst = (uint8_t*)_dst; // compress the body zs.zalloc = NULL; zs.zfree = NULL; zs.next_in = src; zs.avail_in = slen; zs.next_out = dst + BLOCK_HEADER_LENGTH; zs.avail_out = *dlen - BLOCK_HEADER_LENGTH - BLOCK_FOOTER_LENGTH; if (deflateInit2(&zs, level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK) return -1; // -15 to disable zlib header/footer if (deflate(&zs, Z_FINISH) != Z_STREAM_END) return -1; if (deflateEnd(&zs) != Z_OK) return -1; *dlen = zs.total_out + BLOCK_HEADER_LENGTH + BLOCK_FOOTER_LENGTH; // write the header memcpy(dst, g_magic, BLOCK_HEADER_LENGTH); // the last two bytes are a place holder for the length of the block packInt16(&dst[16], *dlen - 1); // write the compressed length; -1 to fit 2 bytes // write the footer crc = crc32(crc32(0L, NULL, 0L), src, slen); packInt32((uint8_t*)&dst[*dlen - 8], crc); packInt32((uint8_t*)&dst[*dlen - 4], slen); return 0; } // Deflate the block in fp->uncompressed_block into fp->compressed_block. Also adds an extra field that stores the compressed block length. static int deflate_block(BGZF *fp, int block_length) { int comp_size = BGZF_MAX_BLOCK_SIZE; if (bgzf_compress(fp->compressed_block, &comp_size, fp->uncompressed_block, block_length, fp->compress_level) != 0) { fp->errcode |= BGZF_ERR_ZLIB; return -1; } fp->block_offset = 0; return comp_size; } // Inflate the block in fp->compressed_block into fp->uncompressed_block static int inflate_block(BGZF* fp, int block_length) { z_stream zs; zs.zalloc = NULL; zs.zfree = NULL; zs.next_in = fp->compressed_block + 18; zs.avail_in = block_length - 16; zs.next_out = fp->uncompressed_block; zs.avail_out = BGZF_MAX_BLOCK_SIZE; if (inflateInit2(&zs, -15) != Z_OK) { fp->errcode |= BGZF_ERR_ZLIB; return -1; } if (inflate(&zs, Z_FINISH) != Z_STREAM_END) { inflateEnd(&zs); fp->errcode |= BGZF_ERR_ZLIB; return -1; } if (inflateEnd(&zs) != Z_OK) { fp->errcode |= BGZF_ERR_ZLIB; return -1; } return zs.total_out; } static int check_header(const uint8_t *header) { return (header[0] == 31 && header[1] == 139 && header[2] == 8 && (header[3] & 4) != 0 && unpackInt16((uint8_t*)&header[10]) == 6 && header[12] == 'B' && header[13] == 'C' && unpackInt16((uint8_t*)&header[14]) == 2); } #ifdef BGZF_CACHE static void free_cache(BGZF *fp) { khint_t k; khash_t(cache) *h = (khash_t(cache)*)fp->cache; if (fp->is_write) return; for (k = kh_begin(h); k < kh_end(h); ++k) if (kh_exist(h, k)) free(kh_val(h, k).block); kh_destroy(cache, h); } static int load_block_from_cache(BGZF *fp, int64_t block_address) { khint_t k; cache_t *p; khash_t(cache) *h = (khash_t(cache)*)fp->cache; k = kh_get(cache, h, block_address); if (k == kh_end(h)) return 0; p = &kh_val(h, k); if (fp->block_length != 0) fp->block_offset = 0; fp->block_address = block_address; fp->block_length = p->size; memcpy(fp->uncompressed_block, p->block, BGZF_MAX_BLOCK_SIZE); _bgzf_seek((_bgzf_file_t)fp->fp, p->end_offset, SEEK_SET); return p->size; } static void cache_block(BGZF *fp, int size) { int ret; khint_t k; cache_t *p; khash_t(cache) *h = (khash_t(cache)*)fp->cache; if (BGZF_MAX_BLOCK_SIZE >= fp->cache_size) return; if ((kh_size(h) + 1) * BGZF_MAX_BLOCK_SIZE > fp->cache_size) { /* A better way would be to remove the oldest block in the * cache, but here we remove a random one for simplicity. This * should not have a big impact on performance. */ for (k = kh_begin(h); k < kh_end(h); ++k) if (kh_exist(h, k)) break; if (k < kh_end(h)) { free(kh_val(h, k).block); kh_del(cache, h, k); } } k = kh_put(cache, h, fp->block_address, &ret); if (ret == 0) return; // if this happens, a bug! p = &kh_val(h, k); p->size = fp->block_length; p->end_offset = fp->block_address + size; p->block = malloc(BGZF_MAX_BLOCK_SIZE); memcpy(kh_val(h, k).block, fp->uncompressed_block, BGZF_MAX_BLOCK_SIZE); } #else static void free_cache(BGZF *fp) {} static int load_block_from_cache(BGZF *fp, int64_t block_address) {return 0;} static void cache_block(BGZF *fp, int size) {} #endif int bgzf_read_block(BGZF *fp) { uint8_t header[BLOCK_HEADER_LENGTH], *compressed_block; int count, size = 0, block_length, remaining; int64_t block_address; block_address = _bgzf_tell((_bgzf_file_t)fp->fp); if (fp->cache_size && load_block_from_cache(fp, block_address)) return 0; count = _bgzf_read(fp->fp, header, sizeof(header)); if (count == 0) { // no data read fp->block_length = 0; return 0; } if (count != sizeof(header) || !check_header(header)) { fp->errcode |= BGZF_ERR_HEADER; return -1; } size = count; block_length = unpackInt16((uint8_t*)&header[16]) + 1; // +1 because when writing this number, we used "-1" compressed_block = (uint8_t*)fp->compressed_block; memcpy(compressed_block, header, BLOCK_HEADER_LENGTH); remaining = block_length - BLOCK_HEADER_LENGTH; count = _bgzf_read(fp->fp, &compressed_block[BLOCK_HEADER_LENGTH], remaining); if (count != remaining) { fp->errcode |= BGZF_ERR_IO; return -1; } size += count; if ((count = inflate_block(fp, block_length)) < 0) return -1; if (fp->block_length != 0) fp->block_offset = 0; // Do not reset offset if this read follows a seek. fp->block_address = block_address; fp->block_length = count; cache_block(fp, size); return 0; } ssize_t bgzf_read(BGZF *fp, void *data, ssize_t length) { ssize_t bytes_read = 0; uint8_t *output = data; if (length <= 0) return 0; assert(fp->is_write == 0); while (bytes_read < length) { int copy_length, available = fp->block_length - fp->block_offset; uint8_t *buffer; if (available <= 0) { if (bgzf_read_block(fp) != 0) return -1; available = fp->block_length - fp->block_offset; if (available <= 0) break; } copy_length = length - bytes_read < available? length - bytes_read : available; buffer = fp->uncompressed_block; memcpy(output, buffer + fp->block_offset, copy_length); fp->block_offset += copy_length; output += copy_length; bytes_read += copy_length; } if (fp->block_offset == fp->block_length) { fp->block_address = _bgzf_tell((_bgzf_file_t)fp->fp); fp->block_offset = fp->block_length = 0; } return bytes_read; } /***** BEGIN: multi-threading *****/ typedef struct { BGZF *fp; struct mtaux_t *mt; void *buf; int i, errcode, toproc; } worker_t; typedef struct mtaux_t { int n_threads, n_blks, curr, done; volatile int proc_cnt; void **blk; int *len; worker_t *w; pthread_t *tid; pthread_mutex_t lock; pthread_cond_t cv; } mtaux_t; static int worker_aux(worker_t *w) { int i, tmp, stop = 0; // wait for condition: to process or all done pthread_mutex_lock(&w->mt->lock); while (!w->toproc && !w->mt->done) pthread_cond_wait(&w->mt->cv, &w->mt->lock); if (w->mt->done) stop = 1; w->toproc = 0; pthread_mutex_unlock(&w->mt->lock); if (stop) return 1; // to quit the thread w->errcode = 0; for (i = w->i; i < w->mt->curr; i += w->mt->n_threads) { int clen = BGZF_MAX_BLOCK_SIZE; if (bgzf_compress(w->buf, &clen, w->mt->blk[i], w->mt->len[i], w->fp->compress_level) != 0) w->errcode |= BGZF_ERR_ZLIB; memcpy(w->mt->blk[i], w->buf, clen); w->mt->len[i] = clen; } tmp = __sync_fetch_and_add(&w->mt->proc_cnt, 1); return 0; } static void *mt_worker(void *data) { while (worker_aux(data) == 0); return 0; } int bgzf_mt(BGZF *fp, int n_threads, int n_sub_blks) { int i; mtaux_t *mt; pthread_attr_t attr; if (!fp->is_write || fp->mt || n_threads <= 1) return -1; mt = calloc(1, sizeof(mtaux_t)); mt->n_threads = n_threads; mt->n_blks = n_threads * n_sub_blks; mt->len = calloc(mt->n_blks, sizeof(int)); mt->blk = calloc(mt->n_blks, sizeof(void*)); for (i = 0; i < mt->n_blks; ++i) mt->blk[i] = malloc(BGZF_MAX_BLOCK_SIZE); mt->tid = calloc(mt->n_threads, sizeof(pthread_t)); // tid[0] is not used, as the worker 0 is launched by the master mt->w = calloc(mt->n_threads, sizeof(worker_t)); for (i = 0; i < mt->n_threads; ++i) { mt->w[i].i = i; mt->w[i].mt = mt; mt->w[i].fp = fp; mt->w[i].buf = malloc(BGZF_MAX_BLOCK_SIZE); } pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&mt->lock, 0); pthread_cond_init(&mt->cv, 0); for (i = 1; i < mt->n_threads; ++i) // worker 0 is effectively launched by the master thread pthread_create(&mt->tid[i], &attr, mt_worker, &mt->w[i]); fp->mt = mt; return 0; } static void mt_destroy(mtaux_t *mt) { int i; // signal all workers to quit pthread_mutex_lock(&mt->lock); mt->done = 1; mt->proc_cnt = 0; pthread_cond_broadcast(&mt->cv); pthread_mutex_unlock(&mt->lock); for (i = 1; i < mt->n_threads; ++i) pthread_join(mt->tid[i], 0); // worker 0 is effectively launched by the master thread // free other data allocated on heap for (i = 0; i < mt->n_blks; ++i) free(mt->blk[i]); for (i = 0; i < mt->n_threads; ++i) free(mt->w[i].buf); free(mt->blk); free(mt->len); free(mt->w); free(mt->tid); pthread_cond_destroy(&mt->cv); pthread_mutex_destroy(&mt->lock); free(mt); } static void mt_queue(BGZF *fp) { mtaux_t *mt = (mtaux_t*)fp->mt; assert(mt->curr < mt->n_blks); // guaranteed by the caller memcpy(mt->blk[mt->curr], fp->uncompressed_block, fp->block_offset); mt->len[mt->curr] = fp->block_offset; fp->block_offset = 0; ++mt->curr; } static int mt_flush(BGZF *fp) { int i; mtaux_t *mt = (mtaux_t*)fp->mt; if (fp->block_offset) mt_queue(fp); // guaranteed that assertion does not fail // signal all the workers to compress pthread_mutex_lock(&mt->lock); for (i = 0; i < mt->n_threads; ++i) mt->w[i].toproc = 1; mt->proc_cnt = 0; pthread_cond_broadcast(&mt->cv); pthread_mutex_unlock(&mt->lock); // worker 0 is doing things here worker_aux(&mt->w[0]); // wait for all the threads to complete while (mt->proc_cnt < mt->n_threads); // dump data to disk for (i = 0; i < mt->n_threads; ++i) fp->errcode |= mt->w[i].errcode; for (i = 0; i < mt->curr; ++i) if (fwrite(mt->blk[i], 1, mt->len[i], fp->fp) != mt->len[i]) fp->errcode |= BGZF_ERR_IO; mt->curr = 0; return 0; } static int mt_lazy_flush(BGZF *fp) { mtaux_t *mt = (mtaux_t*)fp->mt; if (fp->block_offset) mt_queue(fp); if (mt->curr == mt->n_blks) return mt_flush(fp); return -1; } static ssize_t mt_write(BGZF *fp, const void *data, ssize_t length) { const uint8_t *input = data; ssize_t rest = length; while (rest) { int copy_length = BGZF_BLOCK_SIZE - fp->block_offset < rest? BGZF_BLOCK_SIZE - fp->block_offset : rest; memcpy(fp->uncompressed_block + fp->block_offset, input, copy_length); fp->block_offset += copy_length; input += copy_length; rest -= copy_length; if (fp->block_offset == BGZF_BLOCK_SIZE) mt_lazy_flush(fp); } return length - rest; } /***** END: multi-threading *****/ int bgzf_flush(BGZF *fp) { if (!fp->is_write) return 0; if (fp->mt) return mt_flush(fp); while (fp->block_offset > 0) { int block_length; block_length = deflate_block(fp, fp->block_offset); if (block_length < 0) return -1; if (fwrite(fp->compressed_block, 1, block_length, fp->fp) != block_length) { fp->errcode |= BGZF_ERR_IO; // possibly truncated file return -1; } fp->block_address += block_length; } return 0; } int bgzf_flush_try(BGZF *fp, ssize_t size) { if (fp->block_offset + size > BGZF_BLOCK_SIZE) { if (fp->mt) return mt_lazy_flush(fp); else return bgzf_flush(fp); } return -1; } ssize_t bgzf_write(BGZF *fp, const void *data, ssize_t length) { const uint8_t *input = data; int block_length = BGZF_BLOCK_SIZE, bytes_written = 0; assert(fp->is_write); if (fp->mt) return mt_write(fp, data, length); while (bytes_written < length) { uint8_t* buffer = fp->uncompressed_block; int copy_length = block_length - fp->block_offset < length - bytes_written? block_length - fp->block_offset : length - bytes_written; memcpy(buffer + fp->block_offset, input, copy_length); fp->block_offset += copy_length; input += copy_length; bytes_written += copy_length; if (fp->block_offset == block_length && bgzf_flush(fp)) break; } return bytes_written; } int bgzf_close(BGZF* fp) { int ret, count, block_length; if (fp == 0) return -1; if (fp->is_write) { if (bgzf_flush(fp) != 0) return -1; fp->compress_level = -1; block_length = deflate_block(fp, 0); // write an empty block count = fwrite(fp->compressed_block, 1, block_length, fp->fp); if (fflush(fp->fp) != 0) { fp->errcode |= BGZF_ERR_IO; return -1; } if (fp->mt) mt_destroy(fp->mt); } ret = fp->is_write? fclose(fp->fp) : _bgzf_close(fp->fp); if (ret != 0) return -1; free(fp->uncompressed_block); free(fp->compressed_block); free_cache(fp); free(fp); return 0; } void bgzf_set_cache_size(BGZF *fp, int cache_size) { if (fp) fp->cache_size = cache_size; } int bgzf_check_EOF(BGZF *fp) { static uint8_t magic[28] = "\037\213\010\4\0\0\0\0\0\377\6\0\102\103\2\0\033\0\3\0\0\0\0\0\0\0\0\0"; uint8_t buf[28]; off_t offset; offset = _bgzf_tell((_bgzf_file_t)fp->fp); if (_bgzf_seek(fp->fp, -28, SEEK_END) < 0) return 0; _bgzf_read(fp->fp, buf, 28); _bgzf_seek(fp->fp, offset, SEEK_SET); return (memcmp(magic, buf, 28) == 0)? 1 : 0; } int64_t bgzf_seek(BGZF* fp, int64_t pos, int where) { int block_offset; int64_t block_address; if (fp->is_write || where != SEEK_SET) { fp->errcode |= BGZF_ERR_MISUSE; return -1; } block_offset = pos & 0xFFFF; block_address = pos >> 16; if (_bgzf_seek(fp->fp, block_address, SEEK_SET) < 0) { fp->errcode |= BGZF_ERR_IO; return -1; } fp->block_length = 0; // indicates current block has not been loaded fp->block_address = block_address; fp->block_offset = block_offset; return 0; } int bgzf_is_bgzf(const char *fn) { uint8_t buf[16]; int n; _bgzf_file_t fp; if ((fp = _bgzf_open(fn, "r")) == 0) return 0; n = _bgzf_read(fp, buf, 16); _bgzf_close(fp); if (n != 16) return 0; return memcmp(g_magic, buf, 16) == 0? 1 : 0; } int bgzf_getc(BGZF *fp) { int c; if (fp->block_offset >= fp->block_length) { if (bgzf_read_block(fp) != 0) return -2; /* error */ if (fp->block_length == 0) return -1; /* end-of-file */ } c = ((unsigned char*)fp->uncompressed_block)[fp->block_offset++]; if (fp->block_offset == fp->block_length) { fp->block_address = _bgzf_tell((_bgzf_file_t)fp->fp); fp->block_offset = 0; fp->block_length = 0; } return c; } #ifndef kroundup32 #define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x)) #endif int bgzf_getline(BGZF *fp, int delim, kstring_t *str) { int l, state = 0; unsigned char *buf = (unsigned char*)fp->uncompressed_block; str->l = 0; do { if (fp->block_offset >= fp->block_length) { if (bgzf_read_block(fp) != 0) { state = -2; break; } if (fp->block_length == 0) { state = -1; break; } } for (l = fp->block_offset; l < fp->block_length && buf[l] != delim; ++l); if (l < fp->block_length) state = 1; l -= fp->block_offset; if (str->l + l + 1 >= str->m) { str->m = str->l + l + 2; kroundup32(str->m); str->s = (char*)realloc(str->s, str->m); } memcpy(str->s + str->l, buf + fp->block_offset, l); str->l += l; fp->block_offset += l + 1; if (fp->block_offset >= fp->block_length) { fp->block_address = _bgzf_tell((_bgzf_file_t)fp->fp); fp->block_offset = 0; fp->block_length = 0; } } while (state == 0); if (str->l == 0 && state < 0) return state; str->s[str->l] = 0; return str->l; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/kprobaln.c
.c
10,675
281
/* The MIT License Copyright (c) 2003-2006, 2008-2010, by Heng Li <lh3lh3@live.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include <math.h> #include "kprobaln.h" /***************************************** * Probabilistic banded glocal alignment * *****************************************/ #define EI .25 #define EM .33333333333 static float g_qual2prob[256]; #define set_u(u, b, i, k) { int x=(i)-(b); x=x>0?x:0; (u)=((k)-x+1)*3; } kpa_par_t kpa_par_def = { 0.001, 0.1, 10 }; kpa_par_t kpa_par_alt = { 0.0001, 0.01, 10 }; /* The topology of the profile HMM: /\ /\ /\ /\ I[1] I[k-1] I[k] I[L] ^ \ \ ^ \ ^ \ \ ^ | \ \ | \ | \ \ | M[0] M[1] -> ... -> M[k-1] -> M[k] -> ... -> M[L] M[L+1] \ \/ \/ \/ / \ /\ /\ /\ / -> D[k-1] -> D[k] -> M[0] points to every {M,I}[k] and every {M,I}[k] points M[L+1]. On input, _ref is the reference sequence and _query is the query sequence. Both are sequences of 0/1/2/3/4 where 4 stands for an ambiguous residue. iqual is the base quality. c sets the gap open probability, gap extension probability and band width. On output, state and q are arrays of length l_query. The higher 30 bits give the reference position the query base is matched to and the lower two bits can be 0 (an alignment match) or 1 (an insertion). q[i] gives the phred scaled posterior probability of state[i] being wrong. */ int kpa_glocal(const uint8_t *_ref, int l_ref, const uint8_t *_query, int l_query, const uint8_t *iqual, const kpa_par_t *c, int *state, uint8_t *q) { double **f, **b = 0, *s, m[9], sI, sM, bI, bM, pb; float *qual, *_qual; const uint8_t *ref, *query; int bw, bw2, i, k, is_diff = 0, is_backward = 1, Pr; if ( l_ref<=0 || l_query<=0 ) return 0; // FIXME: this may not be an ideal fix, just prevents sefgault /*** initialization ***/ is_backward = state && q? 1 : 0; ref = _ref - 1; query = _query - 1; // change to 1-based coordinate bw = l_ref > l_query? l_ref : l_query; if (bw > c->bw) bw = c->bw; if (bw < abs(l_ref - l_query)) bw = abs(l_ref - l_query); bw2 = bw * 2 + 1; // allocate the forward and backward matrices f[][] and b[][] and the scaling array s[] f = calloc(l_query+1, sizeof(void*)); if (is_backward) b = calloc(l_query+1, sizeof(void*)); for (i = 0; i <= l_query; ++i) { // FIXME: this will lead in segfault for l_query==0 f[i] = calloc(bw2 * 3 + 6, sizeof(double)); // FIXME: this is over-allocated for very short seqs if (is_backward) b[i] = calloc(bw2 * 3 + 6, sizeof(double)); } s = calloc(l_query+2, sizeof(double)); // s[] is the scaling factor to avoid underflow // initialize qual _qual = calloc(l_query, sizeof(float)); if (g_qual2prob[0] == 0) for (i = 0; i < 256; ++i) g_qual2prob[i] = pow(10, -i/10.); for (i = 0; i < l_query; ++i) _qual[i] = g_qual2prob[iqual? iqual[i] : 30]; qual = _qual - 1; // initialize transition probability sM = sI = 1. / (2 * l_query + 2); // the value here seems not to affect results; FIXME: need proof m[0*3+0] = (1 - c->d - c->d) * (1 - sM); m[0*3+1] = m[0*3+2] = c->d * (1 - sM); m[1*3+0] = (1 - c->e) * (1 - sI); m[1*3+1] = c->e * (1 - sI); m[1*3+2] = 0.; m[2*3+0] = 1 - c->e; m[2*3+1] = 0.; m[2*3+2] = c->e; bM = (1 - c->d) / l_ref; bI = c->d / l_ref; // (bM+bI)*l_ref==1 /*** forward ***/ // f[0] set_u(k, bw, 0, 0); f[0][k] = s[0] = 1.; { // f[1] double *fi = f[1], sum; int beg = 1, end = l_ref < bw + 1? l_ref : bw + 1, _beg, _end; for (k = beg, sum = 0.; k <= end; ++k) { int u; double e = (ref[k] > 3 || query[1] > 3)? 1. : ref[k] == query[1]? 1. - qual[1] : qual[1] * EM; set_u(u, bw, 1, k); fi[u+0] = e * bM; fi[u+1] = EI * bI; sum += fi[u] + fi[u+1]; } // rescale s[1] = sum; set_u(_beg, bw, 1, beg); set_u(_end, bw, 1, end); _end += 2; for (k = _beg; k <= _end; ++k) fi[k] /= sum; } // f[2..l_query] for (i = 2; i <= l_query; ++i) { double *fi = f[i], *fi1 = f[i-1], sum, qli = qual[i]; int beg = 1, end = l_ref, x, _beg, _end; uint8_t qyi = query[i]; x = i - bw; beg = beg > x? beg : x; // band start x = i + bw; end = end < x? end : x; // band end for (k = beg, sum = 0.; k <= end; ++k) { int u, v11, v01, v10; double e; e = (ref[k] > 3 || qyi > 3)? 1. : ref[k] == qyi? 1. - qli : qli * EM; set_u(u, bw, i, k); set_u(v11, bw, i-1, k-1); set_u(v10, bw, i-1, k); set_u(v01, bw, i, k-1); fi[u+0] = e * (m[0] * fi1[v11+0] + m[3] * fi1[v11+1] + m[6] * fi1[v11+2]); fi[u+1] = EI * (m[1] * fi1[v10+0] + m[4] * fi1[v10+1]); fi[u+2] = m[2] * fi[v01+0] + m[8] * fi[v01+2]; sum += fi[u] + fi[u+1] + fi[u+2]; // fprintf(stderr, "F (%d,%d;%d): %lg,%lg,%lg\n", i, k, u, fi[u], fi[u+1], fi[u+2]); // DEBUG } // rescale s[i] = sum; set_u(_beg, bw, i, beg); set_u(_end, bw, i, end); _end += 2; for (k = _beg, sum = 1./sum; k <= _end; ++k) fi[k] *= sum; } { // f[l_query+1] double sum; for (k = 1, sum = 0.; k <= l_ref; ++k) { int u; set_u(u, bw, l_query, k); if (u < 3 || u >= bw2*3+3) continue; sum += f[l_query][u+0] * sM + f[l_query][u+1] * sI; } s[l_query+1] = sum; // the last scaling factor } { // compute likelihood double p = 1., Pr1 = 0.; for (i = 0; i <= l_query + 1; ++i) { p *= s[i]; if (p < 1e-100) Pr1 += -4.343 * log(p), p = 1.; } Pr1 += -4.343 * log(p * l_ref * l_query); Pr = (int)(Pr1 + .499); if (!is_backward) { // skip backward and MAP for (i = 0; i <= l_query; ++i) free(f[i]); free(f); free(s); free(_qual); return Pr; } } /*** backward ***/ // b[l_query] (b[l_query+1][0]=1 and thus \tilde{b}[][]=1/s[l_query+1]; this is where s[l_query+1] comes from) for (k = 1; k <= l_ref; ++k) { int u; double *bi = b[l_query]; set_u(u, bw, l_query, k); if (u < 3 || u >= bw2*3+3) continue; bi[u+0] = sM / s[l_query] / s[l_query+1]; bi[u+1] = sI / s[l_query] / s[l_query+1]; } // b[l_query-1..1] for (i = l_query - 1; i >= 1; --i) { int beg = 1, end = l_ref, x, _beg, _end; double *bi = b[i], *bi1 = b[i+1], y = (i > 1), qli1 = qual[i+1]; uint8_t qyi1 = query[i+1]; x = i - bw; beg = beg > x? beg : x; x = i + bw; end = end < x? end : x; for (k = end; k >= beg; --k) { int u, v11, v01, v10; double e; set_u(u, bw, i, k); set_u(v11, bw, i+1, k+1); set_u(v10, bw, i+1, k); set_u(v01, bw, i, k+1); e = (k >= l_ref? 0 : (ref[k+1] > 3 || qyi1 > 3)? 1. : ref[k+1] == qyi1? 1. - qli1 : qli1 * EM) * bi1[v11]; bi[u+0] = e * m[0] + EI * m[1] * bi1[v10+1] + m[2] * bi[v01+2]; // bi1[v11] has been foled into e. bi[u+1] = e * m[3] + EI * m[4] * bi1[v10+1]; bi[u+2] = (e * m[6] + m[8] * bi[v01+2]) * y; // fprintf(stderr, "B (%d,%d;%d): %lg,%lg,%lg\n", i, k, u, bi[u], bi[u+1], bi[u+2]); // DEBUG } // rescale set_u(_beg, bw, i, beg); set_u(_end, bw, i, end); _end += 2; for (k = _beg, y = 1./s[i]; k <= _end; ++k) bi[k] *= y; } { // b[0] int beg = 1, end = l_ref < bw + 1? l_ref : bw + 1; double sum = 0.; for (k = end; k >= beg; --k) { int u; double e = (ref[k] > 3 || query[1] > 3)? 1. : ref[k] == query[1]? 1. - qual[1] : qual[1] * EM; set_u(u, bw, 1, k); if (u < 3 || u >= bw2*3+3) continue; sum += e * b[1][u+0] * bM + EI * b[1][u+1] * bI; } set_u(k, bw, 0, 0); pb = b[0][k] = sum / s[0]; // if everything works as is expected, pb == 1.0 } is_diff = fabs(pb - 1.) > 1e-7? 1 : 0; /*** MAP ***/ for (i = 1; i <= l_query; ++i) { double sum = 0., *fi = f[i], *bi = b[i], max = 0.; int beg = 1, end = l_ref, x, max_k = -1; x = i - bw; beg = beg > x? beg : x; x = i + bw; end = end < x? end : x; for (k = beg; k <= end; ++k) { int u; double z; set_u(u, bw, i, k); z = fi[u+0] * bi[u+0]; if (z > max) max = z, max_k = (k-1)<<2 | 0; sum += z; z = fi[u+1] * bi[u+1]; if (z > max) max = z, max_k = (k-1)<<2 | 1; sum += z; } max /= sum; sum *= s[i]; // if everything works as is expected, sum == 1.0 if (state) state[i-1] = max_k; if (q) k = (int)(-4.343 * log(1. - max) + .499), q[i-1] = k > 100? 99 : k; #ifdef _MAIN fprintf(stderr, "(%.10lg,%.10lg) (%d,%d:%c,%c:%d) %lg\n", pb, sum, i-1, max_k>>2, "ACGT"[query[i]], "ACGT"[ref[(max_k>>2)+1]], max_k&3, max); // DEBUG #endif } /*** free ***/ for (i = 0; i <= l_query; ++i) { free(f[i]); free(b[i]); } free(f); free(b); free(s); free(_qual); return Pr; } #ifdef _MAIN #include <unistd.h> int main(int argc, char *argv[]) { uint8_t conv[256], *iqual, *ref, *query; int c, l_ref, l_query, i, q = 30, b = 10, P; while ((c = getopt(argc, argv, "b:q:")) >= 0) { switch (c) { case 'b': b = atoi(optarg); break; case 'q': q = atoi(optarg); break; } } if (optind + 2 > argc) { fprintf(stderr, "Usage: %s [-q %d] [-b %d] <ref> <query>\n", argv[0], q, b); // example: acttc attc return 1; } memset(conv, 4, 256); conv['a'] = conv['A'] = 0; conv['c'] = conv['C'] = 1; conv['g'] = conv['G'] = 2; conv['t'] = conv['T'] = 3; ref = (uint8_t*)argv[optind]; query = (uint8_t*)argv[optind+1]; l_ref = strlen((char*)ref); l_query = strlen((char*)query); for (i = 0; i < l_ref; ++i) ref[i] = conv[ref[i]]; for (i = 0; i < l_query; ++i) query[i] = conv[query[i]]; iqual = malloc(l_query); memset(iqual, q, l_query); kpa_par_def.bw = b; P = kpa_glocal(ref, l_ref, query, l_query, iqual, &kpa_par_alt, 0, 0); fprintf(stderr, "%d\n", P); free(iqual); return 0; } #endif
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bgzf.h
.h
6,326
208
/* The MIT License Copyright (c) 2008 Broad Institute / Massachusetts Institute of Technology 2011, 2012 Attractive Chaos <attractor@live.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* The BGZF library was originally written by Bob Handsaker from the Broad * Institute. It was later improved by the SAMtools developers. */ #ifndef __BGZF_H #define __BGZF_H #include <stdint.h> #include <stdio.h> #include <zlib.h> #include <sys/types.h> #define BGZF_BLOCK_SIZE 0xff00 // make sure compressBound(BGZF_BLOCK_SIZE) < BGZF_MAX_BLOCK_SIZE #define BGZF_MAX_BLOCK_SIZE 0x10000 #define BGZF_ERR_ZLIB 1 #define BGZF_ERR_HEADER 2 #define BGZF_ERR_IO 4 #define BGZF_ERR_MISUSE 8 typedef struct { int errcode:16, is_write:2, compress_level:14; int cache_size; int block_length, block_offset; int64_t block_address; void *uncompressed_block, *compressed_block; void *cache; // a pointer to a hash table void *fp; // actual file handler; FILE* on writing; FILE* or knetFile* on reading void *mt; // only used for multi-threading } BGZF; #ifndef KSTRING_T #define KSTRING_T kstring_t typedef struct __kstring_t { size_t l, m; char *s; } kstring_t; #endif #ifdef __cplusplus extern "C" { #endif /****************** * Basic routines * ******************/ /** * Open an existing file descriptor for reading or writing. * * @param fd file descriptor * @param mode mode matching /[rwu0-9]+/: 'r' for reading, 'w' for writing and a digit specifies * the zlib compression level; if both 'r' and 'w' are present, 'w' is ignored. * @return BGZF file handler; 0 on error */ BGZF* bgzf_dopen(int fd, const char *mode); #define bgzf_fdopen(fd, mode) bgzf_dopen((fd), (mode)) // for backward compatibility /** * Open the specified file for reading or writing. */ BGZF* bgzf_open(const char* path, const char *mode); /** * Close the BGZF and free all associated resources. * * @param fp BGZF file handler * @return 0 on success and -1 on error */ int bgzf_close(BGZF *fp); /** * Read up to _length_ bytes from the file storing into _data_. * * @param fp BGZF file handler * @param data data array to read into * @param length size of data to read * @return number of bytes actually read; 0 on end-of-file and -1 on error */ ssize_t bgzf_read(BGZF *fp, void *data, ssize_t length); /** * Write _length_ bytes from _data_ to the file. * * @param fp BGZF file handler * @param data data array to write * @param length size of data to write * @return number of bytes actually written; -1 on error */ ssize_t bgzf_write(BGZF *fp, const void *data, ssize_t length); /** * Write the data in the buffer to the file. */ int bgzf_flush(BGZF *fp); /** * Return a virtual file pointer to the current location in the file. * No interpetation of the value should be made, other than a subsequent * call to bgzf_seek can be used to position the file at the same point. * Return value is non-negative on success. */ #define bgzf_tell(fp) ((fp->block_address << 16) | (fp->block_offset & 0xFFFF)) /** * Set the file to read from the location specified by _pos_. * * @param fp BGZF file handler * @param pos virtual file offset returned by bgzf_tell() * @param whence must be SEEK_SET * @return 0 on success and -1 on error */ int64_t bgzf_seek(BGZF *fp, int64_t pos, int whence); /** * Check if the BGZF end-of-file (EOF) marker is present * * @param fp BGZF file handler opened for reading * @return 1 if EOF is present; 0 if not or on I/O error */ int bgzf_check_EOF(BGZF *fp); /** * Check if a file is in the BGZF format * * @param fn file name * @return 1 if _fn_ is BGZF; 0 if not or on I/O error */ int bgzf_is_bgzf(const char *fn); /********************* * Advanced routines * *********************/ /** * Set the cache size. Only effective when compiled with -DBGZF_CACHE. * * @param fp BGZF file handler * @param size size of cache in bytes; 0 to disable caching (default) */ void bgzf_set_cache_size(BGZF *fp, int size); /** * Flush the file if the remaining buffer size is smaller than _size_ */ int bgzf_flush_try(BGZF *fp, ssize_t size); /** * Read one byte from a BGZF file. It is faster than bgzf_read() * @param fp BGZF file handler * @return byte read; -1 on end-of-file or error */ int bgzf_getc(BGZF *fp); /** * Read one line from a BGZF file. It is faster than bgzf_getc() * * @param fp BGZF file handler * @param delim delimitor * @param str string to write to; must be initialized * @return length of the string; 0 on end-of-file; negative on error */ int bgzf_getline(BGZF *fp, int delim, kstring_t *str); /** * Read the next BGZF block. */ int bgzf_read_block(BGZF *fp); /** * Enable multi-threading (only effective on writing) * * @param fp BGZF file handler; must be opened for writing * @param n_threads #threads used for writing * @param n_sub_blks #blocks processed by each thread; a value 64-256 is recommended */ int bgzf_mt(BGZF *fp, int n_threads, int n_sub_blks); #ifdef __cplusplus } #endif #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_tview_html.c
.c
8,406
350
#include <unistd.h> #include "bam_tview.h" #define UNDERLINE_FLAG 10 typedef struct HtmlTview { tview_t view; int row_count; tixel_t** screen; FILE* out; int attributes;/* color... */ } html_tview_t; #define FROM_TV(ptr) ((html_tview_t*)ptr) static void html_destroy(tview_t* base) { int i; html_tview_t* tv=(html_tview_t*)base; if(tv->screen!=NULL) { for(i=0;i< tv->row_count;++i) free(tv->screen[i]); free(tv->screen); } base_tv_destroy(base); free(tv); } /* void (*my_mvprintw)(struct AbstractTview* ,int,int,const char*,...); void (*my_)(struct AbstractTview*,int,int,int); void (*my_attron)(struct AbstractTview*,int); void (*my_attroff)(struct AbstractTview*,int); void (*my_clear)(struct AbstractTview*); int (*my_colorpair)(struct AbstractTview*,int); */ static void html_mvprintw(struct AbstractTview* tv,int y ,int x,const char* fmt,...) { int i,nchars=0; unsigned int size=tv->mcol+2; char* str=malloc(size); if(str==0) exit(EXIT_FAILURE); va_list argptr; va_start(argptr, fmt); nchars=vsnprintf(str,size, fmt, argptr); va_end(argptr); for(i=0;i< nchars;++i) { tv->my_mvaddch(tv,y,x+i,str[i]); } free(str); } static void html_mvaddch(struct AbstractTview* tv,int y,int x,int ch) { tixel_t* row=NULL; html_tview_t* ptr=FROM_TV(tv); if( x >= tv->mcol ) return; //out of screen while(ptr->row_count<=y) { int x; row=(tixel_t*)calloc(tv->mcol,sizeof(tixel_t)); if(row==0) exit(EXIT_FAILURE); for(x=0;x<tv->mcol;++x) {row[x].ch=' ';row[x].attributes=0;} ptr->screen=(tixel_t**)realloc(ptr->screen,sizeof(tixel_t*)*(ptr->row_count+1)); ptr->screen[ptr->row_count++]=row; } row=ptr->screen[y]; row[x].ch=ch; row[x].attributes=ptr->attributes; } static void html_attron(struct AbstractTview* tv,int flag) { html_tview_t* ptr=FROM_TV(tv); ptr->attributes |= flag; } static void html_attroff(struct AbstractTview* tv,int flag) { html_tview_t* ptr=FROM_TV(tv); ptr->attributes &= ~(flag); } static void html_clear(struct AbstractTview* tv) { html_tview_t* ptr=FROM_TV(tv); if(ptr->screen!=NULL) { int i; for(i=0;i< ptr->row_count;++i) free(ptr->screen[i]); free(ptr->screen); ptr->screen=NULL; } ptr->row_count=0; ptr->attributes=0; } static int html_colorpair(struct AbstractTview* tv,int flag) { return (1 << (flag)); } static int html_drawaln(struct AbstractTview* tv, int tid, int pos) { int y,x; html_tview_t* ptr=FROM_TV(tv); html_clear(tv); base_draw_aln(tv, tid, pos); fputs("<html><head>",ptr->out); fprintf(ptr->out,"<title>%s:%d</title>", tv->header->target_name[tid], pos+1 ); //style fputs("<style type='text/css'>\n",ptr->out); fputs(".tviewbody { margin:5px; background-color:white;text-align:center;}\n",ptr->out); fputs(".tviewtitle {text-align:center;}\n",ptr->out); fputs(".tviewpre { margin:5px; background-color:white;}\n",ptr->out); #define CSS(id,col) fprintf(ptr->out,".tviewc%d {color:%s;}\n.tviewcu%d {color:%s;text-decoration:underline;}\n",id,col,id,col); CSS(0, "black"); CSS(1, "blue"); CSS(2, "green"); CSS(3, "yellow"); CSS(4, "black"); CSS(5, "green"); CSS(6, "cyan"); CSS(7, "yellow"); CSS(8, "red"); CSS(9, "blue"); #undef CSS fputs("</style>",ptr->out); fputs("</head><body>",ptr->out); fprintf(ptr->out,"<div class='tviewbody'><div class='tviewtitle'>%s:%d</div>", tv->header->target_name[tid], pos+1 ); fputs("<pre class='tviewpre'>",ptr->out); for(y=0;y< ptr->row_count;++y) { for(x=0;x< tv->mcol;++x) { if(x== 0 || ptr->screen[y][x].attributes != ptr->screen[y][x-1].attributes) { int css=0; fprintf(ptr->out,"<span"); while(css<32) { //if(y>1) fprintf(stderr,"css=%d pow2=%d vs %d\n",css,(1 << (css)),ptr->screen[y][x].attributes); if(( (ptr->screen[y][x].attributes) & (1 << (css)))!=0) { fprintf(ptr->out," class='tviewc%s%d'", (( (ptr->screen[y][x].attributes) & (1 << (UNDERLINE_FLAG)) )!=0?"u":""), css); break; } ++css; } fputs(">",ptr->out); } int ch=ptr->screen[y][x].ch; switch(ch) { case '<': fputs("&lt;",ptr->out);break; case '>': fputs("&gt;",ptr->out);break; case '&': fputs("&amp;",ptr->out);break; default: fputc(ch,ptr->out); break; } if(x+1 == tv->mcol || ptr->screen[y][x].attributes!=ptr->screen[y][x+1].attributes) { fputs("</span>",ptr->out); } } if(y+1 < ptr->row_count) fputs("<br/>",ptr->out); } fputs("</pre></div></body></html>",ptr->out); return 0; } #define ANSI_COLOR_RED "\x1b[31m" #define ANSI_COLOR_GREEN "\x1b[32m" #define ANSI_COLOR_YELLOW "\x1b[33m" #define ANSI_COLOR_BLUE "\x1b[34m" #define ANSI_COLOR_MAGENTA "\x1b[35m" #define ANSI_COLOR_CYAN "\x1b[36m" #define ANSI_COLOR_BLACK "\x1b[0m" #define ANSI_COLOR_RESET ANSI_COLOR_BLACK #define ANSI_UNDERLINE_SET "\033[4m" #define ANSI_UNDERLINE_UNSET "\033[0m" static int text_drawaln(struct AbstractTview* tv, int tid, int pos) { int y,x; html_tview_t* ptr=FROM_TV(tv); html_clear(tv); base_draw_aln(tv, tid, pos); int is_term= isatty(fileno(ptr->out)); for(y=0;y< ptr->row_count;++y) { for(x=0;x< tv->mcol;++x) { if(is_term) { int css=0; while(css<32) { if(( (ptr->screen[y][x].attributes) & (1 << (css)))!=0) { break; } ++css; } switch(css) { //CSS(0, "black"); case 1: fputs(ANSI_COLOR_BLUE,ptr->out); break; case 2: fputs(ANSI_COLOR_GREEN,ptr->out); break; case 3: fputs(ANSI_COLOR_YELLOW,ptr->out); break; //CSS(4, "black"); case 5: fputs(ANSI_COLOR_GREEN,ptr->out); break; case 6: fputs(ANSI_COLOR_CYAN,ptr->out); break; case 7: fputs(ANSI_COLOR_YELLOW,ptr->out); break; case 8: fputs(ANSI_COLOR_RED,ptr->out); break; case 9: fputs(ANSI_COLOR_BLUE,ptr->out); break; default:break; } if(( (ptr->screen[y][x].attributes) & (1 << (UNDERLINE_FLAG)))!=0) { fputs(ANSI_UNDERLINE_SET,ptr->out); } } int ch=ptr->screen[y][x].ch; fputc(ch,ptr->out); if(is_term) { fputs(ANSI_COLOR_RESET,ptr->out); if(( (ptr->screen[y][x].attributes) & (1 << (UNDERLINE_FLAG)))!=0) { fputs(ANSI_UNDERLINE_UNSET,ptr->out); } } } fputc('\n',ptr->out); } return 0; } static int html_loop(tview_t* tv) { //tv->my_drawaln(tv, tv->curr_tid, tv->left_pos); return 0; } static int html_underline(tview_t* tv) { return (1 << UNDERLINE_FLAG); } /* static void init_pair(html_tview_t *tv,int id_ge_1, const char* pen, const char* paper) { } */ tview_t* html_tv_init(const char *fn, const char *fn_fa, const char *samples) { char* colstr=getenv("COLUMNS"); html_tview_t *tv = (html_tview_t*)calloc(1, sizeof(html_tview_t)); tview_t* base=(tview_t*)tv; if(tv==0) { fprintf(stderr,"Calloc failed\n"); return 0; } tv->row_count=0; tv->screen=NULL; tv->out=stdout; tv->attributes=0; base_tv_init(base,fn,fn_fa,samples); /* initialize callbacks */ #define SET_CALLBACK(fun) base->my_##fun=html_##fun; SET_CALLBACK(destroy); SET_CALLBACK(mvprintw); SET_CALLBACK(mvaddch); SET_CALLBACK(attron); SET_CALLBACK(attroff); SET_CALLBACK(clear); SET_CALLBACK(colorpair); SET_CALLBACK(drawaln); SET_CALLBACK(loop); SET_CALLBACK(underline); #undef SET_CALLBACK if(colstr!=0) { base->mcol=atoi(colstr); if(base->mcol<10) base->mcol=80; } base->mrow=99999; /* init_pair(tv,1, "blue", "white"); init_pair(tv,2, "green", "white"); init_pair(tv,3, "yellow", "white"); init_pair(tv,4, "white", "white"); init_pair(tv,5, "green", "white"); init_pair(tv,6, "cyan", "white"); init_pair(tv,7, "yellow", "white"); init_pair(tv,8, "red", "white"); init_pair(tv,9, "blue", "white"); */ return base; } tview_t* text_tv_init(const char *fn, const char *fn_fa, const char *samples) { tview_t* tv=html_tv_init(fn,fn_fa,samples); tv->my_drawaln=text_drawaln; return tv; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bcftools/index.c
.c
8,256
337
#include <assert.h> #include <ctype.h> #include <sys/stat.h> #include "bam_endian.h" #include "kstring.h" #include "bcf.h" #ifdef _USE_KNETFILE #include "knetfile.h" #endif #define TAD_LIDX_SHIFT 13 typedef struct { int32_t n, m; uint64_t *offset; } bcf_lidx_t; struct __bcf_idx_t { int32_t n; bcf_lidx_t *index2; }; /************ * indexing * ************/ static inline void insert_offset2(bcf_lidx_t *index2, int _beg, int _end, uint64_t offset) { int i, beg, end; beg = _beg >> TAD_LIDX_SHIFT; end = (_end - 1) >> TAD_LIDX_SHIFT; if (index2->m < end + 1) { int old_m = index2->m; index2->m = end + 1; kroundup32(index2->m); index2->offset = (uint64_t*)realloc(index2->offset, index2->m * 8); memset(index2->offset + old_m, 0, 8 * (index2->m - old_m)); } if (beg == end) { if (index2->offset[beg] == 0) index2->offset[beg] = offset; } else { for (i = beg; i <= end; ++i) if (index2->offset[i] == 0) index2->offset[i] = offset; } if (index2->n < end + 1) index2->n = end + 1; } bcf_idx_t *bcf_idx_core(bcf_t *bp, bcf_hdr_t *h) { bcf_idx_t *idx; int32_t last_coor, last_tid; uint64_t last_off; kstring_t *str; BGZF *fp = bp->fp; bcf1_t *b; int ret; b = calloc(1, sizeof(bcf1_t)); str = calloc(1, sizeof(kstring_t)); idx = (bcf_idx_t*)calloc(1, sizeof(bcf_idx_t)); idx->n = h->n_ref; idx->index2 = calloc(h->n_ref, sizeof(bcf_lidx_t)); last_tid = 0xffffffffu; last_off = bgzf_tell(fp); last_coor = 0xffffffffu; while ((ret = bcf_read(bp, h, b)) > 0) { int end, tmp; if (last_tid != b->tid) { // change of chromosomes last_tid = b->tid; } else if (last_coor > b->pos) { fprintf(stderr, "[bcf_idx_core] the input is out of order\n"); free(str->s); free(str); free(idx); bcf_destroy(b); return 0; } tmp = strlen(b->ref); end = b->pos + (tmp > 0? tmp : 1); insert_offset2(&idx->index2[b->tid], b->pos, end, last_off); last_off = bgzf_tell(fp); last_coor = b->pos; } free(str->s); free(str); bcf_destroy(b); return idx; } void bcf_idx_destroy(bcf_idx_t *idx) { int i; if (idx == 0) return; for (i = 0; i < idx->n; ++i) free(idx->index2[i].offset); free(idx->index2); free(idx); } /****************** * index file I/O * ******************/ void bcf_idx_save(const bcf_idx_t *idx, BGZF *fp) { int32_t i, ti_is_be; ti_is_be = bam_is_big_endian(); bgzf_write(fp, "BCI\4", 4); if (ti_is_be) { uint32_t x = idx->n; bgzf_write(fp, bam_swap_endian_4p(&x), 4); } else bgzf_write(fp, &idx->n, 4); for (i = 0; i < idx->n; ++i) { bcf_lidx_t *index2 = idx->index2 + i; // write linear index (index2) if (ti_is_be) { int x = index2->n; bgzf_write(fp, bam_swap_endian_4p(&x), 4); } else bgzf_write(fp, &index2->n, 4); if (ti_is_be) { // big endian int x; for (x = 0; (int)x < index2->n; ++x) bam_swap_endian_8p(&index2->offset[x]); bgzf_write(fp, index2->offset, 8 * index2->n); for (x = 0; (int)x < index2->n; ++x) bam_swap_endian_8p(&index2->offset[x]); } else bgzf_write(fp, index2->offset, 8 * index2->n); } } static bcf_idx_t *bcf_idx_load_core(BGZF *fp) { int i, ti_is_be; char magic[4]; bcf_idx_t *idx; ti_is_be = bam_is_big_endian(); if (fp == 0) { fprintf(stderr, "[%s] fail to load index.\n", __func__); return 0; } bgzf_read(fp, magic, 4); if (strncmp(magic, "BCI\4", 4)) { fprintf(stderr, "[%s] wrong magic number.\n", __func__); return 0; } idx = (bcf_idx_t*)calloc(1, sizeof(bcf_idx_t)); bgzf_read(fp, &idx->n, 4); if (ti_is_be) bam_swap_endian_4p(&idx->n); idx->index2 = (bcf_lidx_t*)calloc(idx->n, sizeof(bcf_lidx_t)); for (i = 0; i < idx->n; ++i) { bcf_lidx_t *index2 = idx->index2 + i; int j; bgzf_read(fp, &index2->n, 4); if (ti_is_be) bam_swap_endian_4p(&index2->n); index2->m = index2->n; index2->offset = (uint64_t*)calloc(index2->m, 8); bgzf_read(fp, index2->offset, index2->n * 8); if (ti_is_be) for (j = 0; j < index2->n; ++j) bam_swap_endian_8p(&index2->offset[j]); } return idx; } bcf_idx_t *bcf_idx_load_local(const char *fnidx) { BGZF *fp; fp = bgzf_open(fnidx, "r"); if (fp) { bcf_idx_t *idx = bcf_idx_load_core(fp); bgzf_close(fp); return idx; } else return 0; } #ifdef _USE_KNETFILE static void download_from_remote(const char *url) { const int buf_size = 1 * 1024 * 1024; char *fn; FILE *fp; uint8_t *buf; knetFile *fp_remote; int l; if (strstr(url, "ftp://") != url && strstr(url, "http://") != url) return; l = strlen(url); for (fn = (char*)url + l - 1; fn >= url; --fn) if (*fn == '/') break; ++fn; // fn now points to the file name fp_remote = knet_open(url, "r"); if (fp_remote == 0) { fprintf(stderr, "[download_from_remote] fail to open remote file.\n"); return; } if ((fp = fopen(fn, "w")) == 0) { fprintf(stderr, "[download_from_remote] fail to create file in the working directory.\n"); knet_close(fp_remote); return; } buf = (uint8_t*)calloc(buf_size, 1); while ((l = knet_read(fp_remote, buf, buf_size)) != 0) fwrite(buf, 1, l, fp); free(buf); fclose(fp); knet_close(fp_remote); } #else static void download_from_remote(const char *url) { return; } #endif static char *get_local_version(const char *fn) { struct stat sbuf; char *fnidx = (char*)calloc(strlen(fn) + 5, 1); strcat(strcpy(fnidx, fn), ".bci"); if ((strstr(fnidx, "ftp://") == fnidx || strstr(fnidx, "http://") == fnidx)) { char *p, *url; int l = strlen(fnidx); for (p = fnidx + l - 1; p >= fnidx; --p) if (*p == '/') break; url = fnidx; fnidx = strdup(p + 1); if (stat(fnidx, &sbuf) == 0) { free(url); return fnidx; } fprintf(stderr, "[%s] downloading the index file...\n", __func__); download_from_remote(url); free(url); } if (stat(fnidx, &sbuf) == 0) return fnidx; free(fnidx); return 0; } bcf_idx_t *bcf_idx_load(const char *fn) { bcf_idx_t *idx; char *fname = get_local_version(fn); if (fname == 0) return 0; idx = bcf_idx_load_local(fname); free(fname); return idx; } int bcf_idx_build2(const char *fn, const char *_fnidx) { char *fnidx; BGZF *fpidx; bcf_t *bp; bcf_idx_t *idx; bcf_hdr_t *h; if ((bp = bcf_open(fn, "r")) == 0) { fprintf(stderr, "[bcf_idx_build2] fail to open the BAM file.\n"); return -1; } h = bcf_hdr_read(bp); idx = bcf_idx_core(bp, h); bcf_close(bp); if (_fnidx == 0) { fnidx = (char*)calloc(strlen(fn) + 5, 1); strcpy(fnidx, fn); strcat(fnidx, ".bci"); } else fnidx = strdup(_fnidx); fpidx = bgzf_open(fnidx, "w"); if (fpidx == 0) { fprintf(stderr, "[bcf_idx_build2] fail to create the index file.\n"); free(fnidx); bcf_idx_destroy(idx); return -1; } bcf_idx_save(idx, fpidx); bcf_idx_destroy(idx); bgzf_close(fpidx); free(fnidx); return 0; } int bcf_idx_build(const char *fn) { return bcf_idx_build2(fn, 0); } /******************************************** * parse a region in the format chr:beg-end * ********************************************/ int bcf_parse_region(void *str2id, const char *str, int *tid, int *begin, int *end) { char *s, *p; int i, l, k; l = strlen(str); p = s = (char*)malloc(l+1); /* squeeze out "," */ for (i = k = 0; i != l; ++i) if (str[i] != ',' && !isspace(str[i])) s[k++] = str[i]; s[k] = 0; for (i = 0; i != k; ++i) if (s[i] == ':') break; s[i] = 0; if ((*tid = bcf_str2id(str2id, s)) < 0) { free(s); return -1; } if (i == k) { /* dump the whole sequence */ *begin = 0; *end = 1<<29; free(s); return 0; } for (p = s + i + 1; i != k; ++i) if (s[i] == '-') break; *begin = atoi(p); if (i < k) { p = s + i + 1; *end = atoi(p); } else *end = 1<<29; if (*begin > 0) --*begin; free(s); if (*begin > *end) return -1; return 0; } /******************************* * retrieve a specified region * *******************************/ uint64_t bcf_idx_query(const bcf_idx_t *idx, int tid, int beg) { uint64_t min_off, *offset; int i; if (beg < 0) beg = 0; offset = idx->index2[tid].offset; for (i = beg>>TAD_LIDX_SHIFT; i < idx->index2[tid].n && offset[i] == 0; ++i); min_off = (i == idx->index2[tid].n)? offset[idx->index2[tid].n-1] : offset[i]; return min_off; } int bcf_main_index(int argc, char *argv[]) { if (argc == 1) { fprintf(stderr, "Usage: bcftools index <in.bcf>\n"); return 1; } bcf_idx_build(argv[1]); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bcftools/main.c
.c
5,184
192
#include <string.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> #include "knetfile.h" #include "bcf.h" #include "kseq.h" KSTREAM_INIT(gzFile, gzread, 0x10000) int bcfview(int argc, char *argv[]); int bcf_main_index(int argc, char *argv[]); #define BUF_SIZE 0x10000 int bcf_cat(int n, char * const *fn) { int i; bcf_t *out; uint8_t *buf; buf = malloc(BUF_SIZE); out = bcf_open("-", "w"); for (i = 0; i < n; ++i) { bcf_t *in; bcf_hdr_t *h; off_t end; struct stat s; in = bcf_open(fn[i], "r"); h = bcf_hdr_read(in); if (i == 0) bcf_hdr_write(out, h); bcf_hdr_destroy(h); #ifdef _USE_KNETFILE fstat(knet_fileno((knetFile*)in->fp->fp), &s); end = s.st_size - 28; while (knet_tell((knetFile*)in->fp->fp) < end) { int size = knet_tell((knetFile*)in->fp->fp) + BUF_SIZE < end? BUF_SIZE : end - knet_tell((knetFile*)in->fp->fp); knet_read(in->fp->fp, buf, size); fwrite(buf, 1, size, out->fp->fp); } #else abort(); // FIXME: not implemented #endif bcf_close(in); } bcf_close(out); free(buf); return 0; } extern double bcf_pair_freq(const bcf1_t *b0, const bcf1_t *b1, double f[4]); int bcf_main_ldpair(int argc, char *argv[]) { bcf_t *fp; bcf_hdr_t *h; bcf1_t *b0, *b1; bcf_idx_t *idx; kstring_t str; void *str2id; gzFile fplist; kstream_t *ks; int dret, lineno = 0; if (argc < 3) { fprintf(stderr, "Usage: bcftools ldpair <in.bcf> <in.list>\n"); return 1; } fplist = gzopen(argv[2], "rb"); ks = ks_init(fplist); memset(&str, 0, sizeof(kstring_t)); fp = bcf_open(argv[1], "rb"); h = bcf_hdr_read(fp); str2id = bcf_build_refhash(h); idx = bcf_idx_load(argv[1]); if (idx == 0) { fprintf(stderr, "[%s] No bcf index is found. Abort!\n", __func__); return 1; } b0 = calloc(1, sizeof(bcf1_t)); b1 = calloc(1, sizeof(bcf1_t)); while (ks_getuntil(ks, '\n', &str, &dret) >= 0) { char *p, *q; int k; int tid0 = -1, tid1 = -1, pos0 = -1, pos1 = -1; ++lineno; for (p = q = str.s, k = 0; *p; ++p) { if (*p == ' ' || *p == '\t') { *p = '\0'; if (k == 0) tid0 = bcf_str2id(str2id, q); else if (k == 1) pos0 = atoi(q) - 1; else if (k == 2) tid1 = strcmp(q, "=")? bcf_str2id(str2id, q) : tid0; else if (k == 3) pos1 = atoi(q) - 1; q = p + 1; ++k; } } if (k == 3) pos1 = atoi(q) - 1; if (tid0 >= 0 && tid1 >= 0 && pos0 >= 0 && pos1 >= 0) { uint64_t off; double r, f[4]; off = bcf_idx_query(idx, tid0, pos0); bgzf_seek(fp->fp, off, SEEK_SET); while (bcf_read(fp, h, b0) >= 0 && b0->pos != pos0); off = bcf_idx_query(idx, tid1, pos1); bgzf_seek(fp->fp, off, SEEK_SET); while (bcf_read(fp, h, b1) >= 0 && b1->pos != pos1); r = bcf_pair_freq(b0, b1, f); r *= r; printf("%s\t%d\t%s\t%d\t%.4g\t%.4g\t%.4g\t%.4g\t%.4g\n", h->ns[tid0], pos0+1, h->ns[tid1], pos1+1, r, f[0], f[1], f[2], f[3]); } //else fprintf(stderr, "[%s] Parse error at line %d.\n", __func__, lineno); } bcf_destroy(b0); bcf_destroy(b1); bcf_idx_destroy(idx); bcf_str2id_destroy(str2id); bcf_hdr_destroy(h); bcf_close(fp); free(str.s); ks_destroy(ks); gzclose(fplist); return 0; } int bcf_main_ld(int argc, char *argv[]) { bcf_t *fp; bcf_hdr_t *h; bcf1_t **b, *b0; int i, j, m, n; double f[4]; if (argc == 1) { fprintf(stderr, "Usage: bcftools ld <in.bcf>\n"); return 1; } fp = bcf_open(argv[1], "rb"); h = bcf_hdr_read(fp); // read the entire BCF m = n = 0; b = 0; b0 = calloc(1, sizeof(bcf1_t)); while (bcf_read(fp, h, b0) >= 0) { if (m == n) { m = m? m<<1 : 16; b = realloc(b, sizeof(void*) * m); } b[n] = calloc(1, sizeof(bcf1_t)); bcf_cpy(b[n++], b0); } bcf_destroy(b0); // compute pair-wise r^2 printf("%d\n", n); // the number of loci for (i = 0; i < n; ++i) { printf("%s:%d", h->ns[b[i]->tid], b[i]->pos + 1); for (j = 0; j < i; ++j) { double r = bcf_pair_freq(b[i], b[j], f); printf("\t%.3f", r*r); } printf("\t1.000\n"); } // free for (i = 0; i < n; ++i) bcf_destroy(b[i]); free(b); bcf_hdr_destroy(h); bcf_close(fp); return 0; } int main(int argc, char *argv[]) { if (argc == 1) { fprintf(stderr, "\n"); fprintf(stderr, "Program: bcftools (Tools for data in the VCF/BCF formats)\n"); fprintf(stderr, "Version: %s\n\n", BCF_VERSION); fprintf(stderr, "Usage: bcftools <command> <arguments>\n\n"); fprintf(stderr, "Command: view print, extract, convert and call SNPs from BCF\n"); fprintf(stderr, " index index BCF\n"); fprintf(stderr, " cat concatenate BCFs\n"); fprintf(stderr, " ld compute all-pair r^2\n"); fprintf(stderr, " ldpair compute r^2 between requested pairs\n"); fprintf(stderr, "\n"); return 1; } if (strcmp(argv[1], "view") == 0) return bcfview(argc-1, argv+1); else if (strcmp(argv[1], "index") == 0) return bcf_main_index(argc-1, argv+1); else if (strcmp(argv[1], "ld") == 0) return bcf_main_ld(argc-1, argv+1); else if (strcmp(argv[1], "ldpair") == 0) return bcf_main_ldpair(argc-1, argv+1); else if (strcmp(argv[1], "cat") == 0) return bcf_cat(argc-2, argv+2); // cat is different ... else { fprintf(stderr, "[main] Unrecognized command.\n"); return 1; } return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bcftools/em.c
.c
8,985
311
#include <stdlib.h> #include <string.h> #include <math.h> #include "bcf.h" #include "kmin.h" static double g_q2p[256]; #define ITER_MAX 50 #define ITER_TRY 10 #define EPS 1e-5 extern double kf_gammaq(double, double); /* Generic routines */ // get the 3 genotype likelihoods static double *get_pdg3(const bcf1_t *b) { double *pdg; const uint8_t *PL = 0; int i, PL_len = 0; // initialize g_q2p if necessary if (g_q2p[0] == 0.) for (i = 0; i < 256; ++i) g_q2p[i] = pow(10., -i / 10.); // set PL and PL_len for (i = 0; i < b->n_gi; ++i) { if (b->gi[i].fmt == bcf_str2int("PL", 2)) { PL = (const uint8_t*)b->gi[i].data; PL_len = b->gi[i].len; break; } } if (i == b->n_gi) return 0; // no PL // fill pdg pdg = malloc(3 * b->n_smpl * sizeof(double)); for (i = 0; i < b->n_smpl; ++i) { const uint8_t *pi = PL + i * PL_len; double *p = pdg + i * 3; p[0] = g_q2p[pi[2]]; p[1] = g_q2p[pi[1]]; p[2] = g_q2p[pi[0]]; } return pdg; } // estimate site allele frequency in a very naive and inaccurate way static double est_freq(int n, const double *pdg) { int i, gcnt[3], tmp1; // get a rough estimate of the genotype frequency gcnt[0] = gcnt[1] = gcnt[2] = 0; for (i = 0; i < n; ++i) { const double *p = pdg + i * 3; if (p[0] != 1. || p[1] != 1. || p[2] != 1.) { int which = p[0] > p[1]? 0 : 1; which = p[which] > p[2]? which : 2; ++gcnt[which]; } } tmp1 = gcnt[0] + gcnt[1] + gcnt[2]; return (tmp1 == 0)? -1.0 : (.5 * gcnt[1] + gcnt[2]) / tmp1; } /* Single-locus EM */ typedef struct { int beg, end; const double *pdg; } minaux1_t; static double prob1(double f, void *data) { minaux1_t *a = (minaux1_t*)data; double p = 1., l = 0., f3[3]; int i; // printf("brent %lg\n", f); if (f < 0 || f > 1) return 1e300; f3[0] = (1.-f)*(1.-f); f3[1] = 2.*f*(1.-f); f3[2] = f*f; for (i = a->beg; i < a->end; ++i) { const double *pdg = a->pdg + i * 3; p *= pdg[0] * f3[0] + pdg[1] * f3[1] + pdg[2] * f3[2]; if (p < 1e-200) l -= log(p), p = 1.; } return l - log(p); } // one EM iteration for allele frequency estimate static double freq_iter(double *f, const double *_pdg, int beg, int end) { double f0 = *f, f3[3], err; int i; // printf("em %lg\n", *f); f3[0] = (1.-f0)*(1.-f0); f3[1] = 2.*f0*(1.-f0); f3[2] = f0*f0; for (i = beg, f0 = 0.; i < end; ++i) { const double *pdg = _pdg + i * 3; f0 += (pdg[1] * f3[1] + 2. * pdg[2] * f3[2]) / (pdg[0] * f3[0] + pdg[1] * f3[1] + pdg[2] * f3[2]); } f0 /= (end - beg) * 2; err = fabs(f0 - *f); *f = f0; return err; } /* The following function combines EM and Brent's method. When the signal from * the data is strong, EM is faster but sometimes, EM may converge very slowly. * When this happens, we switch to Brent's method. The idea is learned from * Rasmus Nielsen. */ static double freqml(double f0, int beg, int end, const double *pdg) { int i; double f; for (i = 0, f = f0; i < ITER_TRY; ++i) if (freq_iter(&f, pdg, beg, end) < EPS) break; if (i == ITER_TRY) { // haven't converged yet; try Brent's method minaux1_t a; a.beg = beg; a.end = end; a.pdg = pdg; kmin_brent(prob1, f0 == f? .5*f0 : f0, f, (void*)&a, EPS, &f); } return f; } // one EM iteration for genotype frequency estimate static double g3_iter(double g[3], const double *_pdg, int beg, int end) { double err, gg[3]; int i; gg[0] = gg[1] = gg[2] = 0.; // printf("%lg,%lg,%lg\n", g[0], g[1], g[2]); for (i = beg; i < end; ++i) { double sum, tmp[3]; const double *pdg = _pdg + i * 3; tmp[0] = pdg[0] * g[0]; tmp[1] = pdg[1] * g[1]; tmp[2] = pdg[2] * g[2]; sum = (tmp[0] + tmp[1] + tmp[2]) * (end - beg); gg[0] += tmp[0] / sum; gg[1] += tmp[1] / sum; gg[2] += tmp[2] / sum; } err = fabs(gg[0] - g[0]) > fabs(gg[1] - g[1])? fabs(gg[0] - g[0]) : fabs(gg[1] - g[1]); err = err > fabs(gg[2] - g[2])? err : fabs(gg[2] - g[2]); g[0] = gg[0]; g[1] = gg[1]; g[2] = gg[2]; return err; } // perform likelihood ratio test static double lk_ratio_test(int n, int n1, const double *pdg, double f3[3][3]) { double r; int i; for (i = 0, r = 1.; i < n1; ++i) { const double *p = pdg + i * 3; r *= (p[0] * f3[1][0] + p[1] * f3[1][1] + p[2] * f3[1][2]) / (p[0] * f3[0][0] + p[1] * f3[0][1] + p[2] * f3[0][2]); } for (; i < n; ++i) { const double *p = pdg + i * 3; r *= (p[0] * f3[2][0] + p[1] * f3[2][1] + p[2] * f3[2][2]) / (p[0] * f3[0][0] + p[1] * f3[0][1] + p[2] * f3[0][2]); } return r; } // x[0]: ref frequency // x[1..3]: alt-alt, alt-ref, ref-ref frequenc // x[4]: HWE P-value // x[5..6]: group1 freq, group2 freq // x[7]: 1-degree P-value // x[8]: 2-degree P-value int bcf_em1(const bcf1_t *b, int n1, int flag, double x[10]) { double *pdg; int i, n, n2; if (b->n_alleles < 2) return -1; // one allele only // initialization if (n1 < 0 || n1 > b->n_smpl) n1 = 0; if (flag & 1<<7) flag |= 7<<5; // compute group freq if LRT is required if (flag & 0xf<<1) flag |= 0xf<<1; n = b->n_smpl; n2 = n - n1; pdg = get_pdg3(b); if (pdg == 0) return -1; for (i = 0; i < 10; ++i) x[i] = -1.; // set to negative { if ((x[0] = est_freq(n, pdg)) < 0.) { free(pdg); return -1; // no data } x[0] = freqml(x[0], 0, n, pdg); } if (flag & (0xf<<1|3<<8)) { // estimate the genotype frequency and test HWE double *g = x + 1, f3[3], r; f3[0] = g[0] = (1 - x[0]) * (1 - x[0]); f3[1] = g[1] = 2 * x[0] * (1 - x[0]); f3[2] = g[2] = x[0] * x[0]; for (i = 0; i < ITER_MAX; ++i) if (g3_iter(g, pdg, 0, n) < EPS) break; // Hardy-Weinberg equilibrium (HWE) for (i = 0, r = 1.; i < n; ++i) { double *p = pdg + i * 3; r *= (p[0] * g[0] + p[1] * g[1] + p[2] * g[2]) / (p[0] * f3[0] + p[1] * f3[1] + p[2] * f3[2]); } x[4] = kf_gammaq(.5, log(r)); } if ((flag & 7<<5) && n1 > 0 && n1 < n) { // group frequency x[5] = freqml(x[0], 0, n1, pdg); x[6] = freqml(x[0], n1, n, pdg); } if ((flag & 1<<7) && n1 > 0 && n1 < n) { // 1-degree P-value double f[3], f3[3][3], tmp; f[0] = x[0]; f[1] = x[5]; f[2] = x[6]; for (i = 0; i < 3; ++i) f3[i][0] = (1-f[i])*(1-f[i]), f3[i][1] = 2*f[i]*(1-f[i]), f3[i][2] = f[i]*f[i]; tmp = log(lk_ratio_test(n, n1, pdg, f3)); if (tmp < 0) tmp = 0; x[7] = kf_gammaq(.5, tmp); } if ((flag & 3<<8) && n1 > 0 && n1 < n) { // 2-degree P-value double g[3][3], tmp; for (i = 0; i < 3; ++i) memcpy(g[i], x + 1, 3 * sizeof(double)); for (i = 0; i < ITER_MAX; ++i) if (g3_iter(g[1], pdg, 0, n1) < EPS) break; for (i = 0; i < ITER_MAX; ++i) if (g3_iter(g[2], pdg, n1, n) < EPS) break; tmp = log(lk_ratio_test(n, n1, pdg, g)); if (tmp < 0) tmp = 0; x[8] = kf_gammaq(1., tmp); } // free free(pdg); return 0; } /* Two-locus EM (LD) */ #define _G1(h, k) ((h>>1&1) + (k>>1&1)) #define _G2(h, k) ((h&1) + (k&1)) // 0: the previous site; 1: the current site static int pair_freq_iter(int n, double *pdg[2], double f[4]) { double ff[4]; int i, k, h; // printf("%lf,%lf,%lf,%lf\n", f[0], f[1], f[2], f[3]); memset(ff, 0, 4 * sizeof(double)); for (i = 0; i < n; ++i) { double *p[2], sum, tmp; p[0] = pdg[0] + i * 3; p[1] = pdg[1] + i * 3; for (k = 0, sum = 0.; k < 4; ++k) for (h = 0; h < 4; ++h) sum += f[k] * f[h] * p[0][_G1(k,h)] * p[1][_G2(k,h)]; for (k = 0; k < 4; ++k) { tmp = f[0] * (p[0][_G1(0,k)] * p[1][_G2(0,k)] + p[0][_G1(k,0)] * p[1][_G2(k,0)]) + f[1] * (p[0][_G1(1,k)] * p[1][_G2(1,k)] + p[0][_G1(k,1)] * p[1][_G2(k,1)]) + f[2] * (p[0][_G1(2,k)] * p[1][_G2(2,k)] + p[0][_G1(k,2)] * p[1][_G2(k,2)]) + f[3] * (p[0][_G1(3,k)] * p[1][_G2(3,k)] + p[0][_G1(k,3)] * p[1][_G2(k,3)]); ff[k] += f[k] * tmp / sum; } } for (k = 0; k < 4; ++k) f[k] = ff[k] / (2 * n); return 0; } double bcf_pair_freq(const bcf1_t *b0, const bcf1_t *b1, double f[4]) { const bcf1_t *b[2]; int i, j, n_smpl; double *pdg[2], flast[4], r, f0[2]; // initialize others if (b0->n_smpl != b1->n_smpl) return -1; // different number of samples n_smpl = b0->n_smpl; b[0] = b0; b[1] = b1; f[0] = f[1] = f[2] = f[3] = -1.; if (b[0]->n_alleles < 2 || b[1]->n_alleles < 2) return -1; // one allele only pdg[0] = get_pdg3(b0); pdg[1] = get_pdg3(b1); if (pdg[0] == 0 || pdg[1] == 0) { free(pdg[0]); free(pdg[1]); return -1; } // set the initial value f0[0] = est_freq(n_smpl, pdg[0]); f0[1] = est_freq(n_smpl, pdg[1]); f[0] = (1 - f0[0]) * (1 - f0[1]); f[3] = f0[0] * f0[1]; f[1] = (1 - f0[0]) * f0[1]; f[2] = f0[0] * (1 - f0[1]); // iteration for (j = 0; j < ITER_MAX; ++j) { double eps = 0; memcpy(flast, f, 4 * sizeof(double)); pair_freq_iter(n_smpl, pdg, f); for (i = 0; i < 4; ++i) { double x = fabs(f[i] - flast[i]); if (x > eps) eps = x; } if (eps < EPS) break; } // free free(pdg[0]); free(pdg[1]); { // calculate r^2 double p[2], q[2], D; p[0] = f[0] + f[1]; q[0] = 1 - p[0]; p[1] = f[0] + f[2]; q[1] = 1 - p[1]; D = f[0] * f[3] - f[1] * f[2]; r = sqrt(D * D / (p[0] * p[1] * q[0] * q[1])); // printf("R(%lf,%lf,%lf,%lf)=%lf\n", f[0], f[1], f[2], f[3], r); if (isnan(r)) r = -1.; } return r; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bcftools/call1.c
.c
26,288
634
#include <unistd.h> #include <stdlib.h> #include <math.h> #include <zlib.h> #include <errno.h> #include "bcf.h" #include "prob1.h" #include "kstring.h" #include "time.h" #ifdef _WIN32 #define srand48(x) srand(x) #define lrand48() rand() #endif #include "kseq.h" KSTREAM_INIT(gzFile, gzread, 16384) #define VC_NO_GENO 2 #define VC_BCFOUT 4 #define VC_CALL 8 #define VC_VARONLY 16 #define VC_VCFIN 32 #define VC_UNCOMP 64 #define VC_KEEPALT 256 #define VC_ACGT_ONLY 512 #define VC_QCALL 1024 #define VC_CALL_GT 2048 #define VC_ADJLD 4096 #define VC_NO_INDEL 8192 #define VC_ANNO_MAX 16384 #define VC_FIX_PL 32768 #define VC_EM 0x10000 #define VC_PAIRCALL 0x20000 #define VC_QCNT 0x40000 #define VC_INDEL_ONLY 0x80000 typedef struct { int flag, prior_type, n1, n_sub, *sublist, n_perm; uint32_t *trio_aux; char *prior_file, **subsam, *fn_dict; uint8_t *ploidy; double theta, pref, indel_frac, min_perm_p, min_smpl_frac, min_lrt, min_ma_lrt; void *bed; } viewconf_t; void *bed_read(const char *fn); void bed_destroy(void *_h); int bed_overlap(const void *_h, const char *chr, int beg, int end); static double ttest(int n1, int n2, int a[4]) { extern double kf_betai(double a, double b, double x); double t, v, u1, u2; if (n1 == 0 || n2 == 0 || n1 + n2 < 3) return 1.0; u1 = (double)a[0] / n1; u2 = (double)a[2] / n2; if (u1 <= u2) return 1.; t = (u1 - u2) / sqrt(((a[1] - n1 * u1 * u1) + (a[3] - n2 * u2 * u2)) / (n1 + n2 - 2) * (1./n1 + 1./n2)); v = n1 + n2 - 2; // printf("%d,%d,%d,%d,%lf,%lf,%lf\n", a[0], a[1], a[2], a[3], t, u1, u2); return t < 0.? 1. : .5 * kf_betai(.5*v, .5, v/(v+t*t)); } static int test16_core(int anno[16], anno16_t *a) { extern double kt_fisher_exact(int n11, int n12, int n21, int n22, double *_left, double *_right, double *two); double left, right; int i; a->p[0] = a->p[1] = a->p[2] = a->p[3] = 1.; memcpy(a->d, anno, 4 * sizeof(int)); a->depth = anno[0] + anno[1] + anno[2] + anno[3]; a->is_tested = (anno[0] + anno[1] > 0 && anno[2] + anno[3] > 0); if (a->depth == 0) return -1; a->mq = (int)(sqrt((anno[9] + anno[11]) / a->depth) + .499); kt_fisher_exact(anno[0], anno[1], anno[2], anno[3], &left, &right, &a->p[0]); for (i = 1; i < 4; ++i) a->p[i] = ttest(anno[0] + anno[1], anno[2] + anno[3], anno+4*i); return 0; } int test16(bcf1_t *b, anno16_t *a) { char *p; int i, anno[16]; a->p[0] = a->p[1] = a->p[2] = a->p[3] = 1.; a->d[0] = a->d[1] = a->d[2] = a->d[3] = 0.; a->mq = a->depth = a->is_tested = 0; if ((p = strstr(b->info, "I16=")) == 0) return -1; p += 4; for (i = 0; i < 16; ++i) { errno = 0; anno[i] = strtol(p, &p, 10); if (anno[i] == 0 && (errno == EINVAL || errno == ERANGE)) return -2; ++p; } return test16_core(anno, a); } static int update_bcf1(bcf1_t *b, const bcf_p1aux_t *pa, const bcf_p1rst_t *pr, double pref, int flag, double em[10], int cons_llr, int64_t cons_gt) { kstring_t s; int has_I16, is_var; double fq, r; anno16_t a; has_I16 = test16(b, &a) >= 0? 1 : 0; //rm_info(b, "I16="); // FIXME: probably this function has a bug. If I move it below, I16 will not be removed! memset(&s, 0, sizeof(kstring_t)); kputc('\0', &s); kputs(b->ref, &s); kputc('\0', &s); kputs(b->alt, &s); kputc('\0', &s); kputc('\0', &s); kputs(b->info, &s); if (b->info[0]) kputc(';', &s); { // print EM if (em[0] >= 0) ksprintf(&s, "AF1=%.4g", 1 - em[0]); if (em[4] >= 0 && em[4] <= 0.05) ksprintf(&s, ";G3=%.4g,%.4g,%.4g;HWE=%.3g", em[3], em[2], em[1], em[4]); if (em[5] >= 0 && em[6] >= 0) ksprintf(&s, ";AF2=%.4g,%.4g", 1 - em[5], 1 - em[6]); if (em[7] >= 0) ksprintf(&s, ";LRT=%.3g", em[7]); if (em[8] >= 0) ksprintf(&s, ";LRT2=%.3g", em[8]); } if (cons_llr > 0) { ksprintf(&s, ";CLR=%d", cons_llr); if (cons_gt > 0) ksprintf(&s, ";UGT=%c%c%c;CGT=%c%c%c", cons_gt&0xff, cons_gt>>8&0xff, cons_gt>>16&0xff, cons_gt>>32&0xff, cons_gt>>40&0xff, cons_gt>>48&0xff); } if (pr == 0) { // if pr is unset, return kputc('\0', &s); kputs(b->fmt, &s); kputc('\0', &s); free(b->str); b->m_str = s.m; b->l_str = s.l; b->str = s.s; bcf_sync(b); return 1; } is_var = (pr->p_ref < pref); r = is_var? pr->p_ref : pr->p_var; // ksprintf(&s, ";CI95=%.4g,%.4g", pr->cil, pr->cih); // FIXME: when EM is not used, ";" should be omitted! ksprintf(&s, ";AC1=%d", pr->ac); if (has_I16) ksprintf(&s, ";DP4=%d,%d,%d,%d;MQ=%d", a.d[0], a.d[1], a.d[2], a.d[3], a.mq); fq = pr->p_ref_folded < 0.5? -4.343 * log(pr->p_ref_folded) : 4.343 * log(pr->p_var_folded); if (fq < -999) fq = -999; if (fq > 999) fq = 999; ksprintf(&s, ";FQ=%.3g", fq); if (pr->cmp[0] >= 0.) { // two sample groups int i, q[3]; for (i = 1; i < 3; ++i) { double x = pr->cmp[i] + pr->cmp[0]/2.; q[i] = x == 0? 255 : (int)(-4.343 * log(x) + .499); if (q[i] > 255) q[i] = 255; } if (pr->perm_rank >= 0) ksprintf(&s, ";PR=%d", pr->perm_rank); // ksprintf(&s, ";LRT3=%.3g", pr->lrt); ksprintf(&s, ";PCHI2=%.3g;PC2=%d,%d", q[1], q[2], pr->p_chi2); } if (has_I16 && a.is_tested) ksprintf(&s, ";PV4=%.2g,%.2g,%.2g,%.2g", a.p[0], a.p[1], a.p[2], a.p[3]); kputc('\0', &s); rm_info(&s, "QS="); rm_info(&s, "I16="); kputs(b->fmt, &s); kputc('\0', &s); free(b->str); b->m_str = s.m; b->l_str = s.l; b->str = s.s; b->qual = r < 1e-100? 999 : -4.343 * log(r); if (b->qual > 999) b->qual = 999; bcf_sync(b); if (!is_var) bcf_shrink_alt(b, 1); else if (!(flag&VC_KEEPALT)) bcf_shrink_alt(b, pr->rank0 < 2? 2 : pr->rank0+1); if (is_var && (flag&VC_CALL_GT)) { // call individual genotype int i, x, old_n_gi = b->n_gi; s.m = b->m_str; s.l = b->l_str - 1; s.s = b->str; kputs(":GT:GQ", &s); kputc('\0', &s); b->m_str = s.m; b->l_str = s.l; b->str = s.s; bcf_sync(b); for (i = 0; i < b->n_smpl; ++i) { x = bcf_p1_call_gt(pa, pr->f_exp, i); ((uint8_t*)b->gi[old_n_gi].data)[i] = (x&3) == 0? 1<<3|1 : (x&3) == 1? 1 : 0; ((uint8_t*)b->gi[old_n_gi+1].data)[i] = x>>2; } } return is_var; } static char **read_samples(const char *fn, int *_n) { gzFile fp; kstream_t *ks; kstring_t s; int dret, n = 0, max = 0; char **sam = 0; *_n = 0; s.l = s.m = 0; s.s = 0; fp = gzopen(fn, "r"); if (fp == 0) { // interpret as sample names, not as a file name const char *t = fn, *p = t; while (*t) { t++; if ( *t==',' || !*t ) { sam = realloc(sam, sizeof(void*)*(n+1)); sam[n] = (char*) malloc(sizeof(char)*(t-p+2)); memcpy(sam[n], p, t-p); sam[n][t-p] = 0; sam[n][t-p+1] = 2; // assume diploid p = t+1; n++; } } *_n = n; return sam; // fail to open file } ks = ks_init(fp); while (ks_getuntil(ks, 0, &s, &dret) >= 0) { int l; if (max == n) { max = max? max<<1 : 4; sam = realloc(sam, sizeof(void*)*max); } l = s.l; sam[n] = malloc(s.l + 2); strcpy(sam[n], s.s); sam[n][l+1] = 2; // by default, diploid if (dret != '\n') { if (ks_getuntil(ks, 0, &s, &dret) >= 0) { // read ploidy, 1 or 2 int x = (int)s.s[0] - '0'; if (x == 1 || x == 2) sam[n][l+1] = x; else fprintf(stderr, "(%s) ploidy can only be 1 or 2; assume diploid\n", __func__); } if (dret != '\n') ks_getuntil(ks, '\n', &s, &dret); } ++n; } ks_destroy(ks); gzclose(fp); free(s.s); *_n = n; return sam; } static void write_header(bcf_hdr_t *h) { kstring_t str; str.l = h->l_txt? h->l_txt - 1 : 0; str.m = str.l + 1; str.s = h->txt; if (!strstr(str.s, "##INFO=<ID=DP,")) kputs("##INFO=<ID=DP,Number=1,Type=Integer,Description=\"Raw read depth\">\n", &str); if (!strstr(str.s, "##INFO=<ID=DP4,")) kputs("##INFO=<ID=DP4,Number=4,Type=Integer,Description=\"# high-quality ref-forward bases, ref-reverse, alt-forward and alt-reverse bases\">\n", &str); if (!strstr(str.s, "##INFO=<ID=MQ,")) kputs("##INFO=<ID=MQ,Number=1,Type=Integer,Description=\"Root-mean-square mapping quality of covering reads\">\n", &str); if (!strstr(str.s, "##INFO=<ID=FQ,")) kputs("##INFO=<ID=FQ,Number=1,Type=Float,Description=\"Phred probability of all samples being the same\">\n", &str); if (!strstr(str.s, "##INFO=<ID=AF1,")) kputs("##INFO=<ID=AF1,Number=1,Type=Float,Description=\"Max-likelihood estimate of the first ALT allele frequency (assuming HWE)\">\n", &str); if (!strstr(str.s, "##INFO=<ID=AC1,")) kputs("##INFO=<ID=AC1,Number=1,Type=Float,Description=\"Max-likelihood estimate of the first ALT allele count (no HWE assumption)\">\n", &str); if (!strstr(str.s, "##INFO=<ID=AN,")) kputs("##INFO=<ID=AN,Number=1,Type=Integer,Description=\"Total number of alleles in called genotypes\">\n", &str); if (!strstr(str.s, "##INFO=<ID=IS,")) kputs("##INFO=<ID=IS,Number=2,Type=Float,Description=\"Maximum number of reads supporting an indel and fraction of indel reads\">\n", &str); if (!strstr(str.s, "##INFO=<ID=AC,")) kputs("##INFO=<ID=AC,Number=A,Type=Integer,Description=\"Allele count in genotypes for each ALT allele, in the same order as listed\">\n", &str); if (!strstr(str.s, "##INFO=<ID=G3,")) kputs("##INFO=<ID=G3,Number=3,Type=Float,Description=\"ML estimate of genotype frequencies\">\n", &str); if (!strstr(str.s, "##INFO=<ID=HWE,")) kputs("##INFO=<ID=HWE,Number=1,Type=Float,Description=\"Chi^2 based HWE test P-value based on G3\">\n", &str); if (!strstr(str.s, "##INFO=<ID=CLR,")) kputs("##INFO=<ID=CLR,Number=1,Type=Integer,Description=\"Log ratio of genotype likelihoods with and without the constraint\">\n", &str); if (!strstr(str.s, "##INFO=<ID=UGT,")) kputs("##INFO=<ID=UGT,Number=1,Type=String,Description=\"The most probable unconstrained genotype configuration in the trio\">\n", &str); if (!strstr(str.s, "##INFO=<ID=CGT,")) kputs("##INFO=<ID=CGT,Number=1,Type=String,Description=\"The most probable constrained genotype configuration in the trio\">\n", &str); // if (!strstr(str.s, "##INFO=<ID=CI95,")) // kputs("##INFO=<ID=CI95,Number=2,Type=Float,Description=\"Equal-tail Bayesian credible interval of the site allele frequency at the 95% level\">\n", &str); if (!strstr(str.s, "##INFO=<ID=PV4,")) kputs("##INFO=<ID=PV4,Number=4,Type=Float,Description=\"P-values for strand bias, baseQ bias, mapQ bias and tail distance bias\">\n", &str); if (!strstr(str.s, "##INFO=<ID=INDEL,")) kputs("##INFO=<ID=INDEL,Number=0,Type=Flag,Description=\"Indicates that the variant is an INDEL.\">\n", &str); if (!strstr(str.s, "##INFO=<ID=PC2,")) kputs("##INFO=<ID=PC2,Number=2,Type=Integer,Description=\"Phred probability of the nonRef allele frequency in group1 samples being larger (,smaller) than in group2.\">\n", &str); if (!strstr(str.s, "##INFO=<ID=PCHI2,")) kputs("##INFO=<ID=PCHI2,Number=1,Type=Float,Description=\"Posterior weighted chi^2 P-value for testing the association between group1 and group2 samples.\">\n", &str); if (!strstr(str.s, "##INFO=<ID=QCHI2,")) kputs("##INFO=<ID=QCHI2,Number=1,Type=Integer,Description=\"Phred scaled PCHI2.\">\n", &str); if (!strstr(str.s, "##INFO=<ID=RP,")) kputs("##INFO=<ID=PR,Number=1,Type=Integer,Description=\"# permutations yielding a smaller PCHI2.\">\n", &str); if (!strstr(str.s, "##INFO=<ID=QBD,")) kputs("##INFO=<ID=QBD,Number=1,Type=Float,Description=\"Quality by Depth: QUAL/#reads\">\n", &str); //if (!strstr(str.s, "##INFO=<ID=RPS,")) // kputs("##INFO=<ID=RPS,Number=3,Type=Float,Description=\"Read Position Stats: depth, average, stddev\">\n", &str); if (!strstr(str.s, "##INFO=<ID=RPB,")) kputs("##INFO=<ID=RPB,Number=1,Type=Float,Description=\"Read Position Bias\">\n", &str); if (!strstr(str.s, "##INFO=<ID=MDV,")) kputs("##INFO=<ID=MDV,Number=1,Type=Integer,Description=\"Maximum number of high-quality nonRef reads in samples\">\n", &str); if (!strstr(str.s, "##INFO=<ID=VDB,")) kputs("##INFO=<ID=VDB,Number=1,Type=Float,Description=\"Variant Distance Bias (v2) for filtering splice-site artefacts in RNA-seq data. Note: this version may be broken.\">\n", &str); if (!strstr(str.s, "##FORMAT=<ID=GT,")) kputs("##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">\n", &str); if (!strstr(str.s, "##FORMAT=<ID=GQ,")) kputs("##FORMAT=<ID=GQ,Number=1,Type=Integer,Description=\"Genotype Quality\">\n", &str); if (!strstr(str.s, "##FORMAT=<ID=GL,")) kputs("##FORMAT=<ID=GL,Number=3,Type=Float,Description=\"Likelihoods for RR,RA,AA genotypes (R=ref,A=alt)\">\n", &str); if (!strstr(str.s, "##FORMAT=<ID=DP,")) kputs("##FORMAT=<ID=DP,Number=1,Type=Integer,Description=\"# high-quality bases\">\n", &str); if (!strstr(str.s, "##FORMAT=<ID=DV,")) kputs("##FORMAT=<ID=DV,Number=1,Type=Integer,Description=\"# high-quality non-reference bases\">\n", &str); if (!strstr(str.s, "##FORMAT=<ID=SP,")) kputs("##FORMAT=<ID=SP,Number=1,Type=Integer,Description=\"Phred-scaled strand bias P-value\">\n", &str); if (!strstr(str.s, "##FORMAT=<ID=PL,")) kputs("##FORMAT=<ID=PL,Number=G,Type=Integer,Description=\"List of Phred-scaled genotype likelihoods\">\n", &str); h->l_txt = str.l + 1; h->txt = str.s; } double bcf_pair_freq(const bcf1_t *b0, const bcf1_t *b1, double f[4]); int bcfview(int argc, char *argv[]) { extern int bcf_2qcall(bcf_hdr_t *h, bcf1_t *b); extern void bcf_p1_indel_prior(bcf_p1aux_t *ma, double x); extern int bcf_fix_gt(bcf1_t *b); extern int bcf_anno_max(bcf1_t *b); extern int bcf_shuffle(bcf1_t *b, int seed); extern uint32_t *bcf_trio_prep(int is_x, int is_son); extern int bcf_trio_call(uint32_t *prep, const bcf1_t *b, int *llr, int64_t *gt); extern int bcf_pair_call(const bcf1_t *b); extern int bcf_min_diff(const bcf1_t *b); extern int bcf_p1_get_M(bcf_p1aux_t *b); extern gzFile bcf_p1_fp_lk; bcf_t *bp, *bout = 0; bcf1_t *b, *blast; int c, *seeds = 0; uint64_t n_processed = 0, qcnt[256]; viewconf_t vc; bcf_p1aux_t *p1 = 0; bcf_hdr_t *hin, *hout; int tid, begin, end; char moder[4], modew[4]; tid = begin = end = -1; memset(&vc, 0, sizeof(viewconf_t)); vc.prior_type = vc.n1 = -1; vc.theta = 1e-3; vc.pref = 0.5; vc.indel_frac = -1.; vc.n_perm = 0; vc.min_perm_p = 0.01; vc.min_smpl_frac = 0; vc.min_lrt = 1; vc.min_ma_lrt = -1; memset(qcnt, 0, 8 * 256); while ((c = getopt(argc, argv, "FN1:l:cC:eHAGvbSuP:t:p:QgLi:IMs:D:U:X:d:T:Ywm:K:")) >= 0) { switch (c) { case '1': vc.n1 = atoi(optarg); break; case 'l': vc.bed = bed_read(optarg); if (!vc.bed) { fprintf(stderr,"Could not read \"%s\"\n", optarg); return 1; } break; case 'D': vc.fn_dict = strdup(optarg); break; case 'F': vc.flag |= VC_FIX_PL; break; case 'N': vc.flag |= VC_ACGT_ONLY; break; case 'G': vc.flag |= VC_NO_GENO; break; case 'A': vc.flag |= VC_KEEPALT; break; case 'b': vc.flag |= VC_BCFOUT; break; case 'S': vc.flag |= VC_VCFIN; break; case 'c': vc.flag |= VC_CALL; break; case 'e': vc.flag |= VC_EM; break; case 'v': vc.flag |= VC_VARONLY | VC_CALL; break; case 'u': vc.flag |= VC_UNCOMP | VC_BCFOUT; break; case 'g': vc.flag |= VC_CALL_GT | VC_CALL; break; case 'I': vc.flag |= VC_NO_INDEL; break; case 'w': vc.flag |= VC_INDEL_ONLY; break; case 'M': vc.flag |= VC_ANNO_MAX; break; case 'Y': vc.flag |= VC_QCNT; break; case 'm': vc.min_ma_lrt = atof(optarg); break; case 't': vc.theta = atof(optarg); break; case 'p': vc.pref = atof(optarg); break; case 'i': vc.indel_frac = atof(optarg); break; case 'Q': vc.flag |= VC_QCALL; break; case 'L': vc.flag |= VC_ADJLD; break; case 'U': vc.n_perm = atoi(optarg); break; case 'C': vc.min_lrt = atof(optarg); break; case 'X': vc.min_perm_p = atof(optarg); break; case 'd': vc.min_smpl_frac = atof(optarg); break; case 'K': bcf_p1_fp_lk = gzopen(optarg, "w"); break; case 's': vc.subsam = read_samples(optarg, &vc.n_sub); vc.ploidy = calloc(vc.n_sub + 1, 1); for (tid = 0; tid < vc.n_sub; ++tid) vc.ploidy[tid] = vc.subsam[tid][strlen(vc.subsam[tid]) + 1]; tid = -1; break; case 'T': if (strcmp(optarg, "trioauto") == 0) vc.trio_aux = bcf_trio_prep(0, 0); else if (strcmp(optarg, "trioxd") == 0) vc.trio_aux = bcf_trio_prep(1, 0); else if (strcmp(optarg, "trioxs") == 0) vc.trio_aux = bcf_trio_prep(1, 1); else if (strcmp(optarg, "pair") == 0) vc.flag |= VC_PAIRCALL; else { fprintf(stderr, "[%s] Option '-T' can only take value trioauto, trioxd or trioxs.\n", __func__); return 1; } break; case 'P': if (strcmp(optarg, "full") == 0) vc.prior_type = MC_PTYPE_FULL; else if (strcmp(optarg, "cond2") == 0) vc.prior_type = MC_PTYPE_COND2; else if (strcmp(optarg, "flat") == 0) vc.prior_type = MC_PTYPE_FLAT; else vc.prior_file = strdup(optarg); break; } } if (argc == optind) { fprintf(stderr, "\n"); fprintf(stderr, "Usage: bcftools view [options] <in.bcf> [reg]\n\n"); fprintf(stderr, "Input/output options:\n\n"); fprintf(stderr, " -A keep all possible alternate alleles at variant sites\n"); fprintf(stderr, " -b output BCF instead of VCF\n"); fprintf(stderr, " -D FILE sequence dictionary for VCF->BCF conversion [null]\n"); fprintf(stderr, " -F PL generated by r921 or before (which generate old ordering)\n"); fprintf(stderr, " -G suppress all individual genotype information\n"); fprintf(stderr, " -l FILE list of sites (chr pos) or regions (BED) to output [all sites]\n"); fprintf(stderr, " -L calculate LD for adjacent sites\n"); fprintf(stderr, " -N skip sites where REF is not A/C/G/T\n"); fprintf(stderr, " -Q output the QCALL likelihood format\n"); fprintf(stderr, " -s FILE list of samples to use [all samples]\n"); fprintf(stderr, " -S input is VCF\n"); fprintf(stderr, " -u uncompressed BCF output (force -b)\n"); fprintf(stderr, "\nConsensus/variant calling options:\n\n"); fprintf(stderr, " -c SNP calling (force -e)\n"); fprintf(stderr, " -d FLOAT skip loci where less than FLOAT fraction of samples covered [0]\n"); fprintf(stderr, " -e likelihood based analyses\n"); fprintf(stderr, " -g call genotypes at variant sites (force -c)\n"); fprintf(stderr, " -i FLOAT indel-to-substitution ratio [%.4g]\n", vc.indel_frac); fprintf(stderr, " -I skip indels\n"); fprintf(stderr, " -m FLOAT alternative model for multiallelic and rare-variant calling, include if P(chi^2)>=FLOAT\n"); fprintf(stderr, " -p FLOAT variant if P(ref|D)<FLOAT [%.3g]\n", vc.pref); fprintf(stderr, " -P STR type of prior: full, cond2, flat [full]\n"); fprintf(stderr, " -t FLOAT scaled substitution mutation rate [%.4g]\n", vc.theta); fprintf(stderr, " -T STR constrained calling; STR can be: pair, trioauto, trioxd and trioxs (see manual) [null]\n"); fprintf(stderr, " -v output potential variant sites only (force -c)\n"); fprintf(stderr, "\nContrast calling and association test options:\n\n"); fprintf(stderr, " -1 INT number of group-1 samples [0]\n"); fprintf(stderr, " -C FLOAT posterior constrast for LRT<FLOAT and P(ref|D)<0.5 [%g]\n", vc.min_lrt); fprintf(stderr, " -U INT number of permutations for association testing (effective with -1) [0]\n"); fprintf(stderr, " -X FLOAT only perform permutations for P(chi^2)<FLOAT [%g]\n", vc.min_perm_p); fprintf(stderr, "\n"); return 1; } if (vc.flag & VC_CALL) vc.flag |= VC_EM; if ((vc.flag & VC_VCFIN) && (vc.flag & VC_BCFOUT) && vc.fn_dict == 0) { fprintf(stderr, "[%s] For VCF->BCF conversion please specify the sequence dictionary with -D\n", __func__); return 1; } if (vc.n1 <= 0) vc.n_perm = 0; // TODO: give a warning here! if (vc.n_perm > 0) { seeds = malloc(vc.n_perm * sizeof(int)); srand48(time(0)); for (c = 0; c < vc.n_perm; ++c) seeds[c] = lrand48(); } b = calloc(1, sizeof(bcf1_t)); blast = calloc(1, sizeof(bcf1_t)); strcpy(moder, "r"); if (!(vc.flag & VC_VCFIN)) strcat(moder, "b"); strcpy(modew, "w"); if (vc.flag & VC_BCFOUT) strcat(modew, "b"); if (vc.flag & VC_UNCOMP) strcat(modew, "u"); bp = vcf_open(argv[optind], moder); hin = hout = vcf_hdr_read(bp); if (vc.fn_dict && (vc.flag & VC_VCFIN)) vcf_dictread(bp, hin, vc.fn_dict); bout = vcf_open("-", modew); if (!(vc.flag & VC_QCALL)) { if (vc.n_sub) { vc.sublist = calloc(vc.n_sub, sizeof(int)); hout = bcf_hdr_subsam(hin, vc.n_sub, vc.subsam, vc.sublist); } write_header(hout); // always print the header vcf_hdr_write(bout, hout); } if (vc.flag & VC_CALL) { p1 = bcf_p1_init(hout->n_smpl, vc.ploidy); if (vc.prior_file) { if (bcf_p1_read_prior(p1, vc.prior_file) < 0) { fprintf(stderr, "[%s] fail to read the prior AFS.\n", __func__); return 1; } } else bcf_p1_init_prior(p1, vc.prior_type, vc.theta); if (vc.n1 > 0 && vc.min_lrt > 0.) { // set n1 bcf_p1_set_n1(p1, vc.n1); bcf_p1_init_subprior(p1, vc.prior_type, vc.theta); } if (vc.indel_frac > 0.) bcf_p1_indel_prior(p1, vc.indel_frac); // otherwise use the default indel_frac } if (optind + 1 < argc && !(vc.flag&VC_VCFIN)) { void *str2id = bcf_build_refhash(hout); if (bcf_parse_region(str2id, argv[optind+1], &tid, &begin, &end) >= 0) { bcf_idx_t *idx; idx = bcf_idx_load(argv[optind]); if (idx) { uint64_t off; off = bcf_idx_query(idx, tid, begin); if (off == 0) { fprintf(stderr, "[%s] no records in the query region.\n", __func__); return 1; // FIXME: a lot of memory leaks... } bgzf_seek(bp->fp, off, SEEK_SET); bcf_idx_destroy(idx); } } } if (bcf_p1_fp_lk && p1) { int32_t M = bcf_p1_get_M(p1); gzwrite(bcf_p1_fp_lk, &M, 4); } while (vcf_read(bp, hin, b) > 0) { int is_indel, cons_llr = -1; int64_t cons_gt = -1; double em[10]; if ((vc.flag & VC_VARONLY) && strcmp(b->alt, "X") == 0) continue; if ((vc.flag & VC_VARONLY) && vc.min_smpl_frac > 0.) { extern int bcf_smpl_covered(const bcf1_t *b); int n = bcf_smpl_covered(b); if ((double)n / b->n_smpl < vc.min_smpl_frac) continue; } if (vc.n_sub) bcf_subsam(vc.n_sub, vc.sublist, b); if (vc.flag & VC_FIX_PL) bcf_fix_pl(b); is_indel = bcf_is_indel(b); if ((vc.flag & VC_NO_INDEL) && is_indel) continue; if ((vc.flag & VC_INDEL_ONLY) && !is_indel) continue; if ((vc.flag & VC_ACGT_ONLY) && !is_indel) { int x; if (b->ref[0] == 0 || b->ref[1] != 0) continue; x = toupper(b->ref[0]); if (x != 'A' && x != 'C' && x != 'G' && x != 'T') continue; } if (vc.bed && !bed_overlap(vc.bed, hin->ns[b->tid], b->pos, b->pos + strlen(b->ref))) continue; if (tid >= 0) { int l = strlen(b->ref); l = b->pos + (l > 0? l : 1); if (b->tid != tid || b->pos >= end) break; if (!(l > begin && end > b->pos)) continue; } ++n_processed; if ((vc.flag & VC_QCNT) && !is_indel) { // summarize the difference int x = bcf_min_diff(b); if (x > 255) x = 255; if (x >= 0) ++qcnt[x]; } if (vc.flag & VC_QCALL) { // output QCALL format; STOP here bcf_2qcall(hout, b); continue; } if (vc.trio_aux) // do trio calling bcf_trio_call(vc.trio_aux, b, &cons_llr, &cons_gt); else if (vc.flag & VC_PAIRCALL) cons_llr = bcf_pair_call(b); if (vc.flag & (VC_CALL|VC_ADJLD|VC_EM)) bcf_gl2pl(b); if (vc.flag & VC_EM) bcf_em1(b, vc.n1, 0x1ff, em); else { int i; for (i = 0; i < 9; ++i) em[i] = -1.; } if ( !(vc.flag&VC_KEEPALT) && (vc.flag&VC_CALL) && vc.min_ma_lrt>=0 ) { bcf_p1_set_ploidy(b, p1); // could be improved: do this per site to allow pseudo-autosomal regions int gts = call_multiallelic_gt(b, p1, vc.min_ma_lrt, vc.flag&VC_VARONLY); if ( gts<=1 && vc.flag & VC_VARONLY ) continue; } else if (vc.flag & VC_CALL) { // call variants bcf_p1rst_t pr; int calret; gzwrite(bcf_p1_fp_lk, &b->tid, 4); gzwrite(bcf_p1_fp_lk, &b->pos, 4); gzwrite(bcf_p1_fp_lk, &em[0], sizeof(double)); calret = bcf_p1_cal(b, (em[7] >= 0 && em[7] < vc.min_lrt), p1, &pr); if (n_processed % 100000 == 0) { fprintf(stderr, "[%s] %ld sites processed.\n", __func__, (long)n_processed); bcf_p1_dump_afs(p1); } if (pr.p_ref >= vc.pref && (vc.flag & VC_VARONLY)) continue; if (vc.n_perm && vc.n1 > 0 && pr.p_chi2 < vc.min_perm_p) { // permutation test bcf_p1rst_t r; int i, n = 0; for (i = 0; i < vc.n_perm; ++i) { #ifdef BCF_PERM_LRT // LRT based permutation is much faster but less robust to artifacts double x[10]; bcf_shuffle(b, seeds[i]); bcf_em1(b, vc.n1, 1<<7, x); if (x[7] < em[7]) ++n; #else bcf_shuffle(b, seeds[i]); bcf_p1_cal(b, 1, p1, &r); if (pr.p_chi2 >= r.p_chi2) ++n; #endif } pr.perm_rank = n; } if (calret >= 0) update_bcf1(b, p1, &pr, vc.pref, vc.flag, em, cons_llr, cons_gt); } else if (vc.flag & VC_EM) update_bcf1(b, 0, 0, 0, vc.flag, em, cons_llr, cons_gt); if (vc.flag & VC_ADJLD) { // compute LD double f[4], r2; if ((r2 = bcf_pair_freq(blast, b, f)) >= 0) { kstring_t s; s.m = s.l = 0; s.s = 0; if (*b->info) kputc(';', &s); ksprintf(&s, "NEIR=%.3f;NEIF4=%.3f,%.3f,%.3f,%.3f", r2, f[0], f[1], f[2], f[3]); bcf_append_info(b, s.s, s.l); free(s.s); } bcf_cpy(blast, b); } if (vc.flag & VC_ANNO_MAX) bcf_anno_max(b); if (vc.flag & VC_NO_GENO) { // do not output GENO fields b->n_gi = 0; b->fmt[0] = '\0'; b->l_str = b->fmt - b->str + 1; } else bcf_fix_gt(b); vcf_write(bout, hout, b); } if (bcf_p1_fp_lk) gzclose(bcf_p1_fp_lk); if (vc.prior_file) free(vc.prior_file); if (vc.flag & VC_CALL) bcf_p1_dump_afs(p1); if (hin != hout) bcf_hdr_destroy(hout); bcf_hdr_destroy(hin); bcf_destroy(b); bcf_destroy(blast); vcf_close(bp); vcf_close(bout); if (vc.fn_dict) free(vc.fn_dict); if (vc.ploidy) free(vc.ploidy); if (vc.trio_aux) free(vc.trio_aux); if (vc.n_sub) { int i; for (i = 0; i < vc.n_sub; ++i) free(vc.subsam[i]); free(vc.subsam); free(vc.sublist); } if (vc.bed) bed_destroy(vc.bed); if (vc.flag & VC_QCNT) for (c = 0; c < 256; ++c) fprintf(stderr, "QT\t%d\t%lld\n", c, (long long)qcnt[c]); if (seeds) free(seeds); if (p1) bcf_p1_destroy(p1); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bcftools/mut.c
.c
3,816
128
#include <stdlib.h> #include <stdint.h> #include "bcf.h" #define MAX_GENO 359 int8_t seq_bitcnt[] = { 4, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; char *seq_nt16rev = "XACMGRSVTWYHKDBN"; uint32_t *bcf_trio_prep(int is_x, int is_son) { int i, j, k, n, map[10]; uint32_t *ret; ret = calloc(MAX_GENO, 4); for (i = 0, k = 0; i < 4; ++i) for (j = i; j < 4; ++j) map[k++] = 1<<i|1<<j; for (i = 0, n = 1; i < 10; ++i) { // father if (is_x && seq_bitcnt[map[i]] != 1) continue; if (is_x && is_son) { for (j = 0; j < 10; ++j) // mother for (k = 0; k < 10; ++k) // child if (seq_bitcnt[map[k]] == 1 && (map[j]&map[k])) ret[n++] = j<<16 | i<<8 | k; } else { for (j = 0; j < 10; ++j) // mother for (k = 0; k < 10; ++k) // child if ((map[i]&map[k]) && (map[j]&map[k]) && ((map[i]|map[j])&map[k]) == map[k]) ret[n++] = j<<16 | i<<8 | k; } } ret[0] = n - 1; return ret; } int bcf_trio_call(const uint32_t *prep, const bcf1_t *b, int *llr, int64_t *gt) { int i, j, k; const bcf_ginfo_t *PL; uint8_t *gl10; int map[10]; if (b->n_smpl != 3) return -1; // not a trio for (i = 0; i < b->n_gi; ++i) if (b->gi[i].fmt == bcf_str2int("PL", 2)) break; if (i == b->n_gi) return -1; // no PL gl10 = alloca(10 * b->n_smpl); if (bcf_gl10(b, gl10) < 0) { if (bcf_gl10_indel(b, gl10) < 0) return -1; } PL = b->gi + i; for (i = 0, k = 0; i < 4; ++i) for (j = i; j < 4; ++j) map[k++] = seq_nt16rev[1<<i|1<<j]; for (j = 0; j < 3; ++j) // check if ref hom is the most probable in all members if (((uint8_t*)PL->data)[j * PL->len] != 0) break; if (j < 3) { // we need to go through the complex procedure uint8_t *g[3]; int minc = 1<<30, minc_j = -1, minf = 0, gtf = 0, gtc = 0; g[0] = gl10; g[1] = gl10 + 10; g[2] = gl10 + 20; for (j = 1; j <= (int)prep[0]; ++j) { // compute LK with constraint int sum = g[0][prep[j]&0xff] + g[1][prep[j]>>8&0xff] + g[2][prep[j]>>16&0xff]; if (sum < minc) minc = sum, minc_j = j; } gtc |= map[prep[minc_j]&0xff]; gtc |= map[prep[minc_j]>>8&0xff]<<8; gtc |= map[prep[minc_j]>>16]<<16; for (j = 0; j < 3; ++j) { // compute LK without constraint int min = 1<<30, min_k = -1; for (k = 0; k < 10; ++k) if (g[j][k] < min) min = g[j][k], min_k = k; gtf |= map[min_k]<<(j*8); minf += min; } *llr = minc - minf; *gt = (int64_t)gtc<<32 | gtf; } else *llr = 0, *gt = -1; return 0; } int bcf_pair_call(const bcf1_t *b) { int i, j, k; const bcf_ginfo_t *PL; if (b->n_smpl != 2) return -1; // not a pair for (i = 0; i < b->n_gi; ++i) if (b->gi[i].fmt == bcf_str2int("PL", 2)) break; if (i == b->n_gi) return -1; // no PL PL = b->gi + i; for (j = 0; j < 2; ++j) // check if ref hom is the most probable in all members if (((uint8_t*)PL->data)[j * PL->len] != 0) break; if (j < 2) { // we need to go through the complex procedure uint8_t *g[2]; int minc = 1<<30, minf = 0; g[0] = PL->data; g[1] = (uint8_t*)PL->data + PL->len; for (j = 0; j < PL->len; ++j) // compute LK with constraint minc = minc < g[0][j] + g[1][j]? minc : g[0][j] + g[1][j]; for (j = 0; j < 2; ++j) { // compute LK without constraint int min = 1<<30; for (k = 0; k < PL->len; ++k) min = min < g[j][k]? min : g[j][k]; minf += min; } return minc - minf; } else return 0; } int bcf_min_diff(const bcf1_t *b) { int i, min = 1<<30; const bcf_ginfo_t *PL; for (i = 0; i < b->n_gi; ++i) if (b->gi[i].fmt == bcf_str2int("PL", 2)) break; if (i == b->n_gi) return -1; // no PL PL = b->gi + i; for (i = 0; i < b->n_smpl; ++i) { int m1, m2, j; const uint8_t *p = (uint8_t*)PL->data; m1 = m2 = 1<<30; for (j = 0; j < PL->len; ++j) { if ((int)p[j] < m1) m2 = m1, m1 = p[j]; else if ((int)p[j] < m2) m2 = p[j]; } min = min < m2 - m1? min : m2 - m1; } return min; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bcftools/prob1.c
.c
33,429
989
#include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <errno.h> #include <assert.h> #include <limits.h> #include <zlib.h> #include "prob1.h" #include "kstring.h" #include "kseq.h" KSTREAM_INIT(gzFile, gzread, 16384) #define MC_MAX_EM_ITER 16 #define MC_EM_EPS 1e-5 #define MC_DEF_INDEL 0.15 gzFile bcf_p1_fp_lk; unsigned char seq_nt4_table[256] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 /*'-'*/, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }; struct __bcf_p1aux_t { int n, M, n1, is_indel; uint8_t *ploidy; // haploid or diploid ONLY double *q2p, *pdg; // pdg -> P(D|g) double *phi, *phi_indel; double *z, *zswap; // aux for afs double *z1, *z2, *phi1, *phi2; // only calculated when n1 is set double **hg; // hypergeometric distribution double *lf; // log factorial double t, t1, t2; double *afs, *afs1; // afs: accumulative AFS; afs1: site posterior distribution const uint8_t *PL; // point to PL int PL_len; }; void bcf_p1_indel_prior(bcf_p1aux_t *ma, double x) { int i; for (i = 0; i < ma->M; ++i) ma->phi_indel[i] = ma->phi[i] * x; ma->phi_indel[ma->M] = 1. - ma->phi[ma->M] * x; } static void init_prior(int type, double theta, int M, double *phi) { int i; if (type == MC_PTYPE_COND2) { for (i = 0; i <= M; ++i) phi[i] = 2. * (i + 1) / (M + 1) / (M + 2); } else if (type == MC_PTYPE_FLAT) { for (i = 0; i <= M; ++i) phi[i] = 1. / (M + 1); } else { double sum; for (i = 0, sum = 0.; i < M; ++i) sum += (phi[i] = theta / (M - i)); phi[M] = 1. - sum; } } void bcf_p1_init_prior(bcf_p1aux_t *ma, int type, double theta) { init_prior(type, theta, ma->M, ma->phi); bcf_p1_indel_prior(ma, MC_DEF_INDEL); } void bcf_p1_init_subprior(bcf_p1aux_t *ma, int type, double theta) { if (ma->n1 <= 0 || ma->n1 >= ma->M) return; init_prior(type, theta, 2*ma->n1, ma->phi1); init_prior(type, theta, 2*(ma->n - ma->n1), ma->phi2); } int bcf_p1_read_prior(bcf_p1aux_t *ma, const char *fn) { gzFile fp; kstring_t s; kstream_t *ks; long double sum; int dret, k; memset(&s, 0, sizeof(kstring_t)); fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r"); ks = ks_init(fp); memset(ma->phi, 0, sizeof(double) * (ma->M + 1)); while (ks_getuntil(ks, '\n', &s, &dret) >= 0) { if (strstr(s.s, "[afs] ") == s.s) { char *p = s.s + 6; for (k = 0; k <= ma->M; ++k) { int x; double y; x = strtol(p, &p, 10); if (x != k && (errno == EINVAL || errno == ERANGE)) return -1; ++p; y = strtod(p, &p); if (y == 0. && (errno == EINVAL || errno == ERANGE)) return -1; ma->phi[ma->M - k] += y; } } } ks_destroy(ks); gzclose(fp); free(s.s); for (sum = 0., k = 0; k <= ma->M; ++k) sum += ma->phi[k]; fprintf(stderr, "[prior]"); for (k = 0; k <= ma->M; ++k) ma->phi[k] /= sum; for (k = 0; k <= ma->M; ++k) fprintf(stderr, " %d:%.3lg", k, ma->phi[ma->M - k]); fputc('\n', stderr); for (sum = 0., k = 1; k < ma->M; ++k) sum += ma->phi[ma->M - k] * (2.* k * (ma->M - k) / ma->M / (ma->M - 1)); fprintf(stderr, "[%s] heterozygosity=%lf, ", __func__, (double)sum); for (sum = 0., k = 1; k <= ma->M; ++k) sum += k * ma->phi[ma->M - k] / ma->M; fprintf(stderr, "theta=%lf\n", (double)sum); bcf_p1_indel_prior(ma, MC_DEF_INDEL); return 0; } bcf_p1aux_t *bcf_p1_init(int n, uint8_t *ploidy) { bcf_p1aux_t *ma; int i; ma = calloc(1, sizeof(bcf_p1aux_t)); ma->n1 = -1; ma->n = n; ma->M = 2 * n; if (ploidy) { ma->ploidy = malloc(n); memcpy(ma->ploidy, ploidy, n); for (i = 0, ma->M = 0; i < n; ++i) ma->M += ploidy[i]; if (ma->M == 2 * n) { free(ma->ploidy); ma->ploidy = 0; } } ma->q2p = calloc(256, sizeof(double)); ma->pdg = calloc(3 * ma->n, sizeof(double)); ma->phi = calloc(ma->M + 1, sizeof(double)); ma->phi_indel = calloc(ma->M + 1, sizeof(double)); ma->phi1 = calloc(ma->M + 1, sizeof(double)); ma->phi2 = calloc(ma->M + 1, sizeof(double)); ma->z = calloc(ma->M + 1, sizeof(double)); ma->zswap = calloc(ma->M + 1, sizeof(double)); ma->z1 = calloc(ma->M + 1, sizeof(double)); // actually we do not need this large ma->z2 = calloc(ma->M + 1, sizeof(double)); ma->afs = calloc(ma->M + 1, sizeof(double)); ma->afs1 = calloc(ma->M + 1, sizeof(double)); ma->lf = calloc(ma->M + 1, sizeof(double)); for (i = 0; i < 256; ++i) ma->q2p[i] = pow(10., -i / 10.); for (i = 0; i <= ma->M; ++i) ma->lf[i] = lgamma(i + 1); bcf_p1_init_prior(ma, MC_PTYPE_FULL, 1e-3); // the simplest prior return ma; } int bcf_p1_get_M(bcf_p1aux_t *b) { return b->M; } int bcf_p1_set_n1(bcf_p1aux_t *b, int n1) { if (n1 == 0 || n1 >= b->n) return -1; if (b->M != b->n * 2) { fprintf(stderr, "[%s] unable to set `n1' when there are haploid samples.\n", __func__); return -1; } b->n1 = n1; return 0; } void bcf_p1_set_ploidy(bcf1_t *b, bcf_p1aux_t *ma) { // bcf_p1aux_t fields are not visible outside of prob1.c, hence this wrapper. // Ideally, this should set ploidy per site to allow pseudo-autosomal regions b->ploidy = ma->ploidy; } void bcf_p1_destroy(bcf_p1aux_t *ma) { if (ma) { int k; free(ma->lf); if (ma->hg && ma->n1 > 0) { for (k = 0; k <= 2*ma->n1; ++k) free(ma->hg[k]); free(ma->hg); } free(ma->ploidy); free(ma->q2p); free(ma->pdg); free(ma->phi); free(ma->phi_indel); free(ma->phi1); free(ma->phi2); free(ma->z); free(ma->zswap); free(ma->z1); free(ma->z2); free(ma->afs); free(ma->afs1); free(ma); } } extern double kf_gammap(double s, double z); int test16(bcf1_t *b, anno16_t *a); // Wigginton 2005, PMID: 15789306 // written by Jan Wigginton double calc_hwe(int obs_hom1, int obs_hom2, int obs_hets) { if (obs_hom1 + obs_hom2 + obs_hets == 0 ) return 1; assert(obs_hom1 >= 0 && obs_hom2 >= 0 && obs_hets >= 0); int obs_homc = obs_hom1 < obs_hom2 ? obs_hom2 : obs_hom1; int obs_homr = obs_hom1 < obs_hom2 ? obs_hom1 : obs_hom2; int rare_copies = 2 * obs_homr + obs_hets; int genotypes = obs_hets + obs_homc + obs_homr; double *het_probs = (double*) calloc(rare_copies+1, sizeof(double)); /* start at midpoint */ int mid = rare_copies * (2 * genotypes - rare_copies) / (2 * genotypes); /* check to ensure that midpoint and rare alleles have same parity */ if ((rare_copies & 1) ^ (mid & 1)) mid++; int curr_hets = mid; int curr_homr = (rare_copies - mid) / 2; int curr_homc = genotypes - curr_hets - curr_homr; het_probs[mid] = 1.0; double sum = het_probs[mid]; for (curr_hets = mid; curr_hets > 1; curr_hets -= 2) { het_probs[curr_hets - 2] = het_probs[curr_hets] * curr_hets * (curr_hets - 1.0) / (4.0 * (curr_homr + 1.0) * (curr_homc + 1.0)); sum += het_probs[curr_hets - 2]; /* 2 fewer heterozygotes for next iteration -> add one rare, one common homozygote */ curr_homr++; curr_homc++; } curr_hets = mid; curr_homr = (rare_copies - mid) / 2; curr_homc = genotypes - curr_hets - curr_homr; for (curr_hets = mid; curr_hets <= rare_copies - 2; curr_hets += 2) { het_probs[curr_hets + 2] = het_probs[curr_hets] * 4.0 * curr_homr * curr_homc /((curr_hets + 2.0) * (curr_hets + 1.0)); sum += het_probs[curr_hets + 2]; /* add 2 heterozygotes for next iteration -> subtract one rare, one common homozygote */ curr_homr--; curr_homc--; } int i; for (i = 0; i <= rare_copies; i++) het_probs[i] /= sum; /* p-value calculation for p_hwe */ double p_hwe = 0.0; for (i = 0; i <= rare_copies; i++) { if (het_probs[i] > het_probs[obs_hets]) continue; p_hwe += het_probs[i]; } p_hwe = p_hwe > 1.0 ? 1.0 : p_hwe; free(het_probs); return p_hwe; } static void _bcf1_set_ref(bcf1_t *b, int idp) { kstring_t s; int old_n_gi = b->n_gi; s.m = b->m_str; s.l = b->l_str - 1; s.s = b->str; kputs(":GT", &s); kputc('\0', &s); b->m_str = s.m; b->l_str = s.l; b->str = s.s; bcf_sync(b); // Call GTs int isample, an = 0; for (isample = 0; isample < b->n_smpl; isample++) { if ( idp>=0 && ((uint16_t*)b->gi[idp].data)[isample]==0 ) ((uint8_t*)b->gi[old_n_gi].data)[isample] = 1<<7; else { ((uint8_t*)b->gi[old_n_gi].data)[isample] = 0; an += b->ploidy ? b->ploidy[isample] : 2; } } bcf_fit_alt(b,1); b->qual = 999; // Prepare BCF for output: ref, alt, filter, info, format memset(&s, 0, sizeof(kstring_t)); kputc('\0', &s); kputs(b->ref, &s); kputc('\0', &s); kputs(b->alt, &s); kputc('\0', &s); kputc('\0', &s); { ksprintf(&s, "AN=%d;", an); kputs(b->info, &s); anno16_t a; int has_I16 = test16(b, &a) >= 0? 1 : 0; if (has_I16 ) { if ( a.is_tested) ksprintf(&s, ";PV4=%.2g,%.2g,%.2g,%.2g", a.p[0], a.p[1], a.p[2], a.p[3]); ksprintf(&s, ";DP4=%d,%d,%d,%d;MQ=%d", a.d[0], a.d[1], a.d[2], a.d[3], a.mq); } kputc('\0', &s); rm_info(&s, "I16="); rm_info(&s, "QS="); } kputs(b->fmt, &s); kputc('\0', &s); free(b->str); b->m_str = s.m; b->l_str = s.l; b->str = s.s; bcf_sync(b); } int call_multiallelic_gt(bcf1_t *b, bcf_p1aux_t *ma, double threshold, int var_only) { int nals = 1; char *p; for (p=b->alt; *p; p++) { if ( *p=='X' || p[0]=='.' ) break; if ( p[0]==',' ) nals++; } if ( b->alt[0] && !*p ) nals++; if ( nals>4 ) { if ( *b->ref=='N' ) return 0; fprintf(stderr,"Not ready for this, more than 4 alleles at %d: %s, %s\n", b->pos+1, b->ref,b->alt); exit(1); } // find PL, DV and DP FORMAT indexes uint8_t *pl = NULL; int i, npl = 0, idp = -1, idv = -1; for (i = 0; i < b->n_gi; ++i) { if (b->gi[i].fmt == bcf_str2int("PL", 2)) { pl = (uint8_t*)b->gi[i].data; npl = b->gi[i].len; } else if (b->gi[i].fmt == bcf_str2int("DP", 2)) idp=i; else if (b->gi[i].fmt == bcf_str2int("DV", 2)) idv=i; } if ( nals==1 ) { if ( !var_only ) _bcf1_set_ref(b, idp); return 1; } if ( !pl ) return -1; assert(ma->q2p[0] == 1); // Init P(D|G) int npdg = nals*(nals+1)/2; double *pdg,*_pdg; _pdg = pdg = malloc(sizeof(double)*ma->n*npdg); for (i=0; i<ma->n; i++) { int j; double sum = 0; for (j=0; j<npdg; j++) { //_pdg[j] = pow(10,-0.1*pl[j]); _pdg[j] = ma->q2p[pl[j]]; sum += _pdg[j]; } if ( sum ) for (j=0; j<npdg; j++) _pdg[j] /= sum; _pdg += npdg; pl += npl; } if ((p = strstr(b->info, "QS=")) == 0) { fprintf(stderr,"INFO/QS is required with -m, exiting\n"); exit(1); } double qsum[4]; if ( sscanf(p+3,"%lf,%lf,%lf,%lf",&qsum[0],&qsum[1],&qsum[2],&qsum[3])!=4 ) { fprintf(stderr,"Could not parse %s\n",p); exit(1); } // Calculate the most likely combination of alleles, remembering the most and second most likely set int ia,ib,ic, max_als=0, max_als2=0; double ref_lk = 0, max_lk = INT_MIN, max_lk2 = INT_MIN, lk_sum = INT_MIN, lk_sums[3]; for (ia=0; ia<nals; ia++) { double lk_tot = 0; int iaa = (ia+1)*(ia+2)/2-1; int isample; for (isample=0; isample<ma->n; isample++) { double *p = pdg + isample*npdg; // assert( log(p[iaa]) <= 0 ); lk_tot += log(p[iaa]); } if ( ia==0 ) ref_lk = lk_tot; if ( max_lk<lk_tot ) { max_lk2 = max_lk; max_als2 = max_als; max_lk = lk_tot; max_als = 1<<ia; } else if ( max_lk2<lk_tot ) { max_lk2 = lk_tot; max_als2 = 1<<ia; } lk_sum = lk_tot>lk_sum ? lk_tot + log(1+exp(lk_sum-lk_tot)) : lk_sum + log(1+exp(lk_tot-lk_sum)); } lk_sums[0] = lk_sum; if ( nals>1 ) { for (ia=0; ia<nals; ia++) { if ( qsum[ia]==0 ) continue; int iaa = (ia+1)*(ia+2)/2-1; for (ib=0; ib<ia; ib++) { if ( qsum[ib]==0 ) continue; double lk_tot = 0; double fa = qsum[ia]/(qsum[ia]+qsum[ib]); double fb = qsum[ib]/(qsum[ia]+qsum[ib]); double fab = 2*fa*fb; fa *= fa; fb *= fb; int isample, ibb = (ib+1)*(ib+2)/2-1, iab = iaa - ia + ib; for (isample=0; isample<ma->n; isample++) { double *p = pdg + isample*npdg; //assert( log(fa*p[iaa] + fb*p[ibb] + fab*p[iab]) <= 0 ); if ( b->ploidy && b->ploidy[isample]==1 ) lk_tot += log(fa*p[iaa] + fb*p[ibb]); else lk_tot += log(fa*p[iaa] + fb*p[ibb] + fab*p[iab]); } if ( max_lk<lk_tot ) { max_lk2 = max_lk; max_als2 = max_als; max_lk = lk_tot; max_als = 1<<ia|1<<ib; } else if ( max_lk2<lk_tot ) { max_lk2 = lk_tot; max_als2 = 1<<ia|1<<ib; } lk_sum = lk_tot>lk_sum ? lk_tot + log(1+exp(lk_sum-lk_tot)) : lk_sum + log(1+exp(lk_tot-lk_sum)); } } lk_sums[1] = lk_sum; } if ( nals>2 ) { for (ia=0; ia<nals; ia++) { if ( qsum[ia]==0 ) continue; int iaa = (ia+1)*(ia+2)/2-1; for (ib=0; ib<ia; ib++) { if ( qsum[ib]==0 ) continue; int ibb = (ib+1)*(ib+2)/2-1; int iab = iaa - ia + ib; for (ic=0; ic<ib; ic++) { if ( qsum[ic]==0 ) continue; double lk_tot = 0; double fa = qsum[ia]/(qsum[ia]+qsum[ib]+qsum[ic]); double fb = qsum[ib]/(qsum[ia]+qsum[ib]+qsum[ic]); double fc = qsum[ic]/(qsum[ia]+qsum[ib]+qsum[ic]); double fab = 2*fa*fb, fac = 2*fa*fc, fbc = 2*fb*fc; fa *= fa; fb *= fb; fc *= fc; int isample, icc = (ic+1)*(ic+2)/2-1; int iac = iaa - ia + ic, ibc = ibb - ib + ic; for (isample=0; isample<ma->n; isample++) { double *p = pdg + isample*npdg; //assert( log(fa*p[iaa] + fb*p[ibb] + fc*p[icc] + fab*p[iab] + fac*p[iac] + fbc*p[ibc]) <= 0 ); if ( b->ploidy && b->ploidy[isample]==1 ) lk_tot += log(fa*p[iaa] + fb*p[ibb] + fc*p[icc]); else lk_tot += log(fa*p[iaa] + fb*p[ibb] + fc*p[icc] + fab*p[iab] + fac*p[iac] + fbc*p[ibc]); } if ( max_lk<lk_tot ) { max_lk2 = max_lk; max_als2 = max_als; max_lk = lk_tot; max_als = 1<<ia|1<<ib|1<<ic; } else if ( max_lk2<lk_tot ) { max_lk2 = lk_tot; max_als2 = 1<<ia|1<<ib|1<<ic; } lk_sum = lk_tot>lk_sum ? lk_tot + log(1+exp(lk_sum-lk_tot)) : lk_sum + log(1+exp(lk_tot-lk_sum)); } } } lk_sums[2] = lk_sum; } // Should we add another allele, does it increase the likelihood significantly? int n1=0, n2=0; for (i=0; i<nals; i++) if ( max_als&1<<i) n1++; for (i=0; i<nals; i++) if ( max_als2&1<<i) n2++; if ( n2<n1 && kf_gammap(1,2.0*(max_lk-max_lk2))<threshold ) { // the threshold not exceeded, use the second most likely set with fewer alleles max_lk = max_lk2; max_als = max_als2; n1 = n2; } lk_sum = lk_sums[n1-1]; // Get the BCF record ready for GT and GQ kstring_t s; int old_n_gi = b->n_gi; s.m = b->m_str; s.l = b->l_str - 1; s.s = b->str; kputs(":GT:GQ", &s); kputc('\0', &s); b->m_str = s.m; b->l_str = s.l; b->str = s.s; bcf_sync(b); // Call GTs int isample, gts=0, ac[4] = {0,0,0,0}; int nRR = 0, nAA = 0, nRA = 0, max_dv = 0; for (isample = 0; isample < b->n_smpl; isample++) { int ploidy = b->ploidy ? b->ploidy[isample] : 2; double *p = pdg + isample*npdg; int ia, als = 0; double lk = 0, lk_s = 0; for (ia=0; ia<nals; ia++) { if ( !(max_als&1<<ia) ) continue; int iaa = (ia+1)*(ia+2)/2-1; double _lk = p[iaa]*qsum[ia]*qsum[ia]; if ( _lk > lk ) { lk = _lk; als = ia<<3 | ia; } lk_s += _lk; } if ( ploidy==2 ) { for (ia=0; ia<nals; ia++) { if ( !(max_als&1<<ia) ) continue; int iaa = (ia+1)*(ia+2)/2-1; for (ib=0; ib<ia; ib++) { if ( !(max_als&1<<ib) ) continue; int iab = iaa - ia + ib; double _lk = 2*qsum[ia]*qsum[ib]*p[iab]; if ( _lk > lk ) { lk = _lk; als = ib<<3 | ia; } lk_s += _lk; } } } lk = -log(1-lk/lk_s)/0.2302585; int dp = 0; if ( idp>=0 && (dp=((uint16_t*)b->gi[idp].data)[isample])==0 ) { // no coverage ((uint8_t*)b->gi[old_n_gi].data)[isample] = 1<<7; ((uint8_t*)b->gi[old_n_gi+1].data)[isample] = 0; continue; } if ( lk>99 ) lk = 99; ((uint8_t*)b->gi[old_n_gi].data)[isample] = als; ((uint8_t*)b->gi[old_n_gi+1].data)[isample] = (int)lk; // For MDV annotation int dv; if ( als && idv>=0 && (dv=((uint16_t*)b->gi[idv].data)[isample]) ) { if ( max_dv < dv ) max_dv = dv; } // For HWE annotation; multiple ALT alleles treated as one if ( !als ) nRR++; else if ( !(als>>3&7) || !(als&7) ) nRA++; else nAA++; gts |= 1<<(als>>3&7) | 1<<(als&7); ac[ als>>3&7 ]++; ac[ als&7 ]++; } free(pdg); bcf_fit_alt(b,max_als); // The VCF spec is ambiguous about QUAL: is it the probability of anything else // (that is QUAL(non-ref) = P(ref)+P(any non-ref other than ALT)) or is it // QUAL(non-ref)=P(ref) and QUAL(ref)=1-P(ref)? Assuming the latter. b->qual = gts>1 ? -4.343*(ref_lk - lk_sum) : -4.343*log(1-exp(ref_lk - lk_sum)); if ( b->qual>999 ) b->qual = 999; // Prepare BCF for output: ref, alt, filter, info, format memset(&s, 0, sizeof(kstring_t)); kputc('\0', &s); kputs(b->ref, &s); kputc('\0', &s); kputs(b->alt, &s); kputc('\0', &s); kputc('\0', &s); { int an=0, nalts=0; for (i=0; i<nals; i++) { an += ac[i]; if ( i>0 && ac[i] ) nalts++; } ksprintf(&s, "AN=%d;", an); if ( nalts ) { kputs("AC=", &s); for (i=1; i<nals; i++) { if ( !(gts&1<<i) ) continue; nalts--; ksprintf(&s,"%d", ac[i]); if ( nalts>0 ) kputc(',', &s); } kputc(';', &s); } kputs(b->info, &s); anno16_t a; int has_I16 = test16(b, &a) >= 0? 1 : 0; if (has_I16 ) { if ( a.is_tested) ksprintf(&s, ";PV4=%.2g,%.2g,%.2g,%.2g", a.p[0], a.p[1], a.p[2], a.p[3]); ksprintf(&s, ";DP4=%d,%d,%d,%d;MQ=%d", a.d[0], a.d[1], a.d[2], a.d[3], a.mq); ksprintf(&s, ";QBD=%e", b->qual/(a.d[0] + a.d[1] + a.d[2] + a.d[3])); if ( max_dv ) ksprintf(&s, ";MDV=%d", max_dv); } if ( nAA+nRA ) { double hwe = calc_hwe(nAA, nRR, nRA); ksprintf(&s, ";HWE=%e", hwe); } kputc('\0', &s); rm_info(&s, "I16="); rm_info(&s, "QS="); } kputs(b->fmt, &s); kputc('\0', &s); free(b->str); b->m_str = s.m; b->l_str = s.l; b->str = s.s; bcf_sync(b); return gts; } static int cal_pdg(const bcf1_t *b, bcf_p1aux_t *ma) { int i, j; long *p, tmp; p = alloca(b->n_alleles * sizeof(long)); memset(p, 0, sizeof(long) * b->n_alleles); for (j = 0; j < ma->n; ++j) { const uint8_t *pi = ma->PL + j * ma->PL_len; double *pdg = ma->pdg + j * 3; pdg[0] = ma->q2p[pi[2]]; pdg[1] = ma->q2p[pi[1]]; pdg[2] = ma->q2p[pi[0]]; for (i = 0; i < b->n_alleles; ++i) p[i] += (int)pi[(i+1)*(i+2)/2-1]; } for (i = 0; i < b->n_alleles; ++i) p[i] = p[i]<<4 | i; for (i = 1; i < b->n_alleles; ++i) // insertion sort for (j = i; j > 0 && p[j] < p[j-1]; --j) tmp = p[j], p[j] = p[j-1], p[j-1] = tmp; for (i = b->n_alleles - 1; i >= 0; --i) if ((p[i]&0xf) == 0) break; return i; } int bcf_p1_call_gt(const bcf_p1aux_t *ma, double f0, int k) { double sum, g[3]; double max, f3[3], *pdg = ma->pdg + k * 3; int q, i, max_i, ploidy; ploidy = ma->ploidy? ma->ploidy[k] : 2; if (ploidy == 2) { f3[0] = (1.-f0)*(1.-f0); f3[1] = 2.*f0*(1.-f0); f3[2] = f0*f0; } else { f3[0] = 1. - f0; f3[1] = 0; f3[2] = f0; } for (i = 0, sum = 0.; i < 3; ++i) sum += (g[i] = pdg[i] * f3[i]); for (i = 0, max = -1., max_i = 0; i < 3; ++i) { g[i] /= sum; if (g[i] > max) max = g[i], max_i = i; } max = 1. - max; if (max < 1e-308) max = 1e-308; q = (int)(-4.343 * log(max) + .499); if (q > 99) q = 99; return q<<2|max_i; } #define TINY 1e-20 static void mc_cal_y_core(bcf_p1aux_t *ma, int beg) { double *z[2], *tmp, *pdg; int _j, last_min, last_max; assert(beg == 0 || ma->M == ma->n*2); z[0] = ma->z; z[1] = ma->zswap; pdg = ma->pdg; memset(z[0], 0, sizeof(double) * (ma->M + 1)); memset(z[1], 0, sizeof(double) * (ma->M + 1)); z[0][0] = 1.; last_min = last_max = 0; ma->t = 0.; if (ma->M == ma->n * 2) { int M = 0; for (_j = beg; _j < ma->n; ++_j) { int k, j = _j - beg, _min = last_min, _max = last_max, M0; double p[3], sum; M0 = M; M += 2; pdg = ma->pdg + _j * 3; p[0] = pdg[0]; p[1] = 2. * pdg[1]; p[2] = pdg[2]; for (; _min < _max && z[0][_min] < TINY; ++_min) z[0][_min] = z[1][_min] = 0.; for (; _max > _min && z[0][_max] < TINY; --_max) z[0][_max] = z[1][_max] = 0.; _max += 2; if (_min == 0) k = 0, z[1][k] = (M0-k+1) * (M0-k+2) * p[0] * z[0][k]; if (_min <= 1) k = 1, z[1][k] = (M0-k+1) * (M0-k+2) * p[0] * z[0][k] + k*(M0-k+2) * p[1] * z[0][k-1]; for (k = _min < 2? 2 : _min; k <= _max; ++k) z[1][k] = (M0-k+1)*(M0-k+2) * p[0] * z[0][k] + k*(M0-k+2) * p[1] * z[0][k-1] + k*(k-1)* p[2] * z[0][k-2]; for (k = _min, sum = 0.; k <= _max; ++k) sum += z[1][k]; ma->t += log(sum / (M * (M - 1.))); for (k = _min; k <= _max; ++k) z[1][k] /= sum; if (_min >= 1) z[1][_min-1] = 0.; if (_min >= 2) z[1][_min-2] = 0.; if (j < ma->n - 1) z[1][_max+1] = z[1][_max+2] = 0.; if (_j == ma->n1 - 1) { // set pop1; ma->n1==-1 when unset ma->t1 = ma->t; memcpy(ma->z1, z[1], sizeof(double) * (ma->n1 * 2 + 1)); } tmp = z[0]; z[0] = z[1]; z[1] = tmp; last_min = _min; last_max = _max; } //for (_j = 0; _j < last_min; ++_j) z[0][_j] = 0.; // TODO: are these necessary? //for (_j = last_max + 1; _j < ma->M; ++_j) z[0][_j] = 0.; } else { // this block is very similar to the block above; these two might be merged in future int j, M = 0; for (j = 0; j < ma->n; ++j) { int k, M0, _min = last_min, _max = last_max; double p[3], sum; pdg = ma->pdg + j * 3; for (; _min < _max && z[0][_min] < TINY; ++_min) z[0][_min] = z[1][_min] = 0.; for (; _max > _min && z[0][_max] < TINY; --_max) z[0][_max] = z[1][_max] = 0.; M0 = M; M += ma->ploidy[j]; if (ma->ploidy[j] == 1) { p[0] = pdg[0]; p[1] = pdg[2]; _max++; if (_min == 0) k = 0, z[1][k] = (M0+1-k) * p[0] * z[0][k]; for (k = _min < 1? 1 : _min; k <= _max; ++k) z[1][k] = (M0+1-k) * p[0] * z[0][k] + k * p[1] * z[0][k-1]; for (k = _min, sum = 0.; k <= _max; ++k) sum += z[1][k]; ma->t += log(sum / M); for (k = _min; k <= _max; ++k) z[1][k] /= sum; if (_min >= 1) z[1][_min-1] = 0.; if (j < ma->n - 1) z[1][_max+1] = 0.; } else if (ma->ploidy[j] == 2) { p[0] = pdg[0]; p[1] = 2 * pdg[1]; p[2] = pdg[2]; _max += 2; if (_min == 0) k = 0, z[1][k] = (M0-k+1) * (M0-k+2) * p[0] * z[0][k]; if (_min <= 1) k = 1, z[1][k] = (M0-k+1) * (M0-k+2) * p[0] * z[0][k] + k*(M0-k+2) * p[1] * z[0][k-1]; for (k = _min < 2? 2 : _min; k <= _max; ++k) z[1][k] = (M0-k+1)*(M0-k+2) * p[0] * z[0][k] + k*(M0-k+2) * p[1] * z[0][k-1] + k*(k-1)* p[2] * z[0][k-2]; for (k = _min, sum = 0.; k <= _max; ++k) sum += z[1][k]; ma->t += log(sum / (M * (M - 1.))); for (k = _min; k <= _max; ++k) z[1][k] /= sum; if (_min >= 1) z[1][_min-1] = 0.; if (_min >= 2) z[1][_min-2] = 0.; if (j < ma->n - 1) z[1][_max+1] = z[1][_max+2] = 0.; } tmp = z[0]; z[0] = z[1]; z[1] = tmp; last_min = _min; last_max = _max; } } if (z[0] != ma->z) memcpy(ma->z, z[0], sizeof(double) * (ma->M + 1)); if (bcf_p1_fp_lk) gzwrite(bcf_p1_fp_lk, ma->z, sizeof(double) * (ma->M + 1)); } static void mc_cal_y(bcf_p1aux_t *ma) { if (ma->n1 > 0 && ma->n1 < ma->n && ma->M == ma->n * 2) { // NB: ma->n1 is ineffective when there are haploid samples int k; long double x; memset(ma->z1, 0, sizeof(double) * (2 * ma->n1 + 1)); memset(ma->z2, 0, sizeof(double) * (2 * (ma->n - ma->n1) + 1)); ma->t1 = ma->t2 = 0.; mc_cal_y_core(ma, ma->n1); ma->t2 = ma->t; memcpy(ma->z2, ma->z, sizeof(double) * (2 * (ma->n - ma->n1) + 1)); mc_cal_y_core(ma, 0); // rescale z x = expl(ma->t - (ma->t1 + ma->t2)); for (k = 0; k <= ma->M; ++k) ma->z[k] *= x; } else mc_cal_y_core(ma, 0); } #define CONTRAST_TINY 1e-30 extern double kf_gammaq(double s, double z); // incomplete gamma function for chi^2 test static inline double chi2_test(int a, int b, int c, int d) { double x, z; x = (double)(a+b) * (c+d) * (b+d) * (a+c); if (x == 0.) return 1; z = a * d - b * c; return kf_gammaq(.5, .5 * z * z * (a+b+c+d) / x); } // chi2=(a+b+c+d)(ad-bc)^2/[(a+b)(c+d)(a+c)(b+d)] static inline double contrast2_aux(const bcf_p1aux_t *p1, double sum, int k1, int k2, double x[3]) { double p = p1->phi[k1+k2] * p1->z1[k1] * p1->z2[k2] / sum * p1->hg[k1][k2]; int n1 = p1->n1, n2 = p1->n - p1->n1; if (p < CONTRAST_TINY) return -1; if (.5*k1/n1 < .5*k2/n2) x[1] += p; else if (.5*k1/n1 > .5*k2/n2) x[2] += p; else x[0] += p; return p * chi2_test(k1, k2, (n1<<1) - k1, (n2<<1) - k2); } static double contrast2(bcf_p1aux_t *p1, double ret[3]) { int k, k1, k2, k10, k20, n1, n2; double sum; // get n1 and n2 n1 = p1->n1; n2 = p1->n - p1->n1; if (n1 <= 0 || n2 <= 0) return 0.; if (p1->hg == 0) { // initialize the hypergeometric distribution /* NB: the hg matrix may take a lot of memory when there are many samples. There is a way to avoid precomputing this matrix, but it is slower and quite intricate. The following computation in this block can be accelerated with a similar strategy, but perhaps this is not a serious concern for now. */ double tmp = lgamma(2*(n1+n2)+1) - (lgamma(2*n1+1) + lgamma(2*n2+1)); p1->hg = calloc(2*n1+1, sizeof(void*)); for (k1 = 0; k1 <= 2*n1; ++k1) { p1->hg[k1] = calloc(2*n2+1, sizeof(double)); for (k2 = 0; k2 <= 2*n2; ++k2) p1->hg[k1][k2] = exp(lgamma(k1+k2+1) + lgamma(p1->M-k1-k2+1) - (lgamma(k1+1) + lgamma(k2+1) + lgamma(2*n1-k1+1) + lgamma(2*n2-k2+1) + tmp)); } } { // compute long double suml = 0; for (k = 0; k <= p1->M; ++k) suml += p1->phi[k] * p1->z[k]; sum = suml; } { // get the max k1 and k2 double max; int max_k; for (k = 0, max = 0, max_k = -1; k <= 2*n1; ++k) { double x = p1->phi1[k] * p1->z1[k]; if (x > max) max = x, max_k = k; } k10 = max_k; for (k = 0, max = 0, max_k = -1; k <= 2*n2; ++k) { double x = p1->phi2[k] * p1->z2[k]; if (x > max) max = x, max_k = k; } k20 = max_k; } { // We can do the following with one nested loop, but that is an O(N^2) thing. The following code block is much faster for large N. double x[3], y; long double z = 0., L[2]; x[0] = x[1] = x[2] = 0; L[0] = L[1] = 0; for (k1 = k10; k1 >= 0; --k1) { for (k2 = k20; k2 >= 0; --k2) { if ((y = contrast2_aux(p1, sum, k1, k2, x)) < 0) break; else z += y; } for (k2 = k20 + 1; k2 <= 2*n2; ++k2) { if ((y = contrast2_aux(p1, sum, k1, k2, x)) < 0) break; else z += y; } } ret[0] = x[0]; ret[1] = x[1]; ret[2] = x[2]; x[0] = x[1] = x[2] = 0; for (k1 = k10 + 1; k1 <= 2*n1; ++k1) { for (k2 = k20; k2 >= 0; --k2) { if ((y = contrast2_aux(p1, sum, k1, k2, x)) < 0) break; else z += y; } for (k2 = k20 + 1; k2 <= 2*n2; ++k2) { if ((y = contrast2_aux(p1, sum, k1, k2, x)) < 0) break; else z += y; } } ret[0] += x[0]; ret[1] += x[1]; ret[2] += x[2]; if (ret[0] + ret[1] + ret[2] < 0.95) { // in case of bad things happened ret[0] = ret[1] = ret[2] = 0; L[0] = L[1] = 0; for (k1 = 0, z = 0.; k1 <= 2*n1; ++k1) for (k2 = 0; k2 <= 2*n2; ++k2) if ((y = contrast2_aux(p1, sum, k1, k2, ret)) >= 0) z += y; if (ret[0] + ret[1] + ret[2] < 0.95) // It seems that this may be caused by floating point errors. I do not really understand why... z = 1.0, ret[0] = ret[1] = ret[2] = 1./3; } return (double)z; } } static double mc_cal_afs(bcf_p1aux_t *ma, double *p_ref_folded, double *p_var_folded) { int k; long double sum = 0., sum2; double *phi = ma->is_indel? ma->phi_indel : ma->phi; memset(ma->afs1, 0, sizeof(double) * (ma->M + 1)); mc_cal_y(ma); // compute AFS for (k = 0, sum = 0.; k <= ma->M; ++k) sum += (long double)phi[k] * ma->z[k]; for (k = 0; k <= ma->M; ++k) { ma->afs1[k] = phi[k] * ma->z[k] / sum; if (isnan(ma->afs1[k]) || isinf(ma->afs1[k])) return -1.; } // compute folded variant probability for (k = 0, sum = 0.; k <= ma->M; ++k) sum += (long double)(phi[k] + phi[ma->M - k]) / 2. * ma->z[k]; for (k = 1, sum2 = 0.; k < ma->M; ++k) sum2 += (long double)(phi[k] + phi[ma->M - k]) / 2. * ma->z[k]; *p_var_folded = sum2 / sum; *p_ref_folded = (phi[k] + phi[ma->M - k]) / 2. * (ma->z[ma->M] + ma->z[0]) / sum; // the expected frequency for (k = 0, sum = 0.; k <= ma->M; ++k) { ma->afs[k] += ma->afs1[k]; sum += k * ma->afs1[k]; } return sum / ma->M; } int bcf_p1_cal(const bcf1_t *b, int do_contrast, bcf_p1aux_t *ma, bcf_p1rst_t *rst) { int i, k; long double sum = 0.; ma->is_indel = bcf_is_indel(b); rst->perm_rank = -1; // set PL and PL_len for (i = 0; i < b->n_gi; ++i) { if (b->gi[i].fmt == bcf_str2int("PL", 2)) { ma->PL = (uint8_t*)b->gi[i].data; ma->PL_len = b->gi[i].len; break; } } if (i == b->n_gi) return -1; // no PL if (b->n_alleles < 2) return -1; // FIXME: find a better solution // rst->rank0 = cal_pdg(b, ma); rst->f_exp = mc_cal_afs(ma, &rst->p_ref_folded, &rst->p_var_folded); rst->p_ref = ma->afs1[ma->M]; for (k = 0, sum = 0.; k < ma->M; ++k) sum += ma->afs1[k]; rst->p_var = (double)sum; { // compute the allele count double max = -1; rst->ac = -1; for (k = 0; k <= ma->M; ++k) if (max < ma->z[k]) max = ma->z[k], rst->ac = k; rst->ac = ma->M - rst->ac; } // calculate f_flat and f_em for (k = 0, sum = 0.; k <= ma->M; ++k) sum += (long double)ma->z[k]; rst->f_flat = 0.; for (k = 0; k <= ma->M; ++k) { double p = ma->z[k] / sum; rst->f_flat += k * p; } rst->f_flat /= ma->M; { // estimate equal-tail credible interval (95% level) int l, h; double p; for (i = 0, p = 0.; i <= ma->M; ++i) if (p + ma->afs1[i] > 0.025) break; else p += ma->afs1[i]; l = i; for (i = ma->M, p = 0.; i >= 0; --i) if (p + ma->afs1[i] > 0.025) break; else p += ma->afs1[i]; h = i; rst->cil = (double)(ma->M - h) / ma->M; rst->cih = (double)(ma->M - l) / ma->M; } if (ma->n1 > 0) { // compute LRT double max0, max1, max2; for (k = 0, max0 = -1; k <= ma->M; ++k) if (max0 < ma->z[k]) max0 = ma->z[k]; for (k = 0, max1 = -1; k <= ma->n1 * 2; ++k) if (max1 < ma->z1[k]) max1 = ma->z1[k]; for (k = 0, max2 = -1; k <= ma->M - ma->n1 * 2; ++k) if (max2 < ma->z2[k]) max2 = ma->z2[k]; rst->lrt = log(max1 * max2 / max0); rst->lrt = rst->lrt < 0? 1 : kf_gammaq(.5, rst->lrt); } else rst->lrt = -1.0; rst->cmp[0] = rst->cmp[1] = rst->cmp[2] = rst->p_chi2 = -1.0; if (do_contrast && rst->p_var > 0.5) // skip contrast2() if the locus is a strong non-variant rst->p_chi2 = contrast2(ma, rst->cmp); return 0; } void bcf_p1_dump_afs(bcf_p1aux_t *ma) { int k; fprintf(stderr, "[afs]"); for (k = 0; k <= ma->M; ++k) fprintf(stderr, " %d:%.3lf", k, ma->afs[ma->M - k]); fprintf(stderr, "\n"); memset(ma->afs, 0, sizeof(double) * (ma->M + 1)); }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bcftools/bcf.h
.h
7,223
198
/* The MIT License Copyright (c) 2010 Broad Institute Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Contact: Heng Li <lh3@live.co.uk> */ #ifndef BCF_H #define BCF_H #define BCF_VERSION "0.1.19-44428cd" #include <stdint.h> #include <zlib.h> #ifndef BCF_LITE #include "bgzf.h" typedef BGZF *bcfFile; #else typedef gzFile bcfFile; #define bgzf_open(fn, mode) gzopen(fn, mode) #define bgzf_fdopen(fd, mode) gzdopen(fd, mode) #define bgzf_close(fp) gzclose(fp) #define bgzf_read(fp, buf, len) gzread(fp, buf, len) #define bgzf_write(fp, buf, len) #define bgzf_flush(fp) #endif /* A member in the structs below is said to "primary" if its content cannot be inferred from other members in any of structs below; a member is said to be "derived" if its content can be derived from other members. For example, bcf1_t::str is primary as this comes from the input data, while bcf1_t::info is derived as it can always be correctly set if we know bcf1_t::str. Derived members are for quick access to the content and must be synchronized with the primary data. */ typedef struct { uint32_t fmt; // format of the block, set by bcf_str2int(). int len; // length of data for each individual void *data; // concatenated data // derived info: fmt, len (<-bcf1_t::fmt) } bcf_ginfo_t; typedef struct { int32_t tid, pos; // refID and 0-based position int32_t l_str, m_str; // length and the allocated size of ->str float qual; // SNP quality char *str; // concatenated string of variable length strings in VCF (from col.2 to col.7) char *ref, *alt, *flt, *info, *fmt; // they all point to ->str; no memory allocation int n_gi, m_gi; // number and the allocated size of geno fields bcf_ginfo_t *gi; // array of geno fields int n_alleles, n_smpl; // number of alleles and samples // derived info: ref, alt, flt, info, fmt (<-str), n_gi (<-fmt), n_alleles (<-alt), n_smpl (<-bcf_hdr_t::n_smpl) uint8_t *ploidy; // ploidy of all samples; if NULL, ploidy of 2 is assumed. } bcf1_t; typedef struct { int32_t n_ref, n_smpl; // number of reference sequences and samples int32_t l_nm; // length of concatenated sequence names; 0 padded int32_t l_smpl; // length of concatenated sample names; 0 padded int32_t l_txt; // length of header text (lines started with ##) char *name, *sname, *txt; // concatenated sequence names, sample names and header text char **ns, **sns; // array of sequence and sample names; point to name and sname, respectively // derived info: n_ref (<-name), n_smpl (<-sname), ns (<-name), sns (<-sname) } bcf_hdr_t; typedef struct { int is_vcf; // if the file in operation is a VCF void *v; // auxillary data structure for VCF bcfFile fp; // file handler for BCF } bcf_t; struct __bcf_idx_t; typedef struct __bcf_idx_t bcf_idx_t; #ifdef __cplusplus extern "C" { #endif // open a BCF file; for BCF file only bcf_t *bcf_open(const char *fn, const char *mode); // close file int bcf_close(bcf_t *b); // read one record from BCF; return -1 on end-of-file, and <-1 for errors int bcf_read(bcf_t *bp, const bcf_hdr_t *h, bcf1_t *b); // call this function if b->str is changed int bcf_sync(bcf1_t *b); // write a BCF record int bcf_write(bcf_t *bp, const bcf_hdr_t *h, const bcf1_t *b); // read the BCF header; BCF only bcf_hdr_t *bcf_hdr_read(bcf_t *b); // write the BCF header int bcf_hdr_write(bcf_t *b, const bcf_hdr_t *h); // set bcf_hdr_t::ns and bcf_hdr_t::sns int bcf_hdr_sync(bcf_hdr_t *b); // destroy the header void bcf_hdr_destroy(bcf_hdr_t *h); // destroy a record int bcf_destroy(bcf1_t *b); // BCF->VCF conversion char *bcf_fmt(const bcf_hdr_t *h, bcf1_t *b); // append more info int bcf_append_info(bcf1_t *b, const char *info, int l); // remove tag int remove_tag(char *string, const char *tag, char delim); // remove info tag, string is the kstring holder of bcf1_t.str void rm_info(kstring_t *string, const char *key); // copy int bcf_cpy(bcf1_t *r, const bcf1_t *b); // open a VCF or BCF file if "b" is set in "mode" bcf_t *vcf_open(const char *fn, const char *mode); // close a VCF/BCF file int vcf_close(bcf_t *bp); // read the VCF/BCF header bcf_hdr_t *vcf_hdr_read(bcf_t *bp); // read the sequence dictionary from a separate file; required for VCF->BCF conversion int vcf_dictread(bcf_t *bp, bcf_hdr_t *h, const char *fn); // read a VCF/BCF record; return -1 on end-of-file and <-1 for errors int vcf_read(bcf_t *bp, bcf_hdr_t *h, bcf1_t *b); // write the VCF header int vcf_hdr_write(bcf_t *bp, const bcf_hdr_t *h); // write a VCF record int vcf_write(bcf_t *bp, bcf_hdr_t *h, bcf1_t *b); // keep the first n alleles and discard the rest int bcf_shrink_alt(bcf1_t *b, int n); // keep the masked alleles and discard the rest void bcf_fit_alt(bcf1_t *b, int mask); // convert GL to PL int bcf_gl2pl(bcf1_t *b); // if the site is an indel int bcf_is_indel(const bcf1_t *b); bcf_hdr_t *bcf_hdr_subsam(const bcf_hdr_t *h0, int n, char *const* samples, int *list); int bcf_subsam(int n_smpl, int *list, bcf1_t *b); // move GT to the first FORMAT field int bcf_fix_gt(bcf1_t *b); // update PL generated by old samtools int bcf_fix_pl(bcf1_t *b); // convert PL to GLF-like 10-likelihood GL int bcf_gl10(const bcf1_t *b, uint8_t *gl); // convert up to 4 INDEL alleles to GLF-like 10-likelihood GL int bcf_gl10_indel(const bcf1_t *b, uint8_t *gl); // string hash table void *bcf_build_refhash(bcf_hdr_t *h); void bcf_str2id_destroy(void *_hash); void bcf_str2id_thorough_destroy(void *_hash); int bcf_str2id_add(void *_hash, const char *str); int bcf_str2id(void *_hash, const char *str); void *bcf_str2id_init(); // indexing related functions int bcf_idx_build(const char *fn); uint64_t bcf_idx_query(const bcf_idx_t *idx, int tid, int beg); int bcf_parse_region(void *str2id, const char *str, int *tid, int *begin, int *end); bcf_idx_t *bcf_idx_load(const char *fn); void bcf_idx_destroy(bcf_idx_t *idx); #ifdef __cplusplus } #endif static inline uint32_t bcf_str2int(const char *str, int l) { int i; uint32_t x = 0; for (i = 0; i < l && i < 4; ++i) { if (str[i] == 0) return x; x = x<<8 | str[i]; } return x; } #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bcftools/kmin.c
.c
7,269
210
/* The MIT License Copyright (c) 2008, 2010 by Attractive Chaos <attractor@live.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Hooke-Jeeves algorithm for nonlinear minimization Based on the pseudocodes by Bell and Pike (CACM 9(9):684-685), and the revision by Tomlin and Smith (CACM 12(11):637-638). Both of the papers are comments on Kaupe's Algorithm 178 "Direct Search" (ACM 6(6):313-314). The original algorithm was designed by Hooke and Jeeves (ACM 8:212-229). This program is further revised according to Johnson's implementation at Netlib (opt/hooke.c). Hooke-Jeeves algorithm is very simple and it works quite well on a few examples. However, it might fail to converge due to its heuristic nature. A possible improvement, as is suggested by Johnson, may be to choose a small r at the beginning to quickly approach to the minimum and a large r at later step to hit the minimum. */ #include <stdlib.h> #include <string.h> #include <math.h> #include "kmin.h" static double __kmin_hj_aux(kmin_f func, int n, double *x1, void *data, double fx1, double *dx, int *n_calls) { int k, j = *n_calls; double ftmp; for (k = 0; k != n; ++k) { x1[k] += dx[k]; ftmp = func(n, x1, data); ++j; if (ftmp < fx1) fx1 = ftmp; else { /* search the opposite direction */ dx[k] = 0.0 - dx[k]; x1[k] += dx[k] + dx[k]; ftmp = func(n, x1, data); ++j; if (ftmp < fx1) fx1 = ftmp; else x1[k] -= dx[k]; /* back to the original x[k] */ } } *n_calls = j; return fx1; /* here: fx1=f(n,x1) */ } double kmin_hj(kmin_f func, int n, double *x, void *data, double r, double eps, int max_calls) { double fx, fx1, *x1, *dx, radius; int k, n_calls = 0; x1 = (double*)calloc(n, sizeof(double)); dx = (double*)calloc(n, sizeof(double)); for (k = 0; k != n; ++k) { /* initial directions, based on MGJ */ dx[k] = fabs(x[k]) * r; if (dx[k] == 0) dx[k] = r; } radius = r; fx1 = fx = func(n, x, data); ++n_calls; for (;;) { memcpy(x1, x, n * sizeof(double)); /* x1 = x */ fx1 = __kmin_hj_aux(func, n, x1, data, fx, dx, &n_calls); while (fx1 < fx) { for (k = 0; k != n; ++k) { double t = x[k]; dx[k] = x1[k] > x[k]? fabs(dx[k]) : 0.0 - fabs(dx[k]); x[k] = x1[k]; x1[k] = x1[k] + x1[k] - t; } fx = fx1; if (n_calls >= max_calls) break; fx1 = func(n, x1, data); ++n_calls; fx1 = __kmin_hj_aux(func, n, x1, data, fx1, dx, &n_calls); if (fx1 >= fx) break; for (k = 0; k != n; ++k) if (fabs(x1[k] - x[k]) > .5 * fabs(dx[k])) break; if (k == n) break; } if (radius >= eps) { if (n_calls >= max_calls) break; radius *= r; for (k = 0; k != n; ++k) dx[k] *= r; } else break; /* converge */ } free(x1); free(dx); return fx1; } // I copied this function somewhere several years ago with some of my modifications, but I forgot the source. double kmin_brent(kmin1_f func, double a, double b, void *data, double tol, double *xmin) { double bound, u, r, q, fu, tmp, fa, fb, fc, c; const double gold1 = 1.6180339887; const double gold2 = 0.3819660113; const double tiny = 1e-20; const int max_iter = 100; double e, d, w, v, mid, tol1, tol2, p, eold, fv, fw; int iter; fa = func(a, data); fb = func(b, data); if (fb > fa) { // swap, such that f(a) > f(b) tmp = a; a = b; b = tmp; tmp = fa; fa = fb; fb = tmp; } c = b + gold1 * (b - a), fc = func(c, data); // golden section extrapolation while (fb > fc) { bound = b + 100.0 * (c - b); // the farthest point where we want to go r = (b - a) * (fb - fc); q = (b - c) * (fb - fa); if (fabs(q - r) < tiny) { // avoid 0 denominator tmp = q > r? tiny : 0.0 - tiny; } else tmp = q - r; u = b - ((b - c) * q - (b - a) * r) / (2.0 * tmp); // u is the parabolic extrapolation point if ((b > u && u > c) || (b < u && u < c)) { // u lies between b and c fu = func(u, data); if (fu < fc) { // (b,u,c) bracket the minimum a = b; b = u; fa = fb; fb = fu; break; } else if (fu > fb) { // (a,b,u) bracket the minimum c = u; fc = fu; break; } u = c + gold1 * (c - b); fu = func(u, data); // golden section extrapolation } else if ((c > u && u > bound) || (c < u && u < bound)) { // u lies between c and bound fu = func(u, data); if (fu < fc) { // fb > fc > fu b = c; c = u; u = c + gold1 * (c - b); fb = fc; fc = fu; fu = func(u, data); } else { // (b,c,u) bracket the minimum a = b; b = c; c = u; fa = fb; fb = fc; fc = fu; break; } } else if ((u > bound && bound > c) || (u < bound && bound < c)) { // u goes beyond the bound u = bound; fu = func(u, data); } else { // u goes the other way around, use golden section extrapolation u = c + gold1 * (c - b); fu = func(u, data); } a = b; b = c; c = u; fa = fb; fb = fc; fc = fu; } if (a > c) u = a, a = c, c = u; // swap // now, a<b<c, fa>fb and fb<fc, move on to Brent's algorithm e = d = 0.0; w = v = b; fv = fw = fb; for (iter = 0; iter != max_iter; ++iter) { mid = 0.5 * (a + c); tol2 = 2.0 * (tol1 = tol * fabs(b) + tiny); if (fabs(b - mid) <= (tol2 - 0.5 * (c - a))) { *xmin = b; return fb; // found } if (fabs(e) > tol1) { // related to parabolic interpolation r = (b - w) * (fb - fv); q = (b - v) * (fb - fw); p = (b - v) * q - (b - w) * r; q = 2.0 * (q - r); if (q > 0.0) p = 0.0 - p; else q = 0.0 - q; eold = e; e = d; if (fabs(p) >= fabs(0.5 * q * eold) || p <= q * (a - b) || p >= q * (c - b)) { d = gold2 * (e = (b >= mid ? a - b : c - b)); } else { d = p / q; u = b + d; // actual parabolic interpolation happens here if (u - a < tol2 || c - u < tol2) d = (mid > b)? tol1 : 0.0 - tol1; } } else d = gold2 * (e = (b >= mid ? a - b : c - b)); // golden section interpolation u = fabs(d) >= tol1 ? b + d : b + (d > 0.0? tol1 : -tol1); fu = func(u, data); if (fu <= fb) { // u is the minimum point so far if (u >= b) a = b; else c = b; v = w; w = b; b = u; fv = fw; fw = fb; fb = fu; } else { // adjust (a,c) and (u,v,w) if (u < b) a = u; else c = u; if (fu <= fw || w == b) { v = w; w = u; fv = fw; fw = fu; } else if (fu <= fv || v == b || v == w) { v = u; fv = fu; } } } *xmin = b; return fb; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bcftools/vcf.c
.c
7,040
250
#include <zlib.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "bcf.h" #include "kstring.h" #include "kseq.h" KSTREAM_INIT(gzFile, gzread, 4096) typedef struct { gzFile fp; FILE *fpout; kstream_t *ks; void *refhash; kstring_t line; int max_ref; } vcf_t; bcf_hdr_t *vcf_hdr_read(bcf_t *bp) { kstring_t meta, smpl; int dret; vcf_t *v; bcf_hdr_t *h; if (!bp->is_vcf) return bcf_hdr_read(bp); h = calloc(1, sizeof(bcf_hdr_t)); v = (vcf_t*)bp->v; v->line.l = 0; memset(&meta, 0, sizeof(kstring_t)); memset(&smpl, 0, sizeof(kstring_t)); while (ks_getuntil(v->ks, '\n', &v->line, &dret) >= 0) { if (v->line.l < 2) continue; if (v->line.s[0] != '#') { free(meta.s); free(smpl.s); free(h); return 0; // no sample line } if (v->line.s[0] == '#' && v->line.s[1] == '#') { kputsn(v->line.s, v->line.l, &meta); kputc('\n', &meta); } else if (v->line.s[0] == '#') { int k; ks_tokaux_t aux; char *p; for (p = kstrtok(v->line.s, "\t\n", &aux), k = 0; p; p = kstrtok(0, 0, &aux), ++k) { if (k >= 9) { kputsn(p, aux.p - p, &smpl); kputc('\0', &smpl); } } break; } } kputc('\0', &meta); h->name = 0; h->sname = smpl.s; h->l_smpl = smpl.l; h->txt = meta.s; h->l_txt = meta.l; bcf_hdr_sync(h); return h; } bcf_t *vcf_open(const char *fn, const char *mode) { bcf_t *bp; vcf_t *v; if (strchr(mode, 'b')) return bcf_open(fn, mode); bp = calloc(1, sizeof(bcf_t)); v = calloc(1, sizeof(vcf_t)); bp->is_vcf = 1; bp->v = v; v->refhash = bcf_str2id_init(); if (strchr(mode, 'r')) { v->fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r"); v->ks = ks_init(v->fp); } else if (strchr(mode, 'w')) v->fpout = strcmp(fn, "-")? fopen(fn, "w") : stdout; return bp; } int vcf_dictread(bcf_t *bp, bcf_hdr_t *h, const char *fn) { vcf_t *v; gzFile fp; kstream_t *ks; kstring_t s, rn; int dret; if (bp == 0) return -1; if (!bp->is_vcf) return 0; s.l = s.m = 0; s.s = 0; rn.m = rn.l = h->l_nm; rn.s = h->name; v = (vcf_t*)bp->v; fp = gzopen(fn, "r"); ks = ks_init(fp); while (ks_getuntil(ks, 0, &s, &dret) >= 0) { bcf_str2id_add(v->refhash, strdup(s.s)); kputs(s.s, &rn); kputc('\0', &rn); if (dret != '\n') ks_getuntil(ks, '\n', &s, &dret); } ks_destroy(ks); gzclose(fp); h->l_nm = rn.l; h->name = rn.s; bcf_hdr_sync(h); free(s.s); return 0; } int vcf_close(bcf_t *bp) { vcf_t *v; if (bp == 0) return -1; if (!bp->is_vcf) return bcf_close(bp); v = (vcf_t*)bp->v; if (v->fp) { ks_destroy(v->ks); gzclose(v->fp); } if (v->fpout) fclose(v->fpout); free(v->line.s); bcf_str2id_thorough_destroy(v->refhash); free(v); free(bp); return 0; } int vcf_hdr_write(bcf_t *bp, const bcf_hdr_t *h) { vcf_t *v = (vcf_t*)bp->v; int i, has_ver = 0; if (!bp->is_vcf) return bcf_hdr_write(bp, h); if (h->l_txt > 0) { if (strstr(h->txt, "##fileformat=")) has_ver = 1; if (has_ver == 0) fprintf(v->fpout, "##fileformat=VCFv4.1\n"); fwrite(h->txt, 1, h->l_txt - 1, v->fpout); } if (h->l_txt == 0) fprintf(v->fpout, "##fileformat=VCFv4.1\n"); fprintf(v->fpout, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT"); for (i = 0; i < h->n_smpl; ++i) fprintf(v->fpout, "\t%s", h->sns[i]); fputc('\n', v->fpout); return 0; } int vcf_write(bcf_t *bp, bcf_hdr_t *h, bcf1_t *b) { vcf_t *v = (vcf_t*)bp->v; extern void bcf_fmt_core(const bcf_hdr_t *h, bcf1_t *b, kstring_t *s); if (!bp->is_vcf) return bcf_write(bp, h, b); bcf_fmt_core(h, b, &v->line); fwrite(v->line.s, 1, v->line.l, v->fpout); fputc('\n', v->fpout); return v->line.l + 1; } int vcf_read(bcf_t *bp, bcf_hdr_t *h, bcf1_t *b) { int dret, k, i, sync = 0; vcf_t *v = (vcf_t*)bp->v; char *p, *q; kstring_t str, rn; ks_tokaux_t aux, a2; if (!bp->is_vcf) return bcf_read(bp, h, b); v->line.l = 0; str.l = 0; str.m = b->m_str; str.s = b->str; rn.l = rn.m = h->l_nm; rn.s = h->name; if (ks_getuntil(v->ks, '\n', &v->line, &dret) < 0) return -1; b->n_smpl = h->n_smpl; for (p = kstrtok(v->line.s, "\t", &aux), k = 0; p; p = kstrtok(0, 0, &aux), ++k) { *(char*)aux.p = 0; if (k == 0) { // ref int tid = bcf_str2id(v->refhash, p); if (tid < 0) { tid = bcf_str2id_add(v->refhash, strdup(p)); kputs(p, &rn); kputc('\0', &rn); sync = 1; } b->tid = tid; } else if (k == 1) { // pos b->pos = atoi(p) - 1; } else if (k == 5) { // qual b->qual = (p[0] >= '0' && p[0] <= '9')? atof(p) : 0; } else if (k <= 8) { // variable length strings kputs(p, &str); kputc('\0', &str); b->l_str = str.l; b->m_str = str.m; b->str = str.s; if (k == 8) bcf_sync(b); } else { // k > 9 if (strncmp(p, "./.", 3) == 0) { for (i = 0; i < b->n_gi; ++i) { if (b->gi[i].fmt == bcf_str2int("GT", 2)) { ((uint8_t*)b->gi[i].data)[k-9] = 1<<7; } else if (b->gi[i].fmt == bcf_str2int("GQ", 2)) { ((uint8_t*)b->gi[i].data)[k-9] = 0; } else if (b->gi[i].fmt == bcf_str2int("SP", 2)) { ((int32_t*)b->gi[i].data)[k-9] = 0; } else if (b->gi[i].fmt == bcf_str2int("DP", 2) || b->gi[i].fmt == bcf_str2int("DV", 2)) { ((uint16_t*)b->gi[i].data)[k-9] = 0; } else if (b->gi[i].fmt == bcf_str2int("PL", 2)) { int y = b->n_alleles * (b->n_alleles + 1) / 2; memset((uint8_t*)b->gi[i].data + (k - 9) * y, 0, y); } else if (b->gi[i].fmt == bcf_str2int("GL", 2)) { int y = b->n_alleles * (b->n_alleles + 1) / 2; memset((float*)b->gi[i].data + (k - 9) * y, 0, y * 4); } } goto endblock; } for (q = kstrtok(p, ":", &a2), i = 0; q && i < b->n_gi; q = kstrtok(0, 0, &a2), ++i) { if (b->gi[i].fmt == bcf_str2int("GT", 2)) { ((uint8_t*)b->gi[i].data)[k-9] = (q[0] - '0')<<3 | (q[2] - '0') | (q[1] == '/'? 0 : 1) << 6; } else if (b->gi[i].fmt == bcf_str2int("GQ", 2)) { double _x = strtod(q, &q); int x = (int)(_x + .499); if (x > 255) x = 255; ((uint8_t*)b->gi[i].data)[k-9] = x; } else if (b->gi[i].fmt == bcf_str2int("SP", 2)) { int x = strtol(q, &q, 10); if (x > 0xffff) x = 0xffff; ((uint32_t*)b->gi[i].data)[k-9] = x; } else if (b->gi[i].fmt == bcf_str2int("DP", 2) || b->gi[i].fmt == bcf_str2int("DV", 2)) { int x = strtol(q, &q, 10); if (x > 0xffff) x = 0xffff; ((uint16_t*)b->gi[i].data)[k-9] = x; } else if (b->gi[i].fmt == bcf_str2int("PL", 2)) { int x, y, j; uint8_t *data = (uint8_t*)b->gi[i].data; y = b->n_alleles * (b->n_alleles + 1) / 2; for (j = 0; j < y; ++j) { x = strtol(q, &q, 10); if (x > 255) x = 255; data[(k-9) * y + j] = x; ++q; } } else if (b->gi[i].fmt == bcf_str2int("GL", 2)) { int j, y; float x, *data = (float*)b->gi[i].data; y = b->n_alleles * (b->n_alleles + 1) / 2; for (j = 0; j < y; ++j) { x = strtod(q, &q); data[(k-9) * y + j] = x > 0? -x/10. : x; ++q; } } } endblock: i = i; } } h->l_nm = rn.l; h->name = rn.s; if (sync) bcf_hdr_sync(h); return v->line.l + 1; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bcftools/fet.c
.c
3,122
113
#include <math.h> #include <stdlib.h> /* This program is implemented with ideas from this web page: * * http://www.langsrud.com/fisher.htm */ // log\binom{n}{k} static double lbinom(int n, int k) { if (k == 0 || n == k) return 0; return lgamma(n+1) - lgamma(k+1) - lgamma(n-k+1); } // n11 n12 | n1_ // n21 n22 | n2_ //-----------+---- // n_1 n_2 | n // hypergeometric distribution static double hypergeo(int n11, int n1_, int n_1, int n) { return exp(lbinom(n1_, n11) + lbinom(n-n1_, n_1-n11) - lbinom(n, n_1)); } typedef struct { int n11, n1_, n_1, n; double p; } hgacc_t; // incremental version of hypergenometric distribution static double hypergeo_acc(int n11, int n1_, int n_1, int n, hgacc_t *aux) { if (n1_ || n_1 || n) { aux->n11 = n11; aux->n1_ = n1_; aux->n_1 = n_1; aux->n = n; } else { // then only n11 changed; the rest fixed if (n11%11 && n11 + aux->n - aux->n1_ - aux->n_1) { if (n11 == aux->n11 + 1) { // incremental aux->p *= (double)(aux->n1_ - aux->n11) / n11 * (aux->n_1 - aux->n11) / (n11 + aux->n - aux->n1_ - aux->n_1); aux->n11 = n11; return aux->p; } if (n11 == aux->n11 - 1) { // incremental aux->p *= (double)aux->n11 / (aux->n1_ - n11) * (aux->n11 + aux->n - aux->n1_ - aux->n_1) / (aux->n_1 - n11); aux->n11 = n11; return aux->p; } } aux->n11 = n11; } aux->p = hypergeo(aux->n11, aux->n1_, aux->n_1, aux->n); return aux->p; } double kt_fisher_exact(int n11, int n12, int n21, int n22, double *_left, double *_right, double *two) { int i, j, max, min; double p, q, left, right; hgacc_t aux; int n1_, n_1, n; n1_ = n11 + n12; n_1 = n11 + n21; n = n11 + n12 + n21 + n22; // calculate n1_, n_1 and n max = (n_1 < n1_) ? n_1 : n1_; // max n11, for right tail min = n1_ + n_1 - n; if (min < 0) min = 0; // min n11, for left tail *two = *_left = *_right = 1.; if (min == max) return 1.; // no need to do test q = hypergeo_acc(n11, n1_, n_1, n, &aux); // the probability of the current table // left tail p = hypergeo_acc(min, 0, 0, 0, &aux); for (left = 0., i = min + 1; p < 0.99999999 * q; ++i) // loop until underflow left += p, p = hypergeo_acc(i, 0, 0, 0, &aux); --i; if (p < 1.00000001 * q) left += p; else --i; // right tail p = hypergeo_acc(max, 0, 0, 0, &aux); for (right = 0., j = max - 1; p < 0.99999999 * q; --j) // loop until underflow right += p, p = hypergeo_acc(j, 0, 0, 0, &aux); ++j; if (p < 1.00000001 * q) right += p; else ++j; // two-tail *two = left + right; if (*two > 1.) *two = 1.; // adjust left and right if (abs(i - n11) < abs(j - n11)) right = 1. - left + q; else left = 1.0 - right + q; *_left = left; *_right = right; return q; } #ifdef FET_MAIN #include <stdio.h> int main(int argc, char *argv[]) { char id[1024]; int n11, n12, n21, n22; double left, right, twotail, prob; while (scanf("%s%d%d%d%d", id, &n11, &n12, &n21, &n22) == 5) { prob = kt_fisher_exact(n11, n12, n21, n22, &left, &right, &twotail); printf("%s\t%d\t%d\t%d\t%d\t%.6g\t%.6g\t%.6g\t%.6g\n", id, n11, n12, n21, n22, prob, left, right, twotail); } return 0; } #endif
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bcftools/bcf2qcall.c
.c
3,028
92
#include <errno.h> #include <math.h> #include <string.h> #include <stdlib.h> #include "bcf.h" static int8_t nt4_table[256] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 /*'-'*/, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, -1, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, -1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }; static int read_I16(bcf1_t *b, int anno[16]) { char *p; int i; if ((p = strstr(b->info, "I16=")) == 0) return -1; p += 4; for (i = 0; i < 16; ++i) { anno[i] = strtol(p, &p, 10); if (anno[i] == 0 && (errno == EINVAL || errno == ERANGE)) return -2; ++p; } return 0; } int bcf_2qcall(bcf_hdr_t *h, bcf1_t *b) { int a[4], k, g[10], l, map[4], k1, j, i, i0, anno[16], dp, mq, d_rest; char *s; if (b->ref[1] != 0 || b->n_alleles > 4) return -1; // ref is not a single base for (i = 0; i < b->n_gi; ++i) if (b->gi[i].fmt == bcf_str2int("PL", 2)) break; if (i == b->n_gi) return -1; // no PL if (read_I16(b, anno) != 0) return -1; // no I16; FIXME: can be improved d_rest = dp = anno[0] + anno[1] + anno[2] + anno[3]; if (dp == 0) return -1; // depth is zero mq = (int)(sqrt((double)(anno[9] + anno[11]) / dp) + .499); i0 = i; a[0] = nt4_table[(int)b->ref[0]]; if (a[0] > 3) return -1; // ref is not A/C/G/T a[1] = a[2] = a[3] = -2; // -1 has a special meaning if (b->alt[0] == 0) return -1; // no alternate allele map[0] = map[1] = map[2] = map[3] = -2; map[a[0]] = 0; for (k = 0, s = b->alt, k1 = -1; k < 3 && *s; ++k, s += 2) { if (s[1] != ',' && s[1] != 0) return -1; // ALT is not single base a[k+1] = nt4_table[(int)*s]; if (a[k+1] >= 0) map[a[k+1]] = k+1; else k1 = k+1; if (s[1] == 0) break; } for (k = 0; k < 4; ++k) if (map[k] < 0) map[k] = k1; for (i = 0; i < h->n_smpl; ++i) { int d; uint8_t *p = b->gi[i0].data + i * b->gi[i0].len; for (j = 0; j < b->gi[i0].len; ++j) if (p[j]) break; d = (int)((double)d_rest / (h->n_smpl - i) + .499); if (d == 0) d = 1; if (j == b->gi[i0].len) d = 0; d_rest -= d; for (k = j = 0; k < 4; ++k) { for (l = k; l < 4; ++l) { int t, x = map[k], y = map[l]; if (x > y) t = x, x = y, y = t; // swap g[j++] = p[y * (y+1) / 2 + x]; } } printf("%s\t%d\t%c", h->ns[b->tid], b->pos+1, *b->ref); printf("\t%d\t%d\t0", d, mq); for (j = 0; j < 10; ++j) printf("\t%d", g[j]); printf("\t%s\n", h->sns[i]); } return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bcftools/bcf.c
.c
10,569
397
#include <string.h> #include <ctype.h> #include <stdio.h> #include "kstring.h" #include "bcf.h" bcf_t *bcf_open(const char *fn, const char *mode) { bcf_t *b; b = calloc(1, sizeof(bcf_t)); if (strchr(mode, 'w')) { b->fp = strcmp(fn, "-")? bgzf_open(fn, mode) : bgzf_fdopen(fileno(stdout), mode); } else { b->fp = strcmp(fn, "-")? bgzf_open(fn, mode) : bgzf_fdopen(fileno(stdin), mode); } return b; } int bcf_close(bcf_t *b) { int ret; if (b == 0) return 0; ret = bgzf_close(b->fp); free(b); return ret; } int bcf_hdr_write(bcf_t *b, const bcf_hdr_t *h) { if (b == 0 || h == 0) return -1; bgzf_write(b->fp, "BCF\4", 4); bgzf_write(b->fp, &h->l_nm, 4); bgzf_write(b->fp, h->name, h->l_nm); bgzf_write(b->fp, &h->l_smpl, 4); bgzf_write(b->fp, h->sname, h->l_smpl); bgzf_write(b->fp, &h->l_txt, 4); bgzf_write(b->fp, h->txt, h->l_txt); bgzf_flush(b->fp); return 16 + h->l_nm + h->l_smpl + h->l_txt; } bcf_hdr_t *bcf_hdr_read(bcf_t *b) { uint8_t magic[4]; bcf_hdr_t *h; if (b == 0) return 0; h = calloc(1, sizeof(bcf_hdr_t)); bgzf_read(b->fp, magic, 4); bgzf_read(b->fp, &h->l_nm, 4); h->name = malloc(h->l_nm); bgzf_read(b->fp, h->name, h->l_nm); bgzf_read(b->fp, &h->l_smpl, 4); h->sname = malloc(h->l_smpl); bgzf_read(b->fp, h->sname, h->l_smpl); bgzf_read(b->fp, &h->l_txt, 4); h->txt = malloc(h->l_txt); bgzf_read(b->fp, h->txt, h->l_txt); bcf_hdr_sync(h); return h; } void bcf_hdr_destroy(bcf_hdr_t *h) { if (h == 0) return; free(h->name); free(h->sname); free(h->txt); free(h->ns); free(h->sns); free(h); } static inline char **cnt_null(int l, char *str, int *_n) { int n = 0; char *p, **list; *_n = 0; if (l == 0 || str == 0) return 0; for (p = str; p != str + l; ++p) if (*p == 0) ++n; *_n = n; list = calloc(n, sizeof(void*)); list[0] = str; for (p = str, n = 1; p < str + l - 1; ++p) if (*p == 0) list[n++] = p + 1; return list; } int bcf_hdr_sync(bcf_hdr_t *b) { if (b == 0) return -1; if (b->ns) free(b->ns); if (b->sns) free(b->sns); if (b->l_nm) b->ns = cnt_null(b->l_nm, b->name, &b->n_ref); else b->ns = 0, b->n_ref = 0; b->sns = cnt_null(b->l_smpl, b->sname, &b->n_smpl); return 0; } int bcf_sync(bcf1_t *b) { char *p, *tmp[5]; int i, n, n_smpl = b->n_smpl; ks_tokaux_t aux; // set ref, alt, flt, info, fmt b->ref = b->alt = b->flt = b->info = b->fmt = 0; for (p = b->str, n = 0; p < b->str + b->l_str; ++p) { if (*p == 0 && p+1 != b->str + b->l_str) { if (n == 5) { ++n; break; } else tmp[n++] = p + 1; } } if (n != 5) { fprintf(stderr, "[%s] incorrect number of fields (%d != 5) at %d:%d\n", __func__, n, b->tid, b->pos); return -1; } b->ref = tmp[0]; b->alt = tmp[1]; b->flt = tmp[2]; b->info = tmp[3]; b->fmt = tmp[4]; // set n_alleles if (*b->alt == 0) b->n_alleles = 1; else { for (p = b->alt, n = 1; *p; ++p) if (*p == ',') ++n; b->n_alleles = n + 1; } // set n_gi and gi[i].fmt for (p = b->fmt, n = 1; *p; ++p) if (*p == ':') ++n; if (n > b->m_gi) { int old_m = b->m_gi; b->m_gi = n; kroundup32(b->m_gi); b->gi = realloc(b->gi, b->m_gi * sizeof(bcf_ginfo_t)); memset(b->gi + old_m, 0, (b->m_gi - old_m) * sizeof(bcf_ginfo_t)); } b->n_gi = n; for (p = kstrtok(b->fmt, ":", &aux), n = 0; p; p = kstrtok(0, 0, &aux)) b->gi[n++].fmt = bcf_str2int(p, aux.p - p); // set gi[i].len for (i = 0; i < b->n_gi; ++i) { if (b->gi[i].fmt == bcf_str2int("PL", 2)) { b->gi[i].len = b->n_alleles * (b->n_alleles + 1) / 2; } else if (b->gi[i].fmt == bcf_str2int("DP", 2) || b->gi[i].fmt == bcf_str2int("HQ", 2) || b->gi[i].fmt == bcf_str2int("DV", 2)) { b->gi[i].len = 2; } else if (b->gi[i].fmt == bcf_str2int("GQ", 2) || b->gi[i].fmt == bcf_str2int("GT", 2)) { b->gi[i].len = 1; } else if (b->gi[i].fmt == bcf_str2int("SP", 2)) { b->gi[i].len = 4; } else if (b->gi[i].fmt == bcf_str2int("GL", 2)) { b->gi[i].len = b->n_alleles * (b->n_alleles + 1) / 2 * 4; } b->gi[i].data = realloc(b->gi[i].data, n_smpl * b->gi[i].len); } return 0; } int bcf_write(bcf_t *bp, const bcf_hdr_t *h, const bcf1_t *b) { int i, l = 0; if (b == 0) return -1; bgzf_write(bp->fp, &b->tid, 4); bgzf_write(bp->fp, &b->pos, 4); bgzf_write(bp->fp, &b->qual, 4); bgzf_write(bp->fp, &b->l_str, 4); bgzf_write(bp->fp, b->str, b->l_str); l = 12 + b->l_str; for (i = 0; i < b->n_gi; ++i) { bgzf_write(bp->fp, b->gi[i].data, b->gi[i].len * h->n_smpl); l += b->gi[i].len * h->n_smpl; } return l; } int bcf_read(bcf_t *bp, const bcf_hdr_t *h, bcf1_t *b) { int i, l = 0; if (b == 0) return -1; if (bgzf_read(bp->fp, &b->tid, 4) == 0) return -1; b->n_smpl = h->n_smpl; bgzf_read(bp->fp, &b->pos, 4); bgzf_read(bp->fp, &b->qual, 4); bgzf_read(bp->fp, &b->l_str, 4); if (b->l_str > b->m_str) { b->m_str = b->l_str; kroundup32(b->m_str); b->str = realloc(b->str, b->m_str); } bgzf_read(bp->fp, b->str, b->l_str); l = 12 + b->l_str; if (bcf_sync(b) < 0) return -2; for (i = 0; i < b->n_gi; ++i) { bgzf_read(bp->fp, b->gi[i].data, b->gi[i].len * h->n_smpl); l += b->gi[i].len * h->n_smpl; } return l; } int bcf_destroy(bcf1_t *b) { int i; if (b == 0) return -1; free(b->str); for (i = 0; i < b->m_gi; ++i) free(b->gi[i].data); free(b->gi); free(b); return 0; } static inline void fmt_str(const char *p, kstring_t *s) { if (*p == 0) kputc('.', s); else kputs(p, s); } void bcf_fmt_core(const bcf_hdr_t *h, bcf1_t *b, kstring_t *s) { int i, j, x; s->l = 0; if (h->n_ref) kputs(h->ns[b->tid], s); else kputw(b->tid, s); kputc('\t', s); kputw(b->pos + 1, s); kputc('\t', s); fmt_str(b->str, s); kputc('\t', s); fmt_str(b->ref, s); kputc('\t', s); fmt_str(b->alt, s); kputc('\t', s); ksprintf(s, "%.3g", b->qual); kputc('\t', s); fmt_str(b->flt, s); kputc('\t', s); fmt_str(b->info, s); if (b->fmt[0]) { kputc('\t', s); fmt_str(b->fmt, s); } x = b->n_alleles * (b->n_alleles + 1) / 2; if (b->n_gi == 0) return; int iPL = -1; if ( b->n_alleles > 2 ) { for (i=0; i<b->n_gi; i++) { if ( b->gi[i].fmt == bcf_str2int("PL", 2) ) { iPL = i; break; } } } for (j = 0; j < h->n_smpl; ++j) { int ploidy = b->ploidy ? b->ploidy[j] : 2; kputc('\t', s); for (i = 0; i < b->n_gi; ++i) { if (i) kputc(':', s); if (b->gi[i].fmt == bcf_str2int("PL", 2)) { uint8_t *d = (uint8_t*)b->gi[i].data + j * x; int k; if ( ploidy==1 ) for (k=0; k<b->n_alleles; k++) { if (k>0) kputc(',', s); kputw(d[(k+1)*(k+2)/2-1], s); } else for (k = 0; k < x; ++k) { if (k > 0) kputc(',', s); kputw(d[k], s); } } else if (b->gi[i].fmt == bcf_str2int("DP", 2) || b->gi[i].fmt == bcf_str2int("DV", 2)) { kputw(((uint16_t*)b->gi[i].data)[j], s); } else if (b->gi[i].fmt == bcf_str2int("GQ", 2)) { kputw(((uint8_t*)b->gi[i].data)[j], s); } else if (b->gi[i].fmt == bcf_str2int("SP", 2)) { kputw(((int32_t*)b->gi[i].data)[j], s); } else if (b->gi[i].fmt == bcf_str2int("GT", 2)) { int y = ((uint8_t*)b->gi[i].data)[j]; if ( ploidy==1 ) { if ( y>>7&1 ) kputc('.', s); else kputc('0' + (y>>3&7), s); } else { if ( y>>7&1 ) kputsn("./.", 3, s); else { kputc('0' + (y>>3&7), s); kputc("/|"[y>>6&1], s); kputc('0' + (y&7), s); } } } else if (b->gi[i].fmt == bcf_str2int("GL", 2)) { float *d = (float*)b->gi[i].data + j * x; int k; //printf("- %lx\n", d); for (k = 0; k < x; ++k) { if (k > 0) kputc(',', s); ksprintf(s, "%.2f", d[k]); } } else kputc('.', s); // custom fields } } } char *bcf_fmt(const bcf_hdr_t *h, bcf1_t *b) { kstring_t s; s.l = s.m = 0; s.s = 0; bcf_fmt_core(h, b, &s); return s.s; } int bcf_append_info(bcf1_t *b, const char *info, int l) { int shift = b->fmt - b->str; int l_fmt = b->l_str - shift; char *ori = b->str; if (b->l_str + l > b->m_str) { // enlarge if necessary b->m_str = b->l_str + l; kroundup32(b->m_str); b->str = realloc(b->str, b->m_str); } memmove(b->str + shift + l, b->str + shift, l_fmt); // move the FORMAT field memcpy(b->str + shift - 1, info, l); // append to the INFO field b->str[shift + l - 1] = '\0'; b->fmt = b->str + shift + l; b->l_str += l; if (ori != b->str) bcf_sync(b); // synchronize when realloc changes the pointer return 0; } int remove_tag(char *str, const char *tag, char delim) { char *tmp = str, *p; int len_diff = 0, ori_len = strlen(str); while ( *tmp && (p = strstr(tmp,tag)) ) { if ( p>str ) { if ( *(p-1)!=delim ) { tmp=p+1; continue; } // shared substring p--; } char *q=p+1; while ( *q && *q!=delim ) q++; if ( p==str && *q ) q++; // the tag is first, don't move the delim char len_diff += q-p; if ( ! *q ) { *p = 0; break; } // the tag was last, no delim follows else memmove(p,q,ori_len-(int)(p-str)-(int)(q-p)); // *q==delim } if ( len_diff==ori_len ) str[0]='.', str[1]=0, len_diff--; return len_diff; } void rm_info(kstring_t *s, const char *key) { char *p = s->s; int n = 0; while ( n<4 ) { if ( !*p ) n++; p++; } char *q = p+1; while ( *q && q-s->s<s->l ) q++; int nrm = remove_tag(p, key, ';'); if ( nrm ) memmove(q-nrm, q, s->s+s->l-q+1); s->l -= nrm; } int bcf_cpy(bcf1_t *r, const bcf1_t *b) { char *t1 = r->str; bcf_ginfo_t *t2 = r->gi; int i, t3 = r->m_str, t4 = r->m_gi; *r = *b; r->str = t1; r->gi = t2; r->m_str = t3; r->m_gi = t4; if (r->m_str < b->m_str) { r->m_str = b->m_str; r->str = realloc(r->str, r->m_str); } memcpy(r->str, b->str, r->m_str); bcf_sync(r); // calling bcf_sync() is simple but inefficient for (i = 0; i < r->n_gi; ++i) memcpy(r->gi[i].data, b->gi[i].data, r->n_smpl * r->gi[i].len); return 0; } int bcf_is_indel(const bcf1_t *b) { char *p; if (strlen(b->ref) > 1) return 1; for (p = b->alt; *p; ++p) if (*p != ',' && p[1] != ',' && p[1] != '\0') return 1; return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bcftools/kfunc.c
.c
4,960
163
#include <math.h> /* Log gamma function * \log{\Gamma(z)} * AS245, 2nd algorithm, http://lib.stat.cmu.edu/apstat/245 */ double kf_lgamma(double z) { double x = 0; x += 0.1659470187408462e-06 / (z+7); x += 0.9934937113930748e-05 / (z+6); x -= 0.1385710331296526 / (z+5); x += 12.50734324009056 / (z+4); x -= 176.6150291498386 / (z+3); x += 771.3234287757674 / (z+2); x -= 1259.139216722289 / (z+1); x += 676.5203681218835 / z; x += 0.9999999999995183; return log(x) - 5.58106146679532777 - z + (z-0.5) * log(z+6.5); } /* complementary error function * \frac{2}{\sqrt{\pi}} \int_x^{\infty} e^{-t^2} dt * AS66, 2nd algorithm, http://lib.stat.cmu.edu/apstat/66 */ double kf_erfc(double x) { const double p0 = 220.2068679123761; const double p1 = 221.2135961699311; const double p2 = 112.0792914978709; const double p3 = 33.912866078383; const double p4 = 6.37396220353165; const double p5 = .7003830644436881; const double p6 = .03526249659989109; const double q0 = 440.4137358247522; const double q1 = 793.8265125199484; const double q2 = 637.3336333788311; const double q3 = 296.5642487796737; const double q4 = 86.78073220294608; const double q5 = 16.06417757920695; const double q6 = 1.755667163182642; const double q7 = .08838834764831844; double expntl, z, p; z = fabs(x) * M_SQRT2; if (z > 37.) return x > 0.? 0. : 2.; expntl = exp(z * z * - .5); if (z < 10. / M_SQRT2) // for small z p = expntl * ((((((p6 * z + p5) * z + p4) * z + p3) * z + p2) * z + p1) * z + p0) / (((((((q7 * z + q6) * z + q5) * z + q4) * z + q3) * z + q2) * z + q1) * z + q0); else p = expntl / 2.506628274631001 / (z + 1. / (z + 2. / (z + 3. / (z + 4. / (z + .65))))); return x > 0.? 2. * p : 2. * (1. - p); } /* The following computes regularized incomplete gamma functions. * Formulas are taken from Wiki, with additional input from Numerical * Recipes in C (for modified Lentz's algorithm) and AS245 * (http://lib.stat.cmu.edu/apstat/245). * * A good online calculator is available at: * * http://www.danielsoper.com/statcalc/calc23.aspx * * It calculates upper incomplete gamma function, which equals * kf_gammaq(s,z)*tgamma(s). */ #define KF_GAMMA_EPS 1e-14 #define KF_TINY 1e-290 // regularized lower incomplete gamma function, by series expansion static double _kf_gammap(double s, double z) { double sum, x; int k; for (k = 1, sum = x = 1.; k < 100; ++k) { sum += (x *= z / (s + k)); if (x / sum < KF_GAMMA_EPS) break; } return exp(s * log(z) - z - kf_lgamma(s + 1.) + log(sum)); } // regularized upper incomplete gamma function, by continued fraction static double _kf_gammaq(double s, double z) { int j; double C, D, f; f = 1. + z - s; C = f; D = 0.; // Modified Lentz's algorithm for computing continued fraction // See Numerical Recipes in C, 2nd edition, section 5.2 for (j = 1; j < 100; ++j) { double a = j * (s - j), b = (j<<1) + 1 + z - s, d; D = b + a * D; if (D < KF_TINY) D = KF_TINY; C = b + a / C; if (C < KF_TINY) C = KF_TINY; D = 1. / D; d = C * D; f *= d; if (fabs(d - 1.) < KF_GAMMA_EPS) break; } return exp(s * log(z) - z - kf_lgamma(s) - log(f)); } double kf_gammap(double s, double z) { return z <= 1. || z < s? _kf_gammap(s, z) : 1. - _kf_gammaq(s, z); } double kf_gammaq(double s, double z) { return z <= 1. || z < s? 1. - _kf_gammap(s, z) : _kf_gammaq(s, z); } /* Regularized incomplete beta function. The method is taken from * Numerical Recipe in C, 2nd edition, section 6.4. The following web * page calculates the incomplete beta function, which equals * kf_betai(a,b,x) * gamma(a) * gamma(b) / gamma(a+b): * * http://www.danielsoper.com/statcalc/calc36.aspx */ static double kf_betai_aux(double a, double b, double x) { double C, D, f; int j; if (x == 0.) return 0.; if (x == 1.) return 1.; f = 1.; C = f; D = 0.; // Modified Lentz's algorithm for computing continued fraction for (j = 1; j < 200; ++j) { double aa, d; int m = j>>1; aa = (j&1)? -(a + m) * (a + b + m) * x / ((a + 2*m) * (a + 2*m + 1)) : m * (b - m) * x / ((a + 2*m - 1) * (a + 2*m)); D = 1. + aa * D; if (D < KF_TINY) D = KF_TINY; C = 1. + aa / C; if (C < KF_TINY) C = KF_TINY; D = 1. / D; d = C * D; f *= d; if (fabs(d - 1.) < KF_GAMMA_EPS) break; } return exp(kf_lgamma(a+b) - kf_lgamma(a) - kf_lgamma(b) + a * log(x) + b * log(1.-x)) / a / f; } double kf_betai(double a, double b, double x) { return x < (a + 1.) / (a + b + 2.)? kf_betai_aux(a, b, x) : 1. - kf_betai_aux(b, a, 1. - x); } #ifdef KF_MAIN #include <stdio.h> int main(int argc, char *argv[]) { double x = 5.5, y = 3; double a, b; printf("erfc(%lg): %lg, %lg\n", x, erfc(x), kf_erfc(x)); printf("upper-gamma(%lg,%lg): %lg\n", x, y, kf_gammaq(y, x)*tgamma(y)); a = 2; b = 2; x = 0.5; printf("incomplete-beta(%lg,%lg,%lg): %lg\n", a, b, x, kf_betai(a, b, x) / exp(kf_lgamma(a+b) - kf_lgamma(a) - kf_lgamma(b))); return 0; } #endif
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bcftools/bcfutils.c
.c
13,251
505
#include <string.h> #include <math.h> #include <assert.h> #include "bcf.h" #include "kstring.h" #include "khash.h" KHASH_MAP_INIT_STR(str2id, int) #ifdef _WIN32 #define srand48(x) srand(x) #define drand48() ((double)rand() / RAND_MAX) #endif // FIXME: valgrind report a memory leak in this function. Probably it does not get deallocated... void *bcf_build_refhash(bcf_hdr_t *h) { khash_t(str2id) *hash; int i, ret; hash = kh_init(str2id); for (i = 0; i < h->n_ref; ++i) { khint_t k; k = kh_put(str2id, hash, h->ns[i], &ret); // FIXME: check ret kh_val(hash, k) = i; } return hash; } void *bcf_str2id_init() { return kh_init(str2id); } void bcf_str2id_destroy(void *_hash) { khash_t(str2id) *hash = (khash_t(str2id)*)_hash; if (hash) kh_destroy(str2id, hash); // Note that strings are not freed. } void bcf_str2id_thorough_destroy(void *_hash) { khash_t(str2id) *hash = (khash_t(str2id)*)_hash; khint_t k; if (hash == 0) return; for (k = 0; k < kh_end(hash); ++k) if (kh_exist(hash, k)) free((char*)kh_key(hash, k)); kh_destroy(str2id, hash); } int bcf_str2id(void *_hash, const char *str) { khash_t(str2id) *hash = (khash_t(str2id)*)_hash; khint_t k; if (!hash) return -1; k = kh_get(str2id, hash, str); return k == kh_end(hash)? -1 : kh_val(hash, k); } int bcf_str2id_add(void *_hash, const char *str) { khint_t k; int ret; khash_t(str2id) *hash = (khash_t(str2id)*)_hash; if (!hash) return -1; k = kh_put(str2id, hash, str, &ret); if (ret == 0) return kh_val(hash, k); kh_val(hash, k) = kh_size(hash) - 1; return kh_val(hash, k); } void bcf_fit_alt(bcf1_t *b, int mask) { mask |= 1; // REF must be always present int i,j,nals=0; for (i=0; i<sizeof(int); i++) if ( mask&1<<i) nals++; if ( b->n_alleles <= nals ) return; // update ALT, in principle any of the alleles can be removed char *p; if ( nals>1 ) { char *dst, *src; int n=0, nalts=nals-1; for (src=dst=p=b->alt, i=1; *p; p++) { if ( *p!=',' ) continue; if ( mask&1<<i ) { n++; if ( src!=dst ) { memmove(dst,src,p-src); dst += p-src; } else dst = p; if ( n<nalts ) { *dst=','; dst++; } } i++; if ( n>=nalts ) { *dst=0; break; } src = p+1; } if ( n<nalts ) { memmove(dst,src,p-src); dst += p-src; *dst = 0; } p = dst; } else p = b->alt, *p = '\0'; p++; memmove(p, b->flt, b->str + b->l_str - b->flt); b->l_str -= b->flt - p; // update PL and GT int ipl=-1, igt=-1; for (i = 0; i < b->n_gi; ++i) { bcf_ginfo_t *g = b->gi + i; if (g->fmt == bcf_str2int("PL", 2)) ipl = i; if (g->fmt == bcf_str2int("GT", 2)) igt = i; } // .. create mapping between old and new indexes int npl = nals * (nals+1) / 2; int *map = malloc(sizeof(int)*(npl>b->n_alleles ? npl : b->n_alleles)); int kori=0,knew=0; for (i=0; i<b->n_alleles; i++) { for (j=0; j<=i; j++) { int skip=0; if ( i && !(mask&1<<i) ) skip=1; if ( j && !(mask&1<<j) ) skip=1; if ( !skip ) { map[knew++] = kori; } kori++; } } // .. apply to all samples int n_smpl = b->n_smpl; for (i = 0; i < b->n_gi; ++i) { bcf_ginfo_t *g = b->gi + i; if (g->fmt == bcf_str2int("PL", 2)) { g->len = npl; uint8_t *d = (uint8_t*)g->data; int ismpl, npl_ori = b->n_alleles * (b->n_alleles + 1) / 2; for (knew=ismpl=0; ismpl<n_smpl; ismpl++) { uint8_t *dl = d + ismpl * npl_ori; for (j=0; j<npl; j++) d[knew++] = dl[map[j]]; } } // FIXME: to add GL } // update GTs map[0] = 0; for (i=1, knew=0; i<b->n_alleles; i++) map[i] = mask&1<<i ? ++knew : -1; for (i=0; i<n_smpl; i++) { uint8_t gt = ((uint8_t*)b->gi[igt].data)[i]; int a1 = (gt>>3)&7; int a2 = gt&7; assert( map[a1]>=0 && map[a2]>=0 ); ((uint8_t*)b->gi[igt].data)[i] = ((1<<7|1<<6)&gt) | map[a1]<<3 | map[a2]; } free(map); b->n_alleles = nals; bcf_sync(b); } int bcf_shrink_alt(bcf1_t *b, int n) { char *p; int i, j, k, n_smpl = b->n_smpl; if (b->n_alleles <= n) return -1; // update ALT if (n > 1) { for (p = b->alt, k = 1; *p; ++p) if (*p == ',' && ++k == n) break; *p = '\0'; } else p = b->alt, *p = '\0'; ++p; memmove(p, b->flt, b->str + b->l_str - b->flt); b->l_str -= b->flt - p; // update PL for (i = 0; i < b->n_gi; ++i) { bcf_ginfo_t *g = b->gi + i; if (g->fmt == bcf_str2int("PL", 2)) { int l, x = b->n_alleles * (b->n_alleles + 1) / 2; uint8_t *d = (uint8_t*)g->data; g->len = n * (n + 1) / 2; for (l = k = 0; l < n_smpl; ++l) { uint8_t *dl = d + l * x; for (j = 0; j < g->len; ++j) d[k++] = dl[j]; } } // FIXME: to add GL } b->n_alleles = n; bcf_sync(b); return 0; } int bcf_gl2pl(bcf1_t *b) { char *p; int i, n_smpl = b->n_smpl; bcf_ginfo_t *g; float *d0; uint8_t *d1; if (strstr(b->fmt, "PL")) return -1; if ((p = strstr(b->fmt, "GL")) == 0) return -1; *p = 'P'; for (i = 0; i < b->n_gi; ++i) if (b->gi[i].fmt == bcf_str2int("GL", 2)) break; g = b->gi + i; g->fmt = bcf_str2int("PL", 2); g->len /= 4; // 4 == sizeof(float) d0 = (float*)g->data; d1 = (uint8_t*)g->data; for (i = 0; i < n_smpl * g->len; ++i) { int x = (int)(-10. * d0[i] + .499); if (x > 255) x = 255; if (x < 0) x = 0; d1[i] = x; } return 0; } /* FIXME: this function will fail given AB:GTX:GT. BCFtools never * produces such FMT, but others may do. */ int bcf_fix_gt(bcf1_t *b) { char *s; int i; uint32_t tmp; bcf_ginfo_t gt; // check the presence of the GT FMT if ((s = strstr(b->fmt, ":GT")) == 0) return 0; // no GT or GT is already the first assert(s[3] == '\0' || s[3] == ':'); // :GTX in fact tmp = bcf_str2int("GT", 2); for (i = 0; i < b->n_gi; ++i) if (b->gi[i].fmt == tmp) break; if (i == b->n_gi) return 0; // no GT in b->gi; probably a bug... gt = b->gi[i]; // move GT to the first for (; i > 0; --i) b->gi[i] = b->gi[i-1]; b->gi[0] = gt; if ( s[3]==0 ) memmove(b->fmt + 3, b->fmt, s - b->fmt); // :GT else memmove(b->fmt + 3, b->fmt, s - b->fmt + 1); // :GT: b->fmt[0] = 'G'; b->fmt[1] = 'T'; b->fmt[2] = ':'; return 0; } int bcf_fix_pl(bcf1_t *b) { int i; uint32_t tmp; uint8_t *PL, *swap; bcf_ginfo_t *gi; // pinpoint PL tmp = bcf_str2int("PL", 2); for (i = 0; i < b->n_gi; ++i) if (b->gi[i].fmt == tmp) break; if (i == b->n_gi) return 0; // prepare gi = b->gi + i; PL = (uint8_t*)gi->data; swap = alloca(gi->len); // loop through individuals for (i = 0; i < b->n_smpl; ++i) { int k, l, x; uint8_t *PLi = PL + i * gi->len; memcpy(swap, PLi, gi->len); for (k = x = 0; k < b->n_alleles; ++k) for (l = k; l < b->n_alleles; ++l) PLi[l*(l+1)/2 + k] = swap[x++]; } return 0; } int bcf_smpl_covered(const bcf1_t *b) { int i, j, n = 0; uint32_t tmp; bcf_ginfo_t *gi; // pinpoint PL tmp = bcf_str2int("PL", 2); for (i = 0; i < b->n_gi; ++i) if (b->gi[i].fmt == tmp) break; if (i == b->n_gi) return 0; // count how many samples having PL!=[0..0] gi = b->gi + i; for (i = 0; i < b->n_smpl; ++i) { uint8_t *PLi = ((uint8_t*)gi->data) + i * gi->len; for (j = 0; j < gi->len; ++j) if (PLi[j]) break; if (j < gi->len) ++n; } return n; } static void *locate_field(const bcf1_t *b, const char *fmt, int l) { int i; uint32_t tmp; tmp = bcf_str2int(fmt, l); for (i = 0; i < b->n_gi; ++i) if (b->gi[i].fmt == tmp) break; return i == b->n_gi? 0 : b->gi[i].data; } int bcf_anno_max(bcf1_t *b) { int k, max_gq, max_sp, n_het; kstring_t str; uint8_t *gt, *gq; int32_t *sp; max_gq = max_sp = n_het = 0; gt = locate_field(b, "GT", 2); if (gt == 0) return -1; gq = locate_field(b, "GQ", 2); sp = locate_field(b, "SP", 2); if (sp) for (k = 0; k < b->n_smpl; ++k) if (gt[k]&0x3f) max_sp = max_sp > (int)sp[k]? max_sp : sp[k]; if (gq) for (k = 0; k < b->n_smpl; ++k) if (gt[k]&0x3f) max_gq = max_gq > (int)gq[k]? max_gq : gq[k]; for (k = 0; k < b->n_smpl; ++k) { int a1, a2; a1 = gt[k]&7; a2 = gt[k]>>3&7; if ((!a1 && a2) || (!a2 && a1)) { // a het if (gq == 0) ++n_het; else if (gq[k] >= 20) ++n_het; } } if (n_het) max_sp -= (int)(4.343 * log(n_het) + .499); if (max_sp < 0) max_sp = 0; memset(&str, 0, sizeof(kstring_t)); if (*b->info) kputc(';', &str); ksprintf(&str, "MXSP=%d;MXGQ=%d", max_sp, max_gq); bcf_append_info(b, str.s, str.l); free(str.s); return 0; } // FIXME: only data are shuffled; the header is NOT int bcf_shuffle(bcf1_t *b, int seed) { int i, j, *a; if (seed > 0) srand48(seed); a = malloc(b->n_smpl * sizeof(int)); for (i = 0; i < b->n_smpl; ++i) a[i] = i; for (i = b->n_smpl; i > 1; --i) { int tmp; j = (int)(drand48() * i); tmp = a[j]; a[j] = a[i-1]; a[i-1] = tmp; } for (j = 0; j < b->n_gi; ++j) { bcf_ginfo_t *gi = b->gi + j; uint8_t *swap, *data = (uint8_t*)gi->data; swap = malloc(gi->len * b->n_smpl); for (i = 0; i < b->n_smpl; ++i) memcpy(swap + gi->len * a[i], data + gi->len * i, gi->len); free(gi->data); gi->data = swap; } free(a); return 0; } bcf_hdr_t *bcf_hdr_subsam(const bcf_hdr_t *h0, int n, char *const* samples, int *list) { int i, ret, j; khint_t k; bcf_hdr_t *h; khash_t(str2id) *hash; kstring_t s; s.l = s.m = 0; s.s = 0; hash = kh_init(str2id); for (i = 0; i < h0->n_smpl; ++i) { k = kh_put(str2id, hash, h0->sns[i], &ret); kh_val(hash, k) = i; } for (i = j = 0; i < n; ++i) { k = kh_get(str2id, hash, samples[i]); if (k != kh_end(hash)) { list[j++] = kh_val(hash, k); kputs(samples[i], &s); kputc('\0', &s); } } if (j < n) { fprintf(stderr, "<%s> %d samples in the list but not in BCF.", __func__, n - j); exit(1); } kh_destroy(str2id, hash); h = calloc(1, sizeof(bcf_hdr_t)); *h = *h0; h->ns = 0; h->sns = 0; h->name = malloc(h->l_nm); memcpy(h->name, h0->name, h->l_nm); h->txt = calloc(1, h->l_txt + 1); memcpy(h->txt, h0->txt, h->l_txt); h->l_smpl = s.l; h->sname = s.s; bcf_hdr_sync(h); return h; } int bcf_subsam(int n_smpl, int *list, bcf1_t *b) { int i, j; for (j = 0; j < b->n_gi; ++j) { bcf_ginfo_t *gi = b->gi + j; uint8_t *swap; swap = malloc(gi->len * b->n_smpl); for (i = 0; i < n_smpl; ++i) memcpy(swap + i * gi->len, (uint8_t*)gi->data + list[i] * gi->len, gi->len); free(gi->data); gi->data = swap; } b->n_smpl = n_smpl; return 0; } static int8_t nt4_table[128] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 /*'-'*/, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, -1, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, -1, 4, 4, 4, 4, 4, 4, 4 }; int bcf_gl10(const bcf1_t *b, uint8_t *gl) { int a[4], k, l, map[4], k1, j, i; const bcf_ginfo_t *PL; char *s; if (b->ref[1] != 0 || b->n_alleles > 4) return -1; // ref is not a single base or >4 alleles for (i = 0; i < b->n_gi; ++i) if (b->gi[i].fmt == bcf_str2int("PL", 2)) break; if (i == b->n_gi) return -1; // no PL PL = b->gi + i; a[0] = nt4_table[(int)b->ref[0]]; if (a[0] > 3 || a[0] < 0) return -1; // ref is not A/C/G/T a[1] = a[2] = a[3] = -2; // -1 has a special meaning if (b->alt[0] == 0) return -1; // no alternate allele map[0] = map[1] = map[2] = map[3] = -2; map[a[0]] = 0; for (k = 0, s = b->alt, k1 = -1; k < 3 && *s; ++k, s += 2) { if (s[1] != ',' && s[1] != 0) return -1; // ALT is not single base a[k+1] = nt4_table[(int)*s]; if (a[k+1] >= 0) map[a[k+1]] = k+1; else k1 = k + 1; if (s[1] == 0) break; // the end of the ALT string } for (k = 0; k < 4; ++k) if (map[k] < 0) map[k] = k1; for (i = 0; i < b->n_smpl; ++i) { const uint8_t *p = PL->data + i * PL->len; // the PL for the i-th individual uint8_t *g = gl + 10 * i; for (k = j = 0; k < 4; ++k) { for (l = k; l < 4; ++l) { int t, x = map[k], y = map[l]; if (x > y) t = x, x = y, y = t; // make sure x is the smaller g[j++] = p[y * (y+1) / 2 + x]; } } } return 0; } int bcf_gl10_indel(const bcf1_t *b, uint8_t *gl) { int k, l, j, i; const bcf_ginfo_t *PL; if (b->alt[0] == 0) return -1; // no alternate allele for (i = 0; i < b->n_gi; ++i) if (b->gi[i].fmt == bcf_str2int("PL", 2)) break; if (i == b->n_gi) return -1; // no PL PL = b->gi + i; for (i = 0; i < b->n_smpl; ++i) { const uint8_t *p = PL->data + i * PL->len; // the PL for the i-th individual uint8_t *g = gl + 10 * i; for (k = j = 0; k < 4; ++k) { for (l = k; l < 4; ++l) { int t, x = k, y = l; if (x > y) t = x, x = y, y = t; // make sure x is the smaller x = y * (y+1) / 2 + x; g[j++] = x < PL->len? p[x] : 255; } } } return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bcftools/prob1.h
.h
1,457
50
#ifndef BCF_PROB1_H #define BCF_PROB1_H #include "bcf.h" struct __bcf_p1aux_t; typedef struct __bcf_p1aux_t bcf_p1aux_t; typedef struct { int rank0, perm_rank; // NB: perm_rank is always set to -1 by bcf_p1_cal() int ac; // ML alternative allele count double f_exp, f_flat, p_ref_folded, p_ref, p_var_folded, p_var; double cil, cih; double cmp[3], p_chi2, lrt; // used by contrast2() } bcf_p1rst_t; typedef struct { double p[4]; int mq, depth, is_tested, d[4]; } anno16_t; #define MC_PTYPE_FULL 1 #define MC_PTYPE_COND2 2 #define MC_PTYPE_FLAT 3 #ifdef __cplusplus extern "C" { #endif bcf_p1aux_t *bcf_p1_init(int n, uint8_t *ploidy); void bcf_p1_init_prior(bcf_p1aux_t *ma, int type, double theta); void bcf_p1_init_subprior(bcf_p1aux_t *ma, int type, double theta); void bcf_p1_destroy(bcf_p1aux_t *ma); void bcf_p1_set_ploidy(bcf1_t *b, bcf_p1aux_t *ma); int bcf_p1_cal(const bcf1_t *b, int do_contrast, bcf_p1aux_t *ma, bcf_p1rst_t *rst); int call_multiallelic_gt(bcf1_t *b, bcf_p1aux_t *ma, double threshold, int var_only); int bcf_p1_call_gt(const bcf_p1aux_t *ma, double f0, int k); void bcf_p1_dump_afs(bcf_p1aux_t *ma); int bcf_p1_read_prior(bcf_p1aux_t *ma, const char *fn); int bcf_p1_set_n1(bcf_p1aux_t *b, int n1); void bcf_p1_set_folded(bcf_p1aux_t *p1a); // only effective when set_n1() is not called int bcf_em1(const bcf1_t *b, int n1, int flag, double x[10]); #ifdef __cplusplus } #endif #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bcftools/kmin.h
.h
1,619
47
/* Copyright (c) 2008, 2010 by Attractive Chaos <attractor@live.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef KMIN_H #define KMIN_H #define KMIN_RADIUS 0.5 #define KMIN_EPS 1e-7 #define KMIN_MAXCALL 50000 typedef double (*kmin_f)(int, double*, void*); typedef double (*kmin1_f)(double, void*); #ifdef __cplusplus extern "C" { #endif double kmin_hj(kmin_f func, int n, double *x, void *data, double r, double eps, int max_calls); double kmin_brent(kmin1_f func, double a, double b, void *data, double tol, double *xmin); #ifdef __cplusplus } #endif #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/win32/zlib.h
.h
66,188
1,358
/* zlib.h -- interface of the 'zlib' general purpose compression library version 1.2.3, July 18th, 2005 Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jean-loup Gailly Mark Adler jloup@gzip.org madler@alumni.caltech.edu The data format used by the zlib library is described by RFCs (Request for Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). */ #ifndef ZLIB_H #define ZLIB_H #include "zconf.h" #ifdef __cplusplus extern "C" { #endif #define ZLIB_VERSION "1.2.3" #define ZLIB_VERNUM 0x1230 /* The 'zlib' compression library provides in-memory compression and decompression functions, including integrity checks of the uncompressed data. This version of the library supports only one compression method (deflation) but other algorithms will be added later and will have the same stream interface. Compression can be done in a single step if the buffers are large enough (for example if an input file is mmap'ed), or can be done by repeated calls of the compression function. In the latter case, the application must provide more input and/or consume the output (providing more output space) before each call. The compressed data format used by default by the in-memory functions is the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped around a deflate stream, which is itself documented in RFC 1951. The library also supports reading and writing files in gzip (.gz) format with an interface similar to that of stdio using the functions that start with "gz". The gzip format is different from the zlib format. gzip is a gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. This library can optionally read and write gzip streams in memory as well. The zlib format was designed to be compact and fast for use in memory and on communications channels. The gzip format was designed for single- file compression on file systems, has a larger header than zlib to maintain directory information, and uses a different, slower check method than zlib. The library does not install any signal handler. The decoder checks the consistency of the compressed data, so the library should never crash even in case of corrupted input. */ typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); typedef void (*free_func) OF((voidpf opaque, voidpf address)); struct internal_state; typedef struct z_stream_s { Bytef *next_in; /* next input byte */ uInt avail_in; /* number of bytes available at next_in */ uLong total_in; /* total nb of input bytes read so far */ Bytef *next_out; /* next output byte should be put there */ uInt avail_out; /* remaining free space at next_out */ uLong total_out; /* total nb of bytes output so far */ char *msg; /* last error message, NULL if no error */ struct internal_state FAR *state; /* not visible by applications */ alloc_func zalloc; /* used to allocate the internal state */ free_func zfree; /* used to free the internal state */ voidpf opaque; /* private data object passed to zalloc and zfree */ int data_type; /* best guess about the data type: binary or text */ uLong adler; /* adler32 value of the uncompressed data */ uLong reserved; /* reserved for future use */ } z_stream; typedef z_stream FAR *z_streamp; /* gzip header information passed to and from zlib routines. See RFC 1952 for more details on the meanings of these fields. */ typedef struct gz_header_s { int text; /* true if compressed data believed to be text */ uLong time; /* modification time */ int xflags; /* extra flags (not used when writing a gzip file) */ int os; /* operating system */ Bytef *extra; /* pointer to extra field or Z_NULL if none */ uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ uInt extra_max; /* space at extra (only when reading header) */ Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ uInt name_max; /* space at name (only when reading header) */ Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ uInt comm_max; /* space at comment (only when reading header) */ int hcrc; /* true if there was or will be a header crc */ int done; /* true when done reading gzip header (not used when writing a gzip file) */ } gz_header; typedef gz_header FAR *gz_headerp; /* The application must update next_in and avail_in when avail_in has dropped to zero. It must update next_out and avail_out when avail_out has dropped to zero. The application must initialize zalloc, zfree and opaque before calling the init function. All other fields are set by the compression library and must not be updated by the application. The opaque value provided by the application will be passed as the first parameter for calls of zalloc and zfree. This can be useful for custom memory management. The compression library attaches no meaning to the opaque value. zalloc must return Z_NULL if there is not enough memory for the object. If zlib is used in a multi-threaded application, zalloc and zfree must be thread safe. On 16-bit systems, the functions zalloc and zfree must be able to allocate exactly 65536 bytes, but will not be required to allocate more than this if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers returned by zalloc for objects of exactly 65536 bytes *must* have their offset normalized to zero. The default allocation function provided by this library ensures this (see zutil.c). To reduce memory requirements and avoid any allocation of 64K objects, at the expense of compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). The fields total_in and total_out can be used for statistics or progress reports. After compression, total_in holds the total size of the uncompressed data and may be saved for use in the decompressor (particularly if the decompressor wants to decompress everything in a single step). */ /* constants */ #define Z_NO_FLUSH 0 #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ #define Z_SYNC_FLUSH 2 #define Z_FULL_FLUSH 3 #define Z_FINISH 4 #define Z_BLOCK 5 /* Allowed flush values; see deflate() and inflate() below for details */ #define Z_OK 0 #define Z_STREAM_END 1 #define Z_NEED_DICT 2 #define Z_ERRNO (-1) #define Z_STREAM_ERROR (-2) #define Z_DATA_ERROR (-3) #define Z_MEM_ERROR (-4) #define Z_BUF_ERROR (-5) #define Z_VERSION_ERROR (-6) /* Return codes for the compression/decompression functions. Negative * values are errors, positive values are used for special but normal events. */ #define Z_NO_COMPRESSION 0 #define Z_BEST_SPEED 1 #define Z_BEST_COMPRESSION 9 #define Z_DEFAULT_COMPRESSION (-1) /* compression levels */ #define Z_FILTERED 1 #define Z_HUFFMAN_ONLY 2 #define Z_RLE 3 #define Z_FIXED 4 #define Z_DEFAULT_STRATEGY 0 /* compression strategy; see deflateInit2() below for details */ #define Z_BINARY 0 #define Z_TEXT 1 #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ #define Z_UNKNOWN 2 /* Possible values of the data_type field (though see inflate()) */ #define Z_DEFLATED 8 /* The deflate compression method (the only one supported in this version) */ #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ #define zlib_version zlibVersion() /* for compatibility with versions < 1.0.2 */ /* basic functions */ ZEXTERN const char * ZEXPORT zlibVersion OF((void)); /* The application can compare zlibVersion and ZLIB_VERSION for consistency. If the first character differs, the library code actually used is not compatible with the zlib.h header file used by the application. This check is automatically made by deflateInit and inflateInit. */ /* ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); Initializes the internal stream state for compression. The fields zalloc, zfree and opaque must be initialized before by the caller. If zalloc and zfree are set to Z_NULL, deflateInit updates them to use default allocation functions. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION requests a default compromise between speed and compression (currently equivalent to level 6). deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if level is not a valid compression level, Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible with the version assumed by the caller (ZLIB_VERSION). msg is set to null if there is no error message. deflateInit does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); /* deflate compresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush. The detailed semantics are as follows. deflate performs one or both of the following actions: - Compress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), next_in and avail_in are updated and processing will resume at this point for the next call of deflate(). - Provide more output starting at next_out and update next_out and avail_out accordingly. This action is forced if the parameter flush is non zero. Forcing flush frequently degrades the compression ratio, so this parameter should be set only when necessary (in interactive applications). Some output may be provided even if flush is not set. Before the call of deflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating avail_in or avail_out accordingly; avail_out should never be zero before the call. The application can consume the compressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to decide how much data to accumualte before producing output, in order to maximize compression. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is flushed to the output buffer and the output is aligned on a byte boundary, so that the decompressor can get all input data available so far. (In particular avail_in is zero after the call if enough output space has been provided before the call.) Flushing may degrade compression for some compression algorithms and so it should be used only when necessary. If flush is set to Z_FULL_FLUSH, all output is flushed as with Z_SYNC_FLUSH, and the compression state is reset so that decompression can restart from this point if previous compressed data has been damaged or if random access is desired. Using Z_FULL_FLUSH too often can seriously degrade compression. If deflate returns with avail_out == 0, this function must be called again with the same value of the flush parameter and more output space (updated avail_out), until the flush is complete (deflate returns with non-zero avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that avail_out is greater than six to avoid repeated flush markers due to avail_out == 0 on return. If the parameter flush is set to Z_FINISH, pending input is processed, pending output is flushed and deflate returns with Z_STREAM_END if there was enough output space; if deflate returns with Z_OK, this function must be called again with Z_FINISH and more output space (updated avail_out) but no more input data, until it returns with Z_STREAM_END or an error. After deflate has returned Z_STREAM_END, the only possible operations on the stream are deflateReset or deflateEnd. Z_FINISH can be used immediately after deflateInit if all the compression is to be done in a single step. In this case, avail_out must be at least the value returned by deflateBound (see below). If deflate does not return Z_STREAM_END, then it must be called again as described above. deflate() sets strm->adler to the adler32 checksum of all input read so far (that is, total_in bytes). deflate() may update strm->data_type if it can make a good guess about the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered binary. This field is only for information purposes and does not affect the compression algorithm in any manner. deflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if all input has been consumed and all output has been produced (only when flush is set to Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and deflate() can be called again with more input and more output space to continue compressing. */ ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); /* All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state was inconsistent, Z_DATA_ERROR if the stream was freed prematurely (some input or output was discarded). In the error case, msg may be set but then points to a static string (which must not be deallocated). */ /* ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); Initializes the internal stream state for decompression. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. If next_in is not Z_NULL and avail_in is large enough (the exact value depends on the compression method), inflateInit determines the compression method from the zlib header and allocates all data structures accordingly; otherwise the allocation will be deferred to the first call of inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to use default allocation functions. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library version is incompatible with the version assumed by the caller. msg is set to null if there is no error message. inflateInit does not perform any decompression apart from reading the zlib header if present: this will be done by inflate(). (So next_in and avail_in may be modified, but next_out and avail_out are unchanged.) */ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); /* inflate decompresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush. The detailed semantics are as follows. inflate performs one or both of the following actions: - Decompress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), next_in is updated and processing will resume at this point for the next call of inflate(). - Provide more output starting at next_out and update next_out and avail_out accordingly. inflate() provides as much output as possible, until there is no more input data or no more space in the output buffer (see below about the flush parameter). Before the call of inflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating the next_* and avail_* values accordingly. The application can consume the uncompressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of inflate(). If inflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much output as possible to the output buffer. Z_BLOCK requests that inflate() stop if and when it gets to the next deflate block boundary. When decoding the zlib or gzip format, this will cause inflate() to return immediately after the header and before the first block. When doing a raw inflate, inflate() will go ahead and process the first block, and will return when it gets to the end of that block, or when it runs out of data. The Z_BLOCK option assists in appending to or combining deflate streams. Also to assist in this, on return inflate() will set strm->data_type to the number of unused bits in the last byte taken from strm->next_in, plus 64 if inflate() is currently decoding the last block in the deflate stream, plus 128 if inflate() returned immediately after decoding an end-of-block code or decoding the complete header up to just before the first byte of the deflate stream. The end-of-block will not be indicated until all of the uncompressed data from that block has been written to strm->next_out. The number of unused bits may in general be greater than seven, except when bit 7 of data_type is set, in which case the number of unused bits will be less than eight. inflate() should normally be called until it returns Z_STREAM_END or an error. However if all decompression is to be performed in a single step (a single call of inflate), the parameter flush should be set to Z_FINISH. In this case all pending input is processed and all pending output is flushed; avail_out must be large enough to hold all the uncompressed data. (The size of the uncompressed data may have been saved by the compressor for this purpose.) The next operation on this stream must be inflateEnd to deallocate the decompression state. The use of Z_FINISH is never required, but can be used to inform inflate that a faster approach may be used for the single inflate() call. In this implementation, inflate() always flushes as much output as possible to the output buffer, and always uses the faster approach on the first call. So the only effect of the flush parameter in this implementation is on the return value of inflate(), as noted below, or when it returns early because Z_BLOCK is used. If a preset dictionary is needed after this call (see inflateSetDictionary below), inflate sets strm->adler to the adler32 checksum of the dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise it sets strm->adler to the adler32 checksum of all output produced so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described below. At the end of the stream, inflate() checks that its computed adler32 checksum is equal to that saved by the compressor and returns Z_STREAM_END only if the checksum is correct. inflate() will decompress and check either zlib-wrapped or gzip-wrapped deflate data. The header type is detected automatically. Any information contained in the gzip header is not retained, so applications that need that information should instead use raw inflate, see inflateInit2() below, or inflateBack() and perform their own processing of the gzip header and trailer. inflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if the end of the compressed data has been reached and all uncompressed output has been produced, Z_NEED_DICT if a preset dictionary is needed at this point, Z_DATA_ERROR if the input data was corrupted (input stream not conforming to the zlib format or incorrect check value), Z_STREAM_ERROR if the stream structure was inconsistent (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if no progress is possible or if there was not enough room in the output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and inflate() can be called again with more input and more output space to continue decompressing. If Z_DATA_ERROR is returned, the application may then call inflateSync() to look for a good compression block if a partial recovery of the data is desired. */ ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); /* All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state was inconsistent. In the error case, msg may be set but then points to a static string (which must not be deallocated). */ /* Advanced functions */ /* The following functions are needed only in some special applications. */ /* ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy)); This is another version of deflateInit with more compression options. The fields next_in, zalloc, zfree and opaque must be initialized before by the caller. The method parameter is the compression method. It must be Z_DEFLATED in this version of the library. The windowBits parameter is the base two logarithm of the window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. Larger values of this parameter result in better compression at the expense of memory usage. The default value is 15 if deflateInit is used instead. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits determines the window size. deflate() will then generate raw deflate data with no zlib header or trailer, and will not compute an adler32 check value. windowBits can also be greater than 15 for optional gzip encoding. Add 16 to windowBits to write a simple gzip header and trailer around the compressed data instead of a zlib wrapper. The gzip header will have no file name, no extra data, no comment, no modification time (set to zero), no header crc, and the operating system will be set to 255 (unknown). If a gzip stream is being written, strm->adler is a crc32 instead of an adler32. The memLevel parameter specifies how much memory should be allocated for the internal compression state. memLevel=1 uses minimum memory but is slow and reduces compression ratio; memLevel=9 uses maximum memory for optimal speed. The default value is 8. See zconf.h for total memory usage as a function of windowBits and memLevel. The strategy parameter is used to tune the compression algorithm. Use the value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no string match), or Z_RLE to limit match distances to one (run-length encoding). Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. The effect of Z_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately. Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid method). msg is set to null if there is no error message. deflateInit2 does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, const Bytef *dictionary, uInt dictLength)); /* Initializes the compression dictionary from the given byte sequence without producing any compressed output. This function must be called immediately after deflateInit, deflateInit2 or deflateReset, before any call of deflate. The compressor and decompressor must use exactly the same dictionary (see inflateSetDictionary). The dictionary should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary. Depending on the size of the compression data structures selected by deflateInit or deflateInit2, a part of the dictionary may in effect be discarded, for example if the dictionary is larger than the window size in deflate or deflate2. Thus the strings most likely to be useful should be put at the end of the dictionary, not at the front. In addition, the current implementation of deflate will use at most the window size minus 262 bytes of the provided dictionary. Upon return of this function, strm->adler is set to the adler32 value of the dictionary; the decompressor may later use this value to determine which dictionary has been used by the compressor. (The adler32 value applies to the whole dictionary even if only a subset of the dictionary is actually used by the compressor.) If a raw deflate was requested, then the adler32 value is not computed and strm->adler is not set. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a parameter is invalid (such as NULL dictionary) or the stream state is inconsistent (for example if deflate has already been called for this stream or if the compression method is bsort). deflateSetDictionary does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, z_streamp source)); /* Sets the destination stream as a complete copy of the source stream. This function can be useful when several compression strategies will be tried, for example when there are several ways of pre-processing the input data with a filter. The streams that will be discarded should then be freed by calling deflateEnd. Note that deflateCopy duplicates the internal compression state which can be quite large, so this strategy is slow and can consume lots of memory. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being NULL). msg is left unchanged in both source and destination. */ ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); /* This function is equivalent to deflateEnd followed by deflateInit, but does not free and reallocate all the internal compression state. The stream will keep the same compression level and any other attributes that may have been set by deflateInit2. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being NULL). */ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, int level, int strategy)); /* Dynamically update the compression level and compression strategy. The interpretation of level and strategy is as in deflateInit2. This can be used to switch between compression and straight copy of the input data, or to switch to a different kind of input data requiring a different strategy. If the compression level is changed, the input available so far is compressed with the old level (and may be flushed); the new level will take effect only at the next call of deflate(). Before the call of deflateParams, the stream state must be set as for a call of deflate(), since the currently available input may have to be compressed and flushed. In particular, strm->avail_out must be non-zero. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if strm->avail_out was zero. */ ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)); /* Fine tune deflate's internal compression parameters. This should only be used by someone who understands the algorithm used by zlib's deflate for searching for the best matching string, and even then only by the most fanatic optimizer trying to squeeze out the last compressed bit for their specific input data. Read the deflate.c source code for the meaning of the max_lazy, good_length, nice_length, and max_chain parameters. deflateTune() can be called after deflateInit() or deflateInit2(), and returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. */ ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, uLong sourceLen)); /* deflateBound() returns an upper bound on the compressed size after deflation of sourceLen bytes. It must be called after deflateInit() or deflateInit2(). This would be used to allocate an output buffer for deflation in a single pass, and so would be called before deflate(). */ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, int bits, int value)); /* deflatePrime() inserts bits in the deflate output stream. The intent is that this function is used to start off the deflate output with the bits leftover from a previous deflate stream when appending to it. As such, this function can only be used for raw deflate, and must be used before the first deflate() call after a deflateInit2() or deflateReset(). bits must be less than or equal to 16, and that many of the least significant bits of value will be inserted in the output. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, gz_headerp head)); /* deflateSetHeader() provides gzip header information for when a gzip stream is requested by deflateInit2(). deflateSetHeader() may be called after deflateInit2() or deflateReset() and before the first call of deflate(). The text, time, os, extra field, name, and comment information in the provided gz_header structure are written to the gzip header (xflag is ignored -- the extra flags are set according to the compression level). The caller must assure that, if not Z_NULL, name and comment are terminated with a zero byte, and that if extra is not Z_NULL, that extra_len bytes are available there. If hcrc is true, a gzip header crc is included. Note that the current versions of the command-line version of gzip (up through version 1.3.x) do not support header crc's, and will report that it is a "multi-part gzip file" and give up. If deflateSetHeader is not used, the default gzip header has text false, the time set to zero, and os set to 255, with no extra, name, or comment fields. The gzip header is returned to the default state by deflateReset(). deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ /* ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, int windowBits)); This is another version of inflateInit with an extra parameter. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. The windowBits parameter is the base two logarithm of the maximum window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. The default value is 15 if inflateInit is used instead. windowBits must be greater than or equal to the windowBits value provided to deflateInit2() while compressing, or it must be equal to 15 if deflateInit2() was not used. If a compressed stream with a larger window size is given as input, inflate() will return with the error code Z_DATA_ERROR instead of trying to allocate a larger window. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits determines the window size. inflate() will then process raw deflate data, not looking for a zlib or gzip header, not generating a check value, and not looking for any check values for comparison at the end of the stream. This is for use with other formats that use the deflate compressed data format such as zip. Those formats provide their own check values. If a custom format is developed using the raw deflate format for compressed data, it is recommended that a check value such as an adler32 or a crc32 be applied to the uncompressed data as is done in the zlib, gzip, and zip formats. For most applications, the zlib format should be used as is. Note that comments above on the use in deflateInit2() applies to the magnitude of windowBits. windowBits can also be greater than 15 for optional gzip decoding. Add 32 to windowBits to enable zlib and gzip decoding with automatic header detection, or add 16 to decode only the gzip format (the zlib format will return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a crc32 instead of an adler32. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg is set to null if there is no error message. inflateInit2 does not perform any decompression apart from reading the zlib header if present: this will be done by inflate(). (So next_in and avail_in may be modified, but next_out and avail_out are unchanged.) */ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, const Bytef *dictionary, uInt dictLength)); /* Initializes the decompression dictionary from the given uncompressed byte sequence. This function must be called immediately after a call of inflate, if that call returned Z_NEED_DICT. The dictionary chosen by the compressor can be determined from the adler32 value returned by that call of inflate. The compressor and decompressor must use exactly the same dictionary (see deflateSetDictionary). For raw inflate, this function can be called immediately after inflateInit2() or inflateReset() and before any call of inflate() to set the dictionary. The application must insure that the dictionary that was used for compression is provided. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a parameter is invalid (such as NULL dictionary) or the stream state is inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the expected one (incorrect adler32 value). inflateSetDictionary does not perform any decompression: this will be done by subsequent calls of inflate(). */ ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); /* Skips invalid compressed data until a full flush point (see above the description of deflate with Z_FULL_FLUSH) can be found, or until all available input is skipped. No output is provided. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the success case, the application may save the current current value of total_in which indicates where valid compressed data was found. In the error case, the application may repeatedly call inflateSync, providing more input each time, until success or end of the input data. */ ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, z_streamp source)); /* Sets the destination stream as a complete copy of the source stream. This function can be useful when randomly accessing a large stream. The first pass through the stream can periodically record the inflate state, allowing restarting inflate at those points when randomly accessing the stream. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being NULL). msg is left unchanged in both source and destination. */ ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); /* This function is equivalent to inflateEnd followed by inflateInit, but does not free and reallocate all the internal decompression state. The stream will keep attributes that may have been set by inflateInit2. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being NULL). */ ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, int bits, int value)); /* This function inserts bits in the inflate input stream. The intent is that this function is used to start inflating at a bit position in the middle of a byte. The provided bits will be used before any bytes are used from next_in. This function should only be used with raw inflate, and should be used before the first inflate() call after inflateInit2() or inflateReset(). bits must be less than or equal to 16, and that many of the least significant bits of value will be inserted in the input. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, gz_headerp head)); /* inflateGetHeader() requests that gzip header information be stored in the provided gz_header structure. inflateGetHeader() may be called after inflateInit2() or inflateReset(), and before the first call of inflate(). As inflate() processes the gzip stream, head->done is zero until the header is completed, at which time head->done is set to one. If a zlib stream is being decoded, then head->done is set to -1 to indicate that there will be no gzip header information forthcoming. Note that Z_BLOCK can be used to force inflate() to return immediately after header processing is complete and before any actual data is decompressed. The text, time, xflags, and os fields are filled in with the gzip header contents. hcrc is set to true if there is a header CRC. (The header CRC was valid if done is set to one.) If extra is not Z_NULL, then extra_max contains the maximum number of bytes to write to extra. Once done is true, extra_len contains the actual extra field length, and extra contains the extra field, or that field truncated if extra_max is less than extra_len. If name is not Z_NULL, then up to name_max characters are written there, terminated with a zero unless the length is greater than name_max. If comment is not Z_NULL, then up to comm_max characters are written there, terminated with a zero unless the length is greater than comm_max. When any of extra, name, or comment are not Z_NULL and the respective field is not present in the header, then that field is set to Z_NULL to signal its absence. This allows the use of deflateSetHeader() with the returned structure to duplicate the header. However if those fields are set to allocated memory, then the application will need to save those pointers elsewhere so that they can be eventually freed. If inflateGetHeader is not used, then the header information is simply discarded. The header is always checked for validity, including the header CRC if present. inflateReset() will reset the process to discard the header information. The application would need to call inflateGetHeader() again to retrieve the header from the next gzip stream. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ /* ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, unsigned char FAR *window)); Initialize the internal stream state for decompression using inflateBack() calls. The fields zalloc, zfree and opaque in strm must be initialized before the call. If zalloc and zfree are Z_NULL, then the default library- derived memory allocation routines are used. windowBits is the base two logarithm of the window size, in the range 8..15. window is a caller supplied buffer of that size. Except for special applications where it is assured that deflate was used with small window sizes, windowBits must be 15 and a 32K byte window must be supplied to be able to decompress general deflate streams. See inflateBack() for the usage of these routines. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of the paramaters are invalid, Z_MEM_ERROR if the internal state could not be allocated, or Z_VERSION_ERROR if the version of the library does not match the version of the header file. */ typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, in_func in, void FAR *in_desc, out_func out, void FAR *out_desc)); /* inflateBack() does a raw inflate with a single call using a call-back interface for input and output. This is more efficient than inflate() for file i/o applications in that it avoids copying between the output and the sliding window by simply making the window itself the output buffer. This function trusts the application to not change the output buffer passed by the output function, at least until inflateBack() returns. inflateBackInit() must be called first to allocate the internal state and to initialize the state with the user-provided window buffer. inflateBack() may then be used multiple times to inflate a complete, raw deflate stream with each call. inflateBackEnd() is then called to free the allocated state. A raw deflate stream is one with no zlib or gzip header or trailer. This routine would normally be used in a utility that reads zip or gzip files and writes out uncompressed files. The utility would decode the header and process the trailer on its own, hence this routine expects only the raw deflate stream to decompress. This is different from the normal behavior of inflate(), which expects either a zlib or gzip header and trailer around the deflate stream. inflateBack() uses two subroutines supplied by the caller that are then called by inflateBack() for input and output. inflateBack() calls those routines until it reads a complete deflate stream and writes out all of the uncompressed data, or until it encounters an error. The function's parameters and return types are defined above in the in_func and out_func typedefs. inflateBack() will call in(in_desc, &buf) which should return the number of bytes of provided input, and a pointer to that input in buf. If there is no input available, in() must return zero--buf is ignored in that case--and inflateBack() will return a buffer error. inflateBack() will call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() should return zero on success, or non-zero on failure. If out() returns non-zero, inflateBack() will return with an error. Neither in() nor out() are permitted to change the contents of the window provided to inflateBackInit(), which is also the buffer that out() uses to write from. The length written by out() will be at most the window size. Any non-zero amount of input may be provided by in(). For convenience, inflateBack() can be provided input on the first call by setting strm->next_in and strm->avail_in. If that input is exhausted, then in() will be called. Therefore strm->next_in must be initialized before calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in must also be initialized, and then if strm->avail_in is not zero, input will initially be taken from strm->next_in[0 .. strm->avail_in - 1]. The in_desc and out_desc parameters of inflateBack() is passed as the first parameter of in() and out() respectively when they are called. These descriptors can be optionally used to pass any information that the caller- supplied in() and out() functions need to do their job. On return, inflateBack() will set strm->next_in and strm->avail_in to pass back any unused input that was provided by the last in() call. The return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR if in() or out() returned an error, Z_DATA_ERROR if there was a format error in the deflate stream (in which case strm->msg is set to indicate the nature of the error), or Z_STREAM_ERROR if the stream was not properly initialized. In the case of Z_BUF_ERROR, an input or output error can be distinguished using strm->next_in which will be Z_NULL only if in() returned an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to out() returning non-zero. (in() will always be called before out(), so strm->next_in is assured to be defined if out() returns non-zero.) Note that inflateBack() cannot return Z_OK. */ ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); /* All memory allocated by inflateBackInit() is freed. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream state was inconsistent. */ ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); /* Return flags indicating compile-time options. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: 1.0: size of uInt 3.2: size of uLong 5.4: size of voidpf (pointer) 7.6: size of z_off_t Compiler, assembler, and debug options: 8: DEBUG 9: ASMV or ASMINF -- use ASM code 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention 11: 0 (reserved) One-time table building (smaller code, but not thread-safe if true): 12: BUILDFIXED -- build static block decoding tables when needed 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed 14,15: 0 (reserved) Library content (indicates missing functionality): 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking deflate code when not needed) 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect and decode gzip streams (to avoid linking crc code) 18-19: 0 (reserved) Operation variations (changes in library functionality): 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate 21: FASTEST -- deflate algorithm with only one, lowest compression level 22,23: 0 (reserved) The sprintf variant used by gzprintf (zero is best): 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! 26: 0 = returns value, 1 = void -- 1 means inferred string length returned Remainder: 27-31: 0 (reserved) */ /* utility functions */ /* The following utility functions are implemented on top of the basic stream-oriented functions. To simplify the interface, some default options are assumed (compression level and memory usage, standard memory allocation functions). The source code of these utility functions can easily be modified if you need special options. */ ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)); /* Compresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least the value returned by compressBound(sourceLen). Upon exit, destLen is the actual size of the compressed buffer. This function can be used to compress a whole file at once if the input file is mmap'ed. compress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer. */ ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level)); /* Compresses the source buffer into the destination buffer. The level parameter has the same meaning as in deflateInit. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least the value returned by compressBound(sourceLen). Upon exit, destLen is the actual size of the compressed buffer. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, Z_STREAM_ERROR if the level parameter is invalid. */ ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); /* compressBound() returns an upper bound on the compressed size after compress() or compress2() on sourceLen bytes. It would be used before a compress() or compress2() call to allocate the destination buffer. */ ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)); /* Decompresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, destLen is the actual size of the compressed buffer. This function can be used to decompress a whole file at once if the input file is mmap'ed. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. */ typedef voidp gzFile; ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); /* Opens a gzip (.gz) file for reading or writing. The mode parameter is as in fopen ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman only compression as in "wb1h", or 'R' for run-length encoding as in "wb1R". (See the description of deflateInit2 for more information about the strategy parameter.) gzopen can be used to read a file which is not in gzip format; in this case gzread will directly read from the file without decompression. gzopen returns NULL if the file could not be opened or if there was insufficient memory to allocate the (de)compression state; errno can be checked to distinguish the two cases (if errno is zero, the zlib error is Z_MEM_ERROR). */ ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); /* gzdopen() associates a gzFile with the file descriptor fd. File descriptors are obtained from calls like open, dup, creat, pipe or fileno (in the file has been previously opened with fopen). The mode parameter is as in gzopen. The next call of gzclose on the returned gzFile will also close the file descriptor fd, just like fclose(fdopen(fd), mode) closes the file descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). gzdopen returns NULL if there was insufficient memory to allocate the (de)compression state. */ ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); /* Dynamically update the compression level or strategy. See the description of deflateInit2 for the meaning of these parameters. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not opened for writing. */ ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); /* Reads the given number of uncompressed bytes from the compressed file. If the input file was not in gzip format, gzread copies the given number of bytes into the buffer. gzread returns the number of uncompressed bytes actually read (0 for end of file, -1 for error). */ ZEXTERN int ZEXPORT gzwrite OF((gzFile file, voidpc buf, unsigned len)); /* Writes the given number of uncompressed bytes into the compressed file. gzwrite returns the number of uncompressed bytes actually written (0 in case of error). */ ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); /* Converts, formats, and writes the args to the compressed file under control of the format string, as in fprintf. gzprintf returns the number of uncompressed bytes actually written (0 in case of error). The number of uncompressed bytes written is limited to 4095. The caller should assure that this limit is not exceeded. If it is exceeded, then gzprintf() will return return an error (0) with nothing written. In this case, there may also be a buffer overflow with unpredictable consequences, which is possible only if zlib was compiled with the insecure functions sprintf() or vsprintf() because the secure snprintf() or vsnprintf() functions were not available. */ ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); /* Writes the given null-terminated string to the compressed file, excluding the terminating null character. gzputs returns the number of characters written, or -1 in case of error. */ ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); /* Reads bytes from the compressed file until len-1 characters are read, or a newline character is read and transferred to buf, or an end-of-file condition is encountered. The string is then terminated with a null character. gzgets returns buf, or Z_NULL in case of error. */ ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); /* Writes c, converted to an unsigned char, into the compressed file. gzputc returns the value that was written, or -1 in case of error. */ ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); /* Reads one byte from the compressed file. gzgetc returns this byte or -1 in case of end of file or error. */ ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); /* Push one character back onto the stream to be read again later. Only one character of push-back is allowed. gzungetc() returns the character pushed, or -1 on failure. gzungetc() will fail if a character has been pushed but not read yet, or if c is -1. The pushed character will be discarded if the stream is repositioned with gzseek() or gzrewind(). */ ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); /* Flushes all pending output into the compressed file. The parameter flush is as in the deflate() function. The return value is the zlib error number (see function gzerror below). gzflush returns Z_OK if the flush parameter is Z_FINISH and all output could be flushed. gzflush should be called only when strictly necessary because it can degrade compression. */ ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, z_off_t offset, int whence)); /* Sets the starting position for the next gzread or gzwrite on the given compressed file. The offset represents a number of bytes in the uncompressed data stream. The whence parameter is defined as in lseek(2); the value SEEK_END is not supported. If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek then compresses a sequence of zeroes up to the new starting position. gzseek returns the resulting offset location as measured in bytes from the beginning of the uncompressed stream, or -1 in case of error, in particular if the file is opened for writing and the new starting position would be before the current position. */ ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); /* Rewinds the given file. This function is supported only for reading. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) */ ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); /* Returns the starting position for the next gzread or gzwrite on the given compressed file. This position represents a number of bytes in the uncompressed data stream. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) */ ZEXTERN int ZEXPORT gzeof OF((gzFile file)); /* Returns 1 when EOF has previously been detected reading the given input stream, otherwise zero. */ ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); /* Returns 1 if file is being read directly without decompression, otherwise zero. */ ZEXTERN int ZEXPORT gzclose OF((gzFile file)); /* Flushes all pending output if necessary, closes the compressed file and deallocates all the (de)compression state. The return value is the zlib error number (see function gzerror below). */ ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); /* Returns the error message for the last error which occurred on the given compressed file. errnum is set to zlib error number. If an error occurred in the file system and not in the compression library, errnum is set to Z_ERRNO and the application may consult errno to get the exact error code. */ ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); /* Clears the error and end-of-file flags for file. This is analogous to the clearerr() function in stdio. This is useful for continuing to read a gzip file that is being written concurrently. */ /* checksum functions */ /* These functions are not related to compression but are exported anyway because they might be useful in applications using the compression library. */ ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); /* Update a running Adler-32 checksum with the bytes buf[0..len-1] and return the updated checksum. If buf is NULL, this function returns the required initial value for the checksum. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed much faster. Usage example: uLong adler = adler32(0L, Z_NULL, 0); while (read_buffer(buffer, length) != EOF) { adler = adler32(adler, buffer, length); } if (adler != original_adler) error(); */ ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, z_off_t len2)); /* Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. */ ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); /* Update a running CRC-32 with the bytes buf[0..len-1] and return the updated CRC-32. If buf is NULL, this function returns the required initial value for the for the crc. Pre- and post-conditioning (one's complement) is performed within this function so it shouldn't be done by the application. Usage example: uLong crc = crc32(0L, Z_NULL, 0); while (read_buffer(buffer, length) != EOF) { crc = crc32(crc, buffer, length); } if (crc != original_crc) error(); */ ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); /* Combine two CRC-32 check values into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, CRC-32 check values were calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and len2. */ /* various hacks, don't look :) */ /* deflateInit and inflateInit are macros to allow checking the zlib version * and the compiler's view of z_stream: */ ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, const char *version, int stream_size)); ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, unsigned char FAR *window, const char *version, int stream_size)); #define deflateInit(strm, level) \ deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) #define inflateInit(strm) \ inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ (strategy), ZLIB_VERSION, sizeof(z_stream)) #define inflateInit2(strm, windowBits) \ inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) #define inflateBackInit(strm, windowBits, window) \ inflateBackInit_((strm), (windowBits), (window), \ ZLIB_VERSION, sizeof(z_stream)) #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) struct internal_state {int dummy;}; /* hack for buggy compilers */ #endif ZEXTERN const char * ZEXPORT zError OF((int)); ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); #ifdef __cplusplus } #endif #endif /* ZLIB_H */
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/win32/zconf.h
.h
9,544
333
/* zconf.h -- configuration of the zlib compression library * Copyright (C) 1995-2005 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #ifndef ZCONF_H #define ZCONF_H /* * If you *really* need a unique prefix for all types and library functions, * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. */ #ifdef Z_PREFIX # define deflateInit_ z_deflateInit_ # define deflate z_deflate # define deflateEnd z_deflateEnd # define inflateInit_ z_inflateInit_ # define inflate z_inflate # define inflateEnd z_inflateEnd # define deflateInit2_ z_deflateInit2_ # define deflateSetDictionary z_deflateSetDictionary # define deflateCopy z_deflateCopy # define deflateReset z_deflateReset # define deflateParams z_deflateParams # define deflateBound z_deflateBound # define deflatePrime z_deflatePrime # define inflateInit2_ z_inflateInit2_ # define inflateSetDictionary z_inflateSetDictionary # define inflateSync z_inflateSync # define inflateSyncPoint z_inflateSyncPoint # define inflateCopy z_inflateCopy # define inflateReset z_inflateReset # define inflateBack z_inflateBack # define inflateBackEnd z_inflateBackEnd # define compress z_compress # define compress2 z_compress2 # define compressBound z_compressBound # define uncompress z_uncompress # define adler32 z_adler32 # define crc32 z_crc32 # define get_crc_table z_get_crc_table # define zError z_zError # define alloc_func z_alloc_func # define free_func z_free_func # define in_func z_in_func # define out_func z_out_func # define Byte z_Byte # define uInt z_uInt # define uLong z_uLong # define Bytef z_Bytef # define charf z_charf # define intf z_intf # define uIntf z_uIntf # define uLongf z_uLongf # define voidpf z_voidpf # define voidp z_voidp #endif #if defined(__MSDOS__) && !defined(MSDOS) # define MSDOS #endif #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) # define OS2 #endif #if defined(_WINDOWS) && !defined(WINDOWS) # define WINDOWS #endif #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) # ifndef WIN32 # define WIN32 # endif #endif #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) # ifndef SYS16BIT # define SYS16BIT # endif # endif #endif /* * Compile with -DMAXSEG_64K if the alloc function cannot allocate more * than 64k bytes at a time (needed on systems with 16-bit int). */ #ifdef SYS16BIT # define MAXSEG_64K #endif #ifdef MSDOS # define UNALIGNED_OK #endif #ifdef __STDC_VERSION__ # ifndef STDC # define STDC # endif # if __STDC_VERSION__ >= 199901L # ifndef STDC99 # define STDC99 # endif # endif #endif #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) # define STDC #endif #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) # define STDC #endif #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) # define STDC #endif #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) # define STDC #endif #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ # define STDC #endif #ifndef STDC # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ # define const /* note: need a more gentle solution here */ # endif #endif /* Some Mac compilers merge all .h files incorrectly: */ #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) # define NO_DUMMY_DECL #endif /* Maximum value for memLevel in deflateInit2 */ #ifndef MAX_MEM_LEVEL # ifdef MAXSEG_64K # define MAX_MEM_LEVEL 8 # else # define MAX_MEM_LEVEL 9 # endif #endif /* Maximum value for windowBits in deflateInit2 and inflateInit2. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files * created by gzip. (Files created by minigzip can still be extracted by * gzip.) */ #ifndef MAX_WBITS # define MAX_WBITS 15 /* 32K LZ77 window */ #endif /* The memory requirements for deflate are (in bytes): (1 << (windowBits+2)) + (1 << (memLevel+9)) that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) plus a few kilobytes for small objects. For example, if you want to reduce the default memory requirements from 256K to 128K, compile with make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" Of course this will generally degrade compression (there's no free lunch). The memory requirements for inflate are (in bytes) 1 << windowBits that is, 32K for windowBits=15 (default value) plus a few kilobytes for small objects. */ /* Type declarations */ #ifndef OF /* function prototypes */ # ifdef STDC # define OF(args) args # else # define OF(args) () # endif #endif /* The following definitions for FAR are needed only for MSDOS mixed * model programming (small or medium model with some far allocations). * This was tested only with MSC; for other MSDOS compilers you may have * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, * just define FAR to be empty. */ #ifdef SYS16BIT # if defined(M_I86SM) || defined(M_I86MM) /* MSC small or medium model */ # define SMALL_MEDIUM # ifdef _MSC_VER # define FAR _far # else # define FAR far # endif # endif # if (defined(__SMALL__) || defined(__MEDIUM__)) /* Turbo C small or medium model */ # define SMALL_MEDIUM # ifdef __BORLANDC__ # define FAR _far # else # define FAR far # endif # endif #endif #if defined(WINDOWS) || defined(WIN32) /* If building or using zlib as a DLL, define ZLIB_DLL. * This is not mandatory, but it offers a little performance increase. */ # ifdef ZLIB_DLL # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) # ifdef ZLIB_INTERNAL # define ZEXTERN extern __declspec(dllexport) # else # define ZEXTERN extern __declspec(dllimport) # endif # endif # endif /* ZLIB_DLL */ /* If building or using zlib with the WINAPI/WINAPIV calling convention, * define ZLIB_WINAPI. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. */ # ifdef ZLIB_WINAPI # ifdef FAR # undef FAR # endif # include <windows.h> /* No need for _export, use ZLIB.DEF instead. */ /* For complete Windows compatibility, use WINAPI, not __stdcall. */ # define ZEXPORT WINAPI # ifdef WIN32 # define ZEXPORTVA WINAPIV # else # define ZEXPORTVA FAR CDECL # endif # endif #endif #if defined (__BEOS__) # ifdef ZLIB_DLL # ifdef ZLIB_INTERNAL # define ZEXPORT __declspec(dllexport) # define ZEXPORTVA __declspec(dllexport) # else # define ZEXPORT __declspec(dllimport) # define ZEXPORTVA __declspec(dllimport) # endif # endif #endif #ifndef ZEXTERN # define ZEXTERN extern #endif #ifndef ZEXPORT # define ZEXPORT #endif #ifndef ZEXPORTVA # define ZEXPORTVA #endif #ifndef FAR # define FAR #endif #if !defined(__MACTYPES__) typedef unsigned char Byte; /* 8 bits */ #endif typedef unsigned int uInt; /* 16 bits or more */ typedef unsigned long uLong; /* 32 bits or more */ #ifdef SMALL_MEDIUM /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ # define Bytef Byte FAR #else typedef Byte FAR Bytef; #endif typedef char FAR charf; typedef int FAR intf; typedef uInt FAR uIntf; typedef uLong FAR uLongf; #ifdef STDC typedef void const *voidpc; typedef void FAR *voidpf; typedef void *voidp; #else typedef Byte const *voidpc; typedef Byte FAR *voidpf; typedef Byte *voidp; #endif #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */ # include <sys/types.h> /* for off_t */ # include <unistd.h> /* for SEEK_* and off_t */ # ifdef VMS # include <unixio.h> /* for off_t */ # endif # define z_off_t off_t #endif #ifndef SEEK_SET # define SEEK_SET 0 /* Seek from beginning of file. */ # define SEEK_CUR 1 /* Seek from current position. */ # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ #endif #ifndef z_off_t # define z_off_t long #endif #if defined(__OS400__) # define NO_vsnprintf #endif #if defined(__MVS__) # define NO_vsnprintf # ifdef FAR # undef FAR # endif #endif /* MVS linker does not support external names larger than 8 bytes */ #if defined(__MVS__) # pragma map(deflateInit_,"DEIN") # pragma map(deflateInit2_,"DEIN2") # pragma map(deflateEnd,"DEEND") # pragma map(deflateBound,"DEBND") # pragma map(inflateInit_,"ININ") # pragma map(inflateInit2_,"ININ2") # pragma map(inflateEnd,"INEND") # pragma map(inflateSync,"INSY") # pragma map(inflateSetDictionary,"INSEDI") # pragma map(compressBound,"CMBND") # pragma map(inflate_table,"INTABL") # pragma map(inflate_fast,"INFA") # pragma map(inflate_copyright,"INCOPY") #endif #endif /* ZCONF_H */
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/win32/xcurses.h
.h
49,915
1,378
/* Public Domain Curses */ /* $Id: curses.h,v 1.295 2008/07/15 17:13:25 wmcbrine Exp $ */ /*----------------------------------------------------------------------* * PDCurses * *----------------------------------------------------------------------*/ #ifndef __PDCURSES__ #define __PDCURSES__ 1 /*man-start************************************************************** PDCurses definitions list: (Only define those needed) XCURSES True if compiling for X11. PDC_RGB True if you want to use RGB color definitions (Red = 1, Green = 2, Blue = 4) instead of BGR. PDC_WIDE True if building wide-character support. PDC_DLL_BUILD True if building a Win32 DLL. NCURSES_MOUSE_VERSION Use the ncurses mouse API instead of PDCurses' traditional mouse API. PDCurses portable platform definitions list: PDC_BUILD Defines API build version. PDCURSES Enables access to PDCurses-only routines. XOPEN Always true. SYSVcurses True if you are compiling for SYSV portability. BSDcurses True if you are compiling for BSD portability. **man-end****************************************************************/ #define PDC_BUILD 3401 #define PDCURSES 1 /* PDCurses-only routines */ #define XOPEN 1 /* X/Open Curses routines */ #define SYSVcurses 1 /* System V Curses routines */ #define BSDcurses 1 /* BSD Curses routines */ #define CHTYPE_LONG 1 /* size of chtype; long */ /*----------------------------------------------------------------------*/ #include <stdarg.h> #include <stddef.h> #include <stdio.h> /* Required by X/Open usage below */ #ifdef PDC_WIDE # include <wchar.h> #endif #if defined(__cplusplus) || defined(__cplusplus__) || defined(__CPLUSPLUS) extern "C" { # define bool _bool #endif /*---------------------------------------------------------------------- * * PDCurses Manifest Constants * */ #ifndef FALSE # define FALSE 0 #endif #ifndef TRUE # define TRUE 1 #endif #ifndef NULL # define NULL (void *)0 #endif #ifndef ERR # define ERR (-1) #endif #ifndef OK # define OK 0 #endif /*---------------------------------------------------------------------- * * PDCurses Type Declarations * */ typedef unsigned char bool; /* PDCurses Boolean type */ #ifdef CHTYPE_LONG # if _LP64 typedef unsigned int chtype; # else typedef unsigned long chtype; /* 16-bit attr + 16-bit char */ # endif #else typedef unsigned short chtype; /* 8-bit attr + 8-bit char */ #endif #ifdef PDC_WIDE typedef chtype cchar_t; #endif typedef chtype attr_t; /*---------------------------------------------------------------------- * * PDCurses Mouse Interface -- SYSVR4, with extensions * */ typedef struct { int x; /* absolute column, 0 based, measured in characters */ int y; /* absolute row, 0 based, measured in characters */ short button[3]; /* state of each button */ int changes; /* flags indicating what has changed with the mouse */ } MOUSE_STATUS; #define BUTTON_RELEASED 0x0000 #define BUTTON_PRESSED 0x0001 #define BUTTON_CLICKED 0x0002 #define BUTTON_DOUBLE_CLICKED 0x0003 #define BUTTON_TRIPLE_CLICKED 0x0004 #define BUTTON_MOVED 0x0005 /* PDCurses */ #define WHEEL_SCROLLED 0x0006 /* PDCurses */ #define BUTTON_ACTION_MASK 0x0007 /* PDCurses */ #define PDC_BUTTON_SHIFT 0x0008 /* PDCurses */ #define PDC_BUTTON_CONTROL 0x0010 /* PDCurses */ #define PDC_BUTTON_ALT 0x0020 /* PDCurses */ #define BUTTON_MODIFIER_MASK 0x0038 /* PDCurses */ #define MOUSE_X_POS (Mouse_status.x) #define MOUSE_Y_POS (Mouse_status.y) /* * Bits associated with the .changes field: * 3 2 1 0 * 210987654321098765432109876543210 * 1 <- button 1 has changed * 10 <- button 2 has changed * 100 <- button 3 has changed * 1000 <- mouse has moved * 10000 <- mouse position report * 100000 <- mouse wheel up * 1000000 <- mouse wheel down */ #define PDC_MOUSE_MOVED 0x0008 #define PDC_MOUSE_POSITION 0x0010 #define PDC_MOUSE_WHEEL_UP 0x0020 #define PDC_MOUSE_WHEEL_DOWN 0x0040 #define A_BUTTON_CHANGED (Mouse_status.changes & 7) #define MOUSE_MOVED (Mouse_status.changes & PDC_MOUSE_MOVED) #define MOUSE_POS_REPORT (Mouse_status.changes & PDC_MOUSE_POSITION) #define BUTTON_CHANGED(x) (Mouse_status.changes & (1 << ((x) - 1))) #define BUTTON_STATUS(x) (Mouse_status.button[(x) - 1]) #define MOUSE_WHEEL_UP (Mouse_status.changes & PDC_MOUSE_WHEEL_UP) #define MOUSE_WHEEL_DOWN (Mouse_status.changes & PDC_MOUSE_WHEEL_DOWN) /* mouse bit-masks */ #define BUTTON1_RELEASED 0x00000001L #define BUTTON1_PRESSED 0x00000002L #define BUTTON1_CLICKED 0x00000004L #define BUTTON1_DOUBLE_CLICKED 0x00000008L #define BUTTON1_TRIPLE_CLICKED 0x00000010L #define BUTTON1_MOVED 0x00000010L /* PDCurses */ #define BUTTON2_RELEASED 0x00000020L #define BUTTON2_PRESSED 0x00000040L #define BUTTON2_CLICKED 0x00000080L #define BUTTON2_DOUBLE_CLICKED 0x00000100L #define BUTTON2_TRIPLE_CLICKED 0x00000200L #define BUTTON2_MOVED 0x00000200L /* PDCurses */ #define BUTTON3_RELEASED 0x00000400L #define BUTTON3_PRESSED 0x00000800L #define BUTTON3_CLICKED 0x00001000L #define BUTTON3_DOUBLE_CLICKED 0x00002000L #define BUTTON3_TRIPLE_CLICKED 0x00004000L #define BUTTON3_MOVED 0x00004000L /* PDCurses */ /* For the ncurses-compatible functions only, BUTTON4_PRESSED and BUTTON5_PRESSED are returned for mouse scroll wheel up and down; otherwise PDCurses doesn't support buttons 4 and 5 */ #define BUTTON4_RELEASED 0x00008000L #define BUTTON4_PRESSED 0x00010000L #define BUTTON4_CLICKED 0x00020000L #define BUTTON4_DOUBLE_CLICKED 0x00040000L #define BUTTON4_TRIPLE_CLICKED 0x00080000L #define BUTTON5_RELEASED 0x00100000L #define BUTTON5_PRESSED 0x00200000L #define BUTTON5_CLICKED 0x00400000L #define BUTTON5_DOUBLE_CLICKED 0x00800000L #define BUTTON5_TRIPLE_CLICKED 0x01000000L #define MOUSE_WHEEL_SCROLL 0x02000000L /* PDCurses */ #define BUTTON_MODIFIER_SHIFT 0x04000000L /* PDCurses */ #define BUTTON_MODIFIER_CONTROL 0x08000000L /* PDCurses */ #define BUTTON_MODIFIER_ALT 0x10000000L /* PDCurses */ #define ALL_MOUSE_EVENTS 0x1fffffffL #define REPORT_MOUSE_POSITION 0x20000000L /* ncurses mouse interface */ typedef unsigned long mmask_t; typedef struct { short id; /* unused, always 0 */ int x, y, z; /* x, y same as MOUSE_STATUS; z unused */ mmask_t bstate; /* equivalent to changes + button[], but in the same format as used for mousemask() */ } MEVENT; #ifdef NCURSES_MOUSE_VERSION # define BUTTON_SHIFT BUTTON_MODIFIER_SHIFT # define BUTTON_CONTROL BUTTON_MODIFIER_CONTROL # define BUTTON_CTRL BUTTON_MODIFIER_CONTROL # define BUTTON_ALT BUTTON_MODIFIER_ALT #else # define BUTTON_SHIFT PDC_BUTTON_SHIFT # define BUTTON_CONTROL PDC_BUTTON_CONTROL # define BUTTON_ALT PDC_BUTTON_ALT #endif /*---------------------------------------------------------------------- * * PDCurses Structure Definitions * */ typedef struct _win /* definition of a window */ { int _cury; /* current pseudo-cursor */ int _curx; int _maxy; /* max window coordinates */ int _maxx; int _begy; /* origin on screen */ int _begx; int _flags; /* window properties */ chtype _attrs; /* standard attributes and colors */ chtype _bkgd; /* background, normally blank */ bool _clear; /* causes clear at next refresh */ bool _leaveit; /* leaves cursor where it is */ bool _scroll; /* allows window scrolling */ bool _nodelay; /* input character wait flag */ bool _immed; /* immediate update flag */ bool _sync; /* synchronise window ancestors */ bool _use_keypad; /* flags keypad key mode active */ chtype **_y; /* pointer to line pointer array */ int *_firstch; /* first changed character in line */ int *_lastch; /* last changed character in line */ int _tmarg; /* top of scrolling region */ int _bmarg; /* bottom of scrolling region */ int _delayms; /* milliseconds of delay for getch() */ int _parx, _pary; /* coords relative to parent (0,0) */ struct _win *_parent; /* subwin's pointer to parent win */ } WINDOW; /* Avoid using the SCREEN struct directly -- use the corresponding functions if possible. This struct may eventually be made private. */ typedef struct { bool alive; /* if initscr() called, and not endwin() */ bool autocr; /* if cr -> lf */ bool cbreak; /* if terminal unbuffered */ bool echo; /* if terminal echo */ bool raw_inp; /* raw input mode (v. cooked input) */ bool raw_out; /* raw output mode (7 v. 8 bits) */ bool audible; /* FALSE if the bell is visual */ bool mono; /* TRUE if current screen is mono */ bool resized; /* TRUE if TERM has been resized */ bool orig_attr; /* TRUE if we have the original colors */ short orig_fore; /* original screen foreground color */ short orig_back; /* original screen foreground color */ int cursrow; /* position of physical cursor */ int curscol; /* position of physical cursor */ int visibility; /* visibility of cursor */ int orig_cursor; /* original cursor size */ int lines; /* new value for LINES */ int cols; /* new value for COLS */ unsigned long _trap_mbe; /* trap these mouse button events */ unsigned long _map_mbe_to_key; /* map mouse buttons to slk */ int mouse_wait; /* time to wait (in ms) for a button release after a press, in order to count it as a click */ int slklines; /* lines in use by slk_init() */ WINDOW *slk_winptr; /* window for slk */ int linesrippedoff; /* lines ripped off via ripoffline() */ int linesrippedoffontop; /* lines ripped off on top via ripoffline() */ int delaytenths; /* 1/10ths second to wait block getch() for */ bool _preserve; /* TRUE if screen background to be preserved */ int _restore; /* specifies if screen background to be restored, and how */ bool save_key_modifiers; /* TRUE if each key modifiers saved with each key press */ bool return_key_modifiers; /* TRUE if modifier keys are returned as "real" keys */ bool key_code; /* TRUE if last key is a special key; used internally by get_wch() */ #ifdef XCURSES int XcurscrSize; /* size of Xcurscr shared memory block */ bool sb_on; int sb_viewport_y; int sb_viewport_x; int sb_total_y; int sb_total_x; int sb_cur_y; int sb_cur_x; #endif short line_color; /* color of line attributes - default -1 */ } SCREEN; /*---------------------------------------------------------------------- * * PDCurses External Variables * */ #ifdef PDC_DLL_BUILD # ifdef CURSES_LIBRARY # define PDCEX __declspec(dllexport) extern # else # define PDCEX __declspec(dllimport) # endif #else # define PDCEX extern #endif PDCEX int LINES; /* terminal height */ PDCEX int COLS; /* terminal width */ PDCEX WINDOW *stdscr; /* the default screen window */ PDCEX WINDOW *curscr; /* the current screen image */ PDCEX SCREEN *SP; /* curses variables */ PDCEX MOUSE_STATUS Mouse_status; PDCEX int COLORS; PDCEX int COLOR_PAIRS; PDCEX int TABSIZE; PDCEX chtype acs_map[]; /* alternate character set map */ PDCEX char ttytype[]; /* terminal name/description */ /*man-start************************************************************** PDCurses Text Attributes ======================== Originally, PDCurses used a short (16 bits) for its chtype. To include color, a number of things had to be sacrificed from the strict Unix and System V support. The main problem was fitting all character attributes and color into an unsigned char (all 8 bits!). Today, PDCurses by default uses a long (32 bits) for its chtype, as in System V. The short chtype is still available, by undefining CHTYPE_LONG and rebuilding the library. The following is the structure of a win->_attrs chtype: short form: ------------------------------------------------- |15|14|13|12|11|10| 9| 8| 7| 6| 5| 4| 3| 2| 1| 0| ------------------------------------------------- color number | attrs | character eg 'a' The available non-color attributes are bold, reverse and blink. Others have no effect. The high order char is an index into an array of physical colors (defined in color.c) -- 32 foreground/background color pairs (5 bits) plus 3 bits for other attributes. long form: ---------------------------------------------------------------------------- |31|30|29|28|27|26|25|24|23|22|21|20|19|18|17|16|15|14|13|12|..| 3| 2| 1| 0| ---------------------------------------------------------------------------- color number | modifiers | character eg 'a' The available non-color attributes are bold, underline, invisible, right-line, left-line, protect, reverse and blink. 256 color pairs (8 bits), 8 bits for other attributes, and 16 bits for character data. **man-end****************************************************************/ /*** Video attribute macros ***/ #define A_NORMAL (chtype)0 #ifdef CHTYPE_LONG # define A_ALTCHARSET (chtype)0x00010000 # define A_RIGHTLINE (chtype)0x00020000 # define A_LEFTLINE (chtype)0x00040000 # define A_INVIS (chtype)0x00080000 # define A_UNDERLINE (chtype)0x00100000 # define A_REVERSE (chtype)0x00200000 # define A_BLINK (chtype)0x00400000 # define A_BOLD (chtype)0x00800000 # define A_ATTRIBUTES (chtype)0xffff0000 # define A_CHARTEXT (chtype)0x0000ffff # define A_COLOR (chtype)0xff000000 # define A_ITALIC A_INVIS # define A_PROTECT (A_UNDERLINE | A_LEFTLINE | A_RIGHTLINE) # define PDC_ATTR_SHIFT 19 # define PDC_COLOR_SHIFT 24 #else # define A_BOLD (chtype)0x0100 /* X/Open */ # define A_REVERSE (chtype)0x0200 /* X/Open */ # define A_BLINK (chtype)0x0400 /* X/Open */ # define A_ATTRIBUTES (chtype)0xff00 /* X/Open */ # define A_CHARTEXT (chtype)0x00ff /* X/Open */ # define A_COLOR (chtype)0xf800 /* System V */ # define A_ALTCHARSET A_NORMAL /* X/Open */ # define A_PROTECT A_NORMAL /* X/Open */ # define A_UNDERLINE A_NORMAL /* X/Open */ # define A_LEFTLINE A_NORMAL # define A_RIGHTLINE A_NORMAL # define A_ITALIC A_NORMAL # define A_INVIS A_NORMAL # define PDC_ATTR_SHIFT 8 # define PDC_COLOR_SHIFT 11 #endif #define A_STANDOUT (A_REVERSE | A_BOLD) /* X/Open */ #define A_DIM A_NORMAL #define CHR_MSK A_CHARTEXT /* Obsolete */ #define ATR_MSK A_ATTRIBUTES /* Obsolete */ #define ATR_NRM A_NORMAL /* Obsolete */ /* For use with attr_t -- X/Open says, "these shall be distinct", so this is a non-conforming implementation. */ #define WA_ALTCHARSET A_ALTCHARSET #define WA_BLINK A_BLINK #define WA_BOLD A_BOLD #define WA_DIM A_DIM #define WA_INVIS A_INVIS #define WA_LEFT A_LEFTLINE #define WA_PROTECT A_PROTECT #define WA_REVERSE A_REVERSE #define WA_RIGHT A_RIGHTLINE #define WA_STANDOUT A_STANDOUT #define WA_UNDERLINE A_UNDERLINE #define WA_HORIZONTAL A_NORMAL #define WA_LOW A_NORMAL #define WA_TOP A_NORMAL #define WA_VERTICAL A_NORMAL /*** Alternate character set macros ***/ /* 'w' = 32-bit chtype; acs_map[] index | A_ALTCHARSET 'n' = 16-bit chtype; it gets the fallback set because no bit is available for A_ALTCHARSET */ #ifdef CHTYPE_LONG # define ACS_PICK(w, n) ((chtype)w | A_ALTCHARSET) #else # define ACS_PICK(w, n) ((chtype)n) #endif /* VT100-compatible symbols -- box chars */ #define ACS_ULCORNER ACS_PICK('l', '+') #define ACS_LLCORNER ACS_PICK('m', '+') #define ACS_URCORNER ACS_PICK('k', '+') #define ACS_LRCORNER ACS_PICK('j', '+') #define ACS_RTEE ACS_PICK('u', '+') #define ACS_LTEE ACS_PICK('t', '+') #define ACS_BTEE ACS_PICK('v', '+') #define ACS_TTEE ACS_PICK('w', '+') #define ACS_HLINE ACS_PICK('q', '-') #define ACS_VLINE ACS_PICK('x', '|') #define ACS_PLUS ACS_PICK('n', '+') /* VT100-compatible symbols -- other */ #define ACS_S1 ACS_PICK('o', '-') #define ACS_S9 ACS_PICK('s', '_') #define ACS_DIAMOND ACS_PICK('`', '+') #define ACS_CKBOARD ACS_PICK('a', ':') #define ACS_DEGREE ACS_PICK('f', '\'') #define ACS_PLMINUS ACS_PICK('g', '#') #define ACS_BULLET ACS_PICK('~', 'o') /* Teletype 5410v1 symbols -- these are defined in SysV curses, but are not well-supported by most terminals. Stick to VT100 characters for optimum portability. */ #define ACS_LARROW ACS_PICK(',', '<') #define ACS_RARROW ACS_PICK('+', '>') #define ACS_DARROW ACS_PICK('.', 'v') #define ACS_UARROW ACS_PICK('-', '^') #define ACS_BOARD ACS_PICK('h', '#') #define ACS_LANTERN ACS_PICK('i', '*') #define ACS_BLOCK ACS_PICK('0', '#') /* That goes double for these -- undocumented SysV symbols. Don't use them. */ #define ACS_S3 ACS_PICK('p', '-') #define ACS_S7 ACS_PICK('r', '-') #define ACS_LEQUAL ACS_PICK('y', '<') #define ACS_GEQUAL ACS_PICK('z', '>') #define ACS_PI ACS_PICK('{', 'n') #define ACS_NEQUAL ACS_PICK('|', '+') #define ACS_STERLING ACS_PICK('}', 'L') /* Box char aliases */ #define ACS_BSSB ACS_ULCORNER #define ACS_SSBB ACS_LLCORNER #define ACS_BBSS ACS_URCORNER #define ACS_SBBS ACS_LRCORNER #define ACS_SBSS ACS_RTEE #define ACS_SSSB ACS_LTEE #define ACS_SSBS ACS_BTEE #define ACS_BSSS ACS_TTEE #define ACS_BSBS ACS_HLINE #define ACS_SBSB ACS_VLINE #define ACS_SSSS ACS_PLUS /* cchar_t aliases */ #ifdef PDC_WIDE # define WACS_ULCORNER (&(acs_map['l'])) # define WACS_LLCORNER (&(acs_map['m'])) # define WACS_URCORNER (&(acs_map['k'])) # define WACS_LRCORNER (&(acs_map['j'])) # define WACS_RTEE (&(acs_map['u'])) # define WACS_LTEE (&(acs_map['t'])) # define WACS_BTEE (&(acs_map['v'])) # define WACS_TTEE (&(acs_map['w'])) # define WACS_HLINE (&(acs_map['q'])) # define WACS_VLINE (&(acs_map['x'])) # define WACS_PLUS (&(acs_map['n'])) # define WACS_S1 (&(acs_map['o'])) # define WACS_S9 (&(acs_map['s'])) # define WACS_DIAMOND (&(acs_map['`'])) # define WACS_CKBOARD (&(acs_map['a'])) # define WACS_DEGREE (&(acs_map['f'])) # define WACS_PLMINUS (&(acs_map['g'])) # define WACS_BULLET (&(acs_map['~'])) # define WACS_LARROW (&(acs_map[','])) # define WACS_RARROW (&(acs_map['+'])) # define WACS_DARROW (&(acs_map['.'])) # define WACS_UARROW (&(acs_map['-'])) # define WACS_BOARD (&(acs_map['h'])) # define WACS_LANTERN (&(acs_map['i'])) # define WACS_BLOCK (&(acs_map['0'])) # define WACS_S3 (&(acs_map['p'])) # define WACS_S7 (&(acs_map['r'])) # define WACS_LEQUAL (&(acs_map['y'])) # define WACS_GEQUAL (&(acs_map['z'])) # define WACS_PI (&(acs_map['{'])) # define WACS_NEQUAL (&(acs_map['|'])) # define WACS_STERLING (&(acs_map['}'])) # define WACS_BSSB WACS_ULCORNER # define WACS_SSBB WACS_LLCORNER # define WACS_BBSS WACS_URCORNER # define WACS_SBBS WACS_LRCORNER # define WACS_SBSS WACS_RTEE # define WACS_SSSB WACS_LTEE # define WACS_SSBS WACS_BTEE # define WACS_BSSS WACS_TTEE # define WACS_BSBS WACS_HLINE # define WACS_SBSB WACS_VLINE # define WACS_SSSS WACS_PLUS #endif /*** Color macros ***/ #define COLOR_BLACK 0 #ifdef PDC_RGB /* RGB */ # define COLOR_RED 1 # define COLOR_GREEN 2 # define COLOR_BLUE 4 #else /* BGR */ # define COLOR_BLUE 1 # define COLOR_GREEN 2 # define COLOR_RED 4 #endif #define COLOR_CYAN (COLOR_BLUE | COLOR_GREEN) #define COLOR_MAGENTA (COLOR_RED | COLOR_BLUE) #define COLOR_YELLOW (COLOR_RED | COLOR_GREEN) #define COLOR_WHITE 7 /*---------------------------------------------------------------------- * * Function and Keypad Key Definitions. * Many are just for compatibility. * */ #define KEY_CODE_YES 0x100 /* If get_wch() gives a key code */ #define KEY_BREAK 0x101 /* Not on PC KBD */ #define KEY_DOWN 0x102 /* Down arrow key */ #define KEY_UP 0x103 /* Up arrow key */ #define KEY_LEFT 0x104 /* Left arrow key */ #define KEY_RIGHT 0x105 /* Right arrow key */ #define KEY_HOME 0x106 /* home key */ #define KEY_BACKSPACE 0x107 /* not on pc */ #define KEY_F0 0x108 /* function keys; 64 reserved */ #define KEY_DL 0x148 /* delete line */ #define KEY_IL 0x149 /* insert line */ #define KEY_DC 0x14a /* delete character */ #define KEY_IC 0x14b /* insert char or enter ins mode */ #define KEY_EIC 0x14c /* exit insert char mode */ #define KEY_CLEAR 0x14d /* clear screen */ #define KEY_EOS 0x14e /* clear to end of screen */ #define KEY_EOL 0x14f /* clear to end of line */ #define KEY_SF 0x150 /* scroll 1 line forward */ #define KEY_SR 0x151 /* scroll 1 line back (reverse) */ #define KEY_NPAGE 0x152 /* next page */ #define KEY_PPAGE 0x153 /* previous page */ #define KEY_STAB 0x154 /* set tab */ #define KEY_CTAB 0x155 /* clear tab */ #define KEY_CATAB 0x156 /* clear all tabs */ #define KEY_ENTER 0x157 /* enter or send (unreliable) */ #define KEY_SRESET 0x158 /* soft/reset (partial/unreliable) */ #define KEY_RESET 0x159 /* reset/hard reset (unreliable) */ #define KEY_PRINT 0x15a /* print/copy */ #define KEY_LL 0x15b /* home down/bottom (lower left) */ #define KEY_ABORT 0x15c /* abort/terminate key (any) */ #define KEY_SHELP 0x15d /* short help */ #define KEY_LHELP 0x15e /* long help */ #define KEY_BTAB 0x15f /* Back tab key */ #define KEY_BEG 0x160 /* beg(inning) key */ #define KEY_CANCEL 0x161 /* cancel key */ #define KEY_CLOSE 0x162 /* close key */ #define KEY_COMMAND 0x163 /* cmd (command) key */ #define KEY_COPY 0x164 /* copy key */ #define KEY_CREATE 0x165 /* create key */ #define KEY_END 0x166 /* end key */ #define KEY_EXIT 0x167 /* exit key */ #define KEY_FIND 0x168 /* find key */ #define KEY_HELP 0x169 /* help key */ #define KEY_MARK 0x16a /* mark key */ #define KEY_MESSAGE 0x16b /* message key */ #define KEY_MOVE 0x16c /* move key */ #define KEY_NEXT 0x16d /* next object key */ #define KEY_OPEN 0x16e /* open key */ #define KEY_OPTIONS 0x16f /* options key */ #define KEY_PREVIOUS 0x170 /* previous object key */ #define KEY_REDO 0x171 /* redo key */ #define KEY_REFERENCE 0x172 /* ref(erence) key */ #define KEY_REFRESH 0x173 /* refresh key */ #define KEY_REPLACE 0x174 /* replace key */ #define KEY_RESTART 0x175 /* restart key */ #define KEY_RESUME 0x176 /* resume key */ #define KEY_SAVE 0x177 /* save key */ #define KEY_SBEG 0x178 /* shifted beginning key */ #define KEY_SCANCEL 0x179 /* shifted cancel key */ #define KEY_SCOMMAND 0x17a /* shifted command key */ #define KEY_SCOPY 0x17b /* shifted copy key */ #define KEY_SCREATE 0x17c /* shifted create key */ #define KEY_SDC 0x17d /* shifted delete char key */ #define KEY_SDL 0x17e /* shifted delete line key */ #define KEY_SELECT 0x17f /* select key */ #define KEY_SEND 0x180 /* shifted end key */ #define KEY_SEOL 0x181 /* shifted clear line key */ #define KEY_SEXIT 0x182 /* shifted exit key */ #define KEY_SFIND 0x183 /* shifted find key */ #define KEY_SHOME 0x184 /* shifted home key */ #define KEY_SIC 0x185 /* shifted input key */ #define KEY_SLEFT 0x187 /* shifted left arrow key */ #define KEY_SMESSAGE 0x188 /* shifted message key */ #define KEY_SMOVE 0x189 /* shifted move key */ #define KEY_SNEXT 0x18a /* shifted next key */ #define KEY_SOPTIONS 0x18b /* shifted options key */ #define KEY_SPREVIOUS 0x18c /* shifted prev key */ #define KEY_SPRINT 0x18d /* shifted print key */ #define KEY_SREDO 0x18e /* shifted redo key */ #define KEY_SREPLACE 0x18f /* shifted replace key */ #define KEY_SRIGHT 0x190 /* shifted right arrow */ #define KEY_SRSUME 0x191 /* shifted resume key */ #define KEY_SSAVE 0x192 /* shifted save key */ #define KEY_SSUSPEND 0x193 /* shifted suspend key */ #define KEY_SUNDO 0x194 /* shifted undo key */ #define KEY_SUSPEND 0x195 /* suspend key */ #define KEY_UNDO 0x196 /* undo key */ /* PDCurses-specific key definitions -- PC only */ #define ALT_0 0x197 #define ALT_1 0x198 #define ALT_2 0x199 #define ALT_3 0x19a #define ALT_4 0x19b #define ALT_5 0x19c #define ALT_6 0x19d #define ALT_7 0x19e #define ALT_8 0x19f #define ALT_9 0x1a0 #define ALT_A 0x1a1 #define ALT_B 0x1a2 #define ALT_C 0x1a3 #define ALT_D 0x1a4 #define ALT_E 0x1a5 #define ALT_F 0x1a6 #define ALT_G 0x1a7 #define ALT_H 0x1a8 #define ALT_I 0x1a9 #define ALT_J 0x1aa #define ALT_K 0x1ab #define ALT_L 0x1ac #define ALT_M 0x1ad #define ALT_N 0x1ae #define ALT_O 0x1af #define ALT_P 0x1b0 #define ALT_Q 0x1b1 #define ALT_R 0x1b2 #define ALT_S 0x1b3 #define ALT_T 0x1b4 #define ALT_U 0x1b5 #define ALT_V 0x1b6 #define ALT_W 0x1b7 #define ALT_X 0x1b8 #define ALT_Y 0x1b9 #define ALT_Z 0x1ba #define CTL_LEFT 0x1bb /* Control-Left-Arrow */ #define CTL_RIGHT 0x1bc #define CTL_PGUP 0x1bd #define CTL_PGDN 0x1be #define CTL_HOME 0x1bf #define CTL_END 0x1c0 #define KEY_A1 0x1c1 /* upper left on Virtual keypad */ #define KEY_A2 0x1c2 /* upper middle on Virt. keypad */ #define KEY_A3 0x1c3 /* upper right on Vir. keypad */ #define KEY_B1 0x1c4 /* middle left on Virt. keypad */ #define KEY_B2 0x1c5 /* center on Virt. keypad */ #define KEY_B3 0x1c6 /* middle right on Vir. keypad */ #define KEY_C1 0x1c7 /* lower left on Virt. keypad */ #define KEY_C2 0x1c8 /* lower middle on Virt. keypad */ #define KEY_C3 0x1c9 /* lower right on Vir. keypad */ #define PADSLASH 0x1ca /* slash on keypad */ #define PADENTER 0x1cb /* enter on keypad */ #define CTL_PADENTER 0x1cc /* ctl-enter on keypad */ #define ALT_PADENTER 0x1cd /* alt-enter on keypad */ #define PADSTOP 0x1ce /* stop on keypad */ #define PADSTAR 0x1cf /* star on keypad */ #define PADMINUS 0x1d0 /* minus on keypad */ #define PADPLUS 0x1d1 /* plus on keypad */ #define CTL_PADSTOP 0x1d2 /* ctl-stop on keypad */ #define CTL_PADCENTER 0x1d3 /* ctl-enter on keypad */ #define CTL_PADPLUS 0x1d4 /* ctl-plus on keypad */ #define CTL_PADMINUS 0x1d5 /* ctl-minus on keypad */ #define CTL_PADSLASH 0x1d6 /* ctl-slash on keypad */ #define CTL_PADSTAR 0x1d7 /* ctl-star on keypad */ #define ALT_PADPLUS 0x1d8 /* alt-plus on keypad */ #define ALT_PADMINUS 0x1d9 /* alt-minus on keypad */ #define ALT_PADSLASH 0x1da /* alt-slash on keypad */ #define ALT_PADSTAR 0x1db /* alt-star on keypad */ #define ALT_PADSTOP 0x1dc /* alt-stop on keypad */ #define CTL_INS 0x1dd /* ctl-insert */ #define ALT_DEL 0x1de /* alt-delete */ #define ALT_INS 0x1df /* alt-insert */ #define CTL_UP 0x1e0 /* ctl-up arrow */ #define CTL_DOWN 0x1e1 /* ctl-down arrow */ #define CTL_TAB 0x1e2 /* ctl-tab */ #define ALT_TAB 0x1e3 #define ALT_MINUS 0x1e4 #define ALT_EQUAL 0x1e5 #define ALT_HOME 0x1e6 #define ALT_PGUP 0x1e7 #define ALT_PGDN 0x1e8 #define ALT_END 0x1e9 #define ALT_UP 0x1ea /* alt-up arrow */ #define ALT_DOWN 0x1eb /* alt-down arrow */ #define ALT_RIGHT 0x1ec /* alt-right arrow */ #define ALT_LEFT 0x1ed /* alt-left arrow */ #define ALT_ENTER 0x1ee /* alt-enter */ #define ALT_ESC 0x1ef /* alt-escape */ #define ALT_BQUOTE 0x1f0 /* alt-back quote */ #define ALT_LBRACKET 0x1f1 /* alt-left bracket */ #define ALT_RBRACKET 0x1f2 /* alt-right bracket */ #define ALT_SEMICOLON 0x1f3 /* alt-semi-colon */ #define ALT_FQUOTE 0x1f4 /* alt-forward quote */ #define ALT_COMMA 0x1f5 /* alt-comma */ #define ALT_STOP 0x1f6 /* alt-stop */ #define ALT_FSLASH 0x1f7 /* alt-forward slash */ #define ALT_BKSP 0x1f8 /* alt-backspace */ #define CTL_BKSP 0x1f9 /* ctl-backspace */ #define PAD0 0x1fa /* keypad 0 */ #define CTL_PAD0 0x1fb /* ctl-keypad 0 */ #define CTL_PAD1 0x1fc #define CTL_PAD2 0x1fd #define CTL_PAD3 0x1fe #define CTL_PAD4 0x1ff #define CTL_PAD5 0x200 #define CTL_PAD6 0x201 #define CTL_PAD7 0x202 #define CTL_PAD8 0x203 #define CTL_PAD9 0x204 #define ALT_PAD0 0x205 /* alt-keypad 0 */ #define ALT_PAD1 0x206 #define ALT_PAD2 0x207 #define ALT_PAD3 0x208 #define ALT_PAD4 0x209 #define ALT_PAD5 0x20a #define ALT_PAD6 0x20b #define ALT_PAD7 0x20c #define ALT_PAD8 0x20d #define ALT_PAD9 0x20e #define CTL_DEL 0x20f /* clt-delete */ #define ALT_BSLASH 0x210 /* alt-back slash */ #define CTL_ENTER 0x211 /* ctl-enter */ #define SHF_PADENTER 0x212 /* shift-enter on keypad */ #define SHF_PADSLASH 0x213 /* shift-slash on keypad */ #define SHF_PADSTAR 0x214 /* shift-star on keypad */ #define SHF_PADPLUS 0x215 /* shift-plus on keypad */ #define SHF_PADMINUS 0x216 /* shift-minus on keypad */ #define SHF_UP 0x217 /* shift-up on keypad */ #define SHF_DOWN 0x218 /* shift-down on keypad */ #define SHF_IC 0x219 /* shift-insert on keypad */ #define SHF_DC 0x21a /* shift-delete on keypad */ #define KEY_MOUSE 0x21b /* "mouse" key */ #define KEY_SHIFT_L 0x21c /* Left-shift */ #define KEY_SHIFT_R 0x21d /* Right-shift */ #define KEY_CONTROL_L 0x21e /* Left-control */ #define KEY_CONTROL_R 0x21f /* Right-control */ #define KEY_ALT_L 0x220 /* Left-alt */ #define KEY_ALT_R 0x221 /* Right-alt */ #define KEY_RESIZE 0x222 /* Window resize */ #define KEY_SUP 0x223 /* Shifted up arrow */ #define KEY_SDOWN 0x224 /* Shifted down arrow */ #define KEY_MIN KEY_BREAK /* Minimum curses key value */ #define KEY_MAX KEY_SDOWN /* Maximum curses key */ #define KEY_F(n) (KEY_F0 + (n)) /*---------------------------------------------------------------------- * * PDCurses Function Declarations * */ /* Standard */ int addch(const chtype); int addchnstr(const chtype *, int); int addchstr(const chtype *); int addnstr(const char *, int); int addstr(const char *); int attroff(chtype); int attron(chtype); int attrset(chtype); int attr_get(attr_t *, short *, void *); int attr_off(attr_t, void *); int attr_on(attr_t, void *); int attr_set(attr_t, short, void *); int baudrate(void); int beep(void); int bkgd(chtype); void bkgdset(chtype); int border(chtype, chtype, chtype, chtype, chtype, chtype, chtype, chtype); int box(WINDOW *, chtype, chtype); bool can_change_color(void); int cbreak(void); int chgat(int, attr_t, short, const void *); int clearok(WINDOW *, bool); int clear(void); int clrtobot(void); int clrtoeol(void); int color_content(short, short *, short *, short *); int color_set(short, void *); int copywin(const WINDOW *, WINDOW *, int, int, int, int, int, int, int); int curs_set(int); int def_prog_mode(void); int def_shell_mode(void); int delay_output(int); int delch(void); int deleteln(void); void delscreen(SCREEN *); int delwin(WINDOW *); WINDOW *derwin(WINDOW *, int, int, int, int); int doupdate(void); WINDOW *dupwin(WINDOW *); int echochar(const chtype); int echo(void); int endwin(void); char erasechar(void); int erase(void); void filter(void); int flash(void); int flushinp(void); chtype getbkgd(WINDOW *); int getnstr(char *, int); int getstr(char *); WINDOW *getwin(FILE *); int halfdelay(int); bool has_colors(void); bool has_ic(void); bool has_il(void); int hline(chtype, int); void idcok(WINDOW *, bool); int idlok(WINDOW *, bool); void immedok(WINDOW *, bool); int inchnstr(chtype *, int); int inchstr(chtype *); chtype inch(void); int init_color(short, short, short, short); int init_pair(short, short, short); WINDOW *initscr(void); int innstr(char *, int); int insch(chtype); int insdelln(int); int insertln(void); int insnstr(const char *, int); int insstr(const char *); int instr(char *); int intrflush(WINDOW *, bool); bool isendwin(void); bool is_linetouched(WINDOW *, int); bool is_wintouched(WINDOW *); char *keyname(int); int keypad(WINDOW *, bool); char killchar(void); int leaveok(WINDOW *, bool); char *longname(void); int meta(WINDOW *, bool); int move(int, int); int mvaddch(int, int, const chtype); int mvaddchnstr(int, int, const chtype *, int); int mvaddchstr(int, int, const chtype *); int mvaddnstr(int, int, const char *, int); int mvaddstr(int, int, const char *); int mvchgat(int, int, int, attr_t, short, const void *); int mvcur(int, int, int, int); int mvdelch(int, int); int mvderwin(WINDOW *, int, int); int mvgetch(int, int); int mvgetnstr(int, int, char *, int); int mvgetstr(int, int, char *); int mvhline(int, int, chtype, int); chtype mvinch(int, int); int mvinchnstr(int, int, chtype *, int); int mvinchstr(int, int, chtype *); int mvinnstr(int, int, char *, int); int mvinsch(int, int, chtype); int mvinsnstr(int, int, const char *, int); int mvinsstr(int, int, const char *); int mvinstr(int, int, char *); int mvprintw(int, int, const char *, ...); int mvscanw(int, int, const char *, ...); int mvvline(int, int, chtype, int); int mvwaddchnstr(WINDOW *, int, int, const chtype *, int); int mvwaddchstr(WINDOW *, int, int, const chtype *); int mvwaddch(WINDOW *, int, int, const chtype); int mvwaddnstr(WINDOW *, int, int, const char *, int); int mvwaddstr(WINDOW *, int, int, const char *); int mvwchgat(WINDOW *, int, int, int, attr_t, short, const void *); int mvwdelch(WINDOW *, int, int); int mvwgetch(WINDOW *, int, int); int mvwgetnstr(WINDOW *, int, int, char *, int); int mvwgetstr(WINDOW *, int, int, char *); int mvwhline(WINDOW *, int, int, chtype, int); int mvwinchnstr(WINDOW *, int, int, chtype *, int); int mvwinchstr(WINDOW *, int, int, chtype *); chtype mvwinch(WINDOW *, int, int); int mvwinnstr(WINDOW *, int, int, char *, int); int mvwinsch(WINDOW *, int, int, chtype); int mvwinsnstr(WINDOW *, int, int, const char *, int); int mvwinsstr(WINDOW *, int, int, const char *); int mvwinstr(WINDOW *, int, int, char *); int mvwin(WINDOW *, int, int); int mvwprintw(WINDOW *, int, int, const char *, ...); int mvwscanw(WINDOW *, int, int, const char *, ...); int mvwvline(WINDOW *, int, int, chtype, int); int napms(int); WINDOW *newpad(int, int); SCREEN *newterm(const char *, FILE *, FILE *); WINDOW *newwin(int, int, int, int); int nl(void); int nocbreak(void); int nodelay(WINDOW *, bool); int noecho(void); int nonl(void); void noqiflush(void); int noraw(void); int notimeout(WINDOW *, bool); int overlay(const WINDOW *, WINDOW *); int overwrite(const WINDOW *, WINDOW *); int pair_content(short, short *, short *); int pechochar(WINDOW *, chtype); int pnoutrefresh(WINDOW *, int, int, int, int, int, int); int prefresh(WINDOW *, int, int, int, int, int, int); int printw(const char *, ...); int putwin(WINDOW *, FILE *); void qiflush(void); int raw(void); int redrawwin(WINDOW *); int refresh(void); int reset_prog_mode(void); int reset_shell_mode(void); int resetty(void); int ripoffline(int, int (*)(WINDOW *, int)); int savetty(void); int scanw(const char *, ...); int scr_dump(const char *); int scr_init(const char *); int scr_restore(const char *); int scr_set(const char *); int scrl(int); int scroll(WINDOW *); int scrollok(WINDOW *, bool); SCREEN *set_term(SCREEN *); int setscrreg(int, int); int slk_attroff(const chtype); int slk_attr_off(const attr_t, void *); int slk_attron(const chtype); int slk_attr_on(const attr_t, void *); int slk_attrset(const chtype); int slk_attr_set(const attr_t, short, void *); int slk_clear(void); int slk_color(short); int slk_init(int); char *slk_label(int); int slk_noutrefresh(void); int slk_refresh(void); int slk_restore(void); int slk_set(int, const char *, int); int slk_touch(void); int standend(void); int standout(void); int start_color(void); WINDOW *subpad(WINDOW *, int, int, int, int); WINDOW *subwin(WINDOW *, int, int, int, int); int syncok(WINDOW *, bool); chtype termattrs(void); attr_t term_attrs(void); char *termname(void); void timeout(int); int touchline(WINDOW *, int, int); int touchwin(WINDOW *); int typeahead(int); int untouchwin(WINDOW *); void use_env(bool); int vidattr(chtype); int vid_attr(attr_t, short, void *); int vidputs(chtype, int (*)(int)); int vid_puts(attr_t, short, void *, int (*)(int)); int vline(chtype, int); int vw_printw(WINDOW *, const char *, va_list); int vwprintw(WINDOW *, const char *, va_list); int vw_scanw(WINDOW *, const char *, va_list); int vwscanw(WINDOW *, const char *, va_list); int waddchnstr(WINDOW *, const chtype *, int); int waddchstr(WINDOW *, const chtype *); int waddch(WINDOW *, const chtype); int waddnstr(WINDOW *, const char *, int); int waddstr(WINDOW *, const char *); int wattroff(WINDOW *, chtype); int wattron(WINDOW *, chtype); int wattrset(WINDOW *, chtype); int wattr_get(WINDOW *, attr_t *, short *, void *); int wattr_off(WINDOW *, attr_t, void *); int wattr_on(WINDOW *, attr_t, void *); int wattr_set(WINDOW *, attr_t, short, void *); void wbkgdset(WINDOW *, chtype); int wbkgd(WINDOW *, chtype); int wborder(WINDOW *, chtype, chtype, chtype, chtype, chtype, chtype, chtype, chtype); int wchgat(WINDOW *, int, attr_t, short, const void *); int wclear(WINDOW *); int wclrtobot(WINDOW *); int wclrtoeol(WINDOW *); int wcolor_set(WINDOW *, short, void *); void wcursyncup(WINDOW *); int wdelch(WINDOW *); int wdeleteln(WINDOW *); int wechochar(WINDOW *, const chtype); int werase(WINDOW *); int wgetch(WINDOW *); int wgetnstr(WINDOW *, char *, int); int wgetstr(WINDOW *, char *); int whline(WINDOW *, chtype, int); int winchnstr(WINDOW *, chtype *, int); int winchstr(WINDOW *, chtype *); chtype winch(WINDOW *); int winnstr(WINDOW *, char *, int); int winsch(WINDOW *, chtype); int winsdelln(WINDOW *, int); int winsertln(WINDOW *); int winsnstr(WINDOW *, const char *, int); int winsstr(WINDOW *, const char *); int winstr(WINDOW *, char *); int wmove(WINDOW *, int, int); int wnoutrefresh(WINDOW *); int wprintw(WINDOW *, const char *, ...); int wredrawln(WINDOW *, int, int); int wrefresh(WINDOW *); int wscanw(WINDOW *, const char *, ...); int wscrl(WINDOW *, int); int wsetscrreg(WINDOW *, int, int); int wstandend(WINDOW *); int wstandout(WINDOW *); void wsyncdown(WINDOW *); void wsyncup(WINDOW *); void wtimeout(WINDOW *, int); int wtouchln(WINDOW *, int, int, int); int wvline(WINDOW *, chtype, int); /* Wide-character functions */ #ifdef PDC_WIDE int addnwstr(const wchar_t *, int); int addwstr(const wchar_t *); int add_wch(const cchar_t *); int add_wchnstr(const cchar_t *, int); int add_wchstr(const cchar_t *); int border_set(const cchar_t *, const cchar_t *, const cchar_t *, const cchar_t *, const cchar_t *, const cchar_t *, const cchar_t *, const cchar_t *); int box_set(WINDOW *, const cchar_t *, const cchar_t *); int echo_wchar(const cchar_t *); int erasewchar(wchar_t *); int getbkgrnd(cchar_t *); int getcchar(const cchar_t *, wchar_t *, attr_t *, short *, void *); int getn_wstr(wint_t *, int); int get_wch(wint_t *); int get_wstr(wint_t *); int hline_set(const cchar_t *, int); int innwstr(wchar_t *, int); int ins_nwstr(const wchar_t *, int); int ins_wch(const cchar_t *); int ins_wstr(const wchar_t *); int inwstr(wchar_t *); int in_wch(cchar_t *); int in_wchnstr(cchar_t *, int); int in_wchstr(cchar_t *); char *key_name(wchar_t); int killwchar(wchar_t *); int mvaddnwstr(int, int, const wchar_t *, int); int mvaddwstr(int, int, const wchar_t *); int mvadd_wch(int, int, const cchar_t *); int mvadd_wchnstr(int, int, const cchar_t *, int); int mvadd_wchstr(int, int, const cchar_t *); int mvgetn_wstr(int, int, wint_t *, int); int mvget_wch(int, int, wint_t *); int mvget_wstr(int, int, wint_t *); int mvhline_set(int, int, const cchar_t *, int); int mvinnwstr(int, int, wchar_t *, int); int mvins_nwstr(int, int, const wchar_t *, int); int mvins_wch(int, int, const cchar_t *); int mvins_wstr(int, int, const wchar_t *); int mvinwstr(int, int, wchar_t *); int mvin_wch(int, int, cchar_t *); int mvin_wchnstr(int, int, cchar_t *, int); int mvin_wchstr(int, int, cchar_t *); int mvvline_set(int, int, const cchar_t *, int); int mvwaddnwstr(WINDOW *, int, int, const wchar_t *, int); int mvwaddwstr(WINDOW *, int, int, const wchar_t *); int mvwadd_wch(WINDOW *, int, int, const cchar_t *); int mvwadd_wchnstr(WINDOW *, int, int, const cchar_t *, int); int mvwadd_wchstr(WINDOW *, int, int, const cchar_t *); int mvwgetn_wstr(WINDOW *, int, int, wint_t *, int); int mvwget_wch(WINDOW *, int, int, wint_t *); int mvwget_wstr(WINDOW *, int, int, wint_t *); int mvwhline_set(WINDOW *, int, int, const cchar_t *, int); int mvwinnwstr(WINDOW *, int, int, wchar_t *, int); int mvwins_nwstr(WINDOW *, int, int, const wchar_t *, int); int mvwins_wch(WINDOW *, int, int, const cchar_t *); int mvwins_wstr(WINDOW *, int, int, const wchar_t *); int mvwin_wch(WINDOW *, int, int, cchar_t *); int mvwin_wchnstr(WINDOW *, int, int, cchar_t *, int); int mvwin_wchstr(WINDOW *, int, int, cchar_t *); int mvwinwstr(WINDOW *, int, int, wchar_t *); int mvwvline_set(WINDOW *, int, int, const cchar_t *, int); int pecho_wchar(WINDOW *, const cchar_t*); int setcchar(cchar_t*, const wchar_t*, const attr_t, short, const void*); int slk_wset(int, const wchar_t *, int); int unget_wch(const wchar_t); int vline_set(const cchar_t *, int); int waddnwstr(WINDOW *, const wchar_t *, int); int waddwstr(WINDOW *, const wchar_t *); int wadd_wch(WINDOW *, const cchar_t *); int wadd_wchnstr(WINDOW *, const cchar_t *, int); int wadd_wchstr(WINDOW *, const cchar_t *); int wbkgrnd(WINDOW *, const cchar_t *); void wbkgrndset(WINDOW *, const cchar_t *); int wborder_set(WINDOW *, const cchar_t *, const cchar_t *, const cchar_t *, const cchar_t *, const cchar_t *, const cchar_t *, const cchar_t *, const cchar_t *); int wecho_wchar(WINDOW *, const cchar_t *); int wgetbkgrnd(WINDOW *, cchar_t *); int wgetn_wstr(WINDOW *, wint_t *, int); int wget_wch(WINDOW *, wint_t *); int wget_wstr(WINDOW *, wint_t *); int whline_set(WINDOW *, const cchar_t *, int); int winnwstr(WINDOW *, wchar_t *, int); int wins_nwstr(WINDOW *, const wchar_t *, int); int wins_wch(WINDOW *, const cchar_t *); int wins_wstr(WINDOW *, const wchar_t *); int winwstr(WINDOW *, wchar_t *); int win_wch(WINDOW *, cchar_t *); int win_wchnstr(WINDOW *, cchar_t *, int); int win_wchstr(WINDOW *, cchar_t *); wchar_t *wunctrl(cchar_t *); int wvline_set(WINDOW *, const cchar_t *, int); #endif /* Quasi-standard */ chtype getattrs(WINDOW *); int getbegx(WINDOW *); int getbegy(WINDOW *); int getmaxx(WINDOW *); int getmaxy(WINDOW *); int getparx(WINDOW *); int getpary(WINDOW *); int getcurx(WINDOW *); int getcury(WINDOW *); void traceoff(void); void traceon(void); char *unctrl(chtype); int crmode(void); int nocrmode(void); int draino(int); int resetterm(void); int fixterm(void); int saveterm(void); int setsyx(int, int); int mouse_set(unsigned long); int mouse_on(unsigned long); int mouse_off(unsigned long); int request_mouse_pos(void); int map_button(unsigned long); void wmouse_position(WINDOW *, int *, int *); unsigned long getmouse(void); unsigned long getbmap(void); /* ncurses */ int assume_default_colors(int, int); const char *curses_version(void); bool has_key(int); int use_default_colors(void); int wresize(WINDOW *, int, int); int mouseinterval(int); mmask_t mousemask(mmask_t, mmask_t *); bool mouse_trafo(int *, int *, bool); int nc_getmouse(MEVENT *); int ungetmouse(MEVENT *); bool wenclose(const WINDOW *, int, int); bool wmouse_trafo(const WINDOW *, int *, int *, bool); /* PDCurses */ int addrawch(chtype); int insrawch(chtype); bool is_termresized(void); int mvaddrawch(int, int, chtype); int mvdeleteln(int, int); int mvinsertln(int, int); int mvinsrawch(int, int, chtype); int mvwaddrawch(WINDOW *, int, int, chtype); int mvwdeleteln(WINDOW *, int, int); int mvwinsertln(WINDOW *, int, int); int mvwinsrawch(WINDOW *, int, int, chtype); int raw_output(bool); int resize_term(int, int); WINDOW *resize_window(WINDOW *, int, int); int waddrawch(WINDOW *, chtype); int winsrawch(WINDOW *, chtype); char wordchar(void); #ifdef PDC_WIDE wchar_t *slk_wlabel(int); #endif void PDC_debug(const char *, ...); int PDC_ungetch(int); int PDC_set_blink(bool); int PDC_set_line_color(short); void PDC_set_title(const char *); int PDC_clearclipboard(void); int PDC_freeclipboard(char *); int PDC_getclipboard(char **, long *); int PDC_setclipboard(const char *, long); unsigned long PDC_get_input_fd(void); unsigned long PDC_get_key_modifiers(void); int PDC_return_key_modifiers(bool); int PDC_save_key_modifiers(bool); #ifdef XCURSES WINDOW *Xinitscr(int, char **); void XCursesExit(void); int sb_init(void); int sb_set_horz(int, int, int); int sb_set_vert(int, int, int); int sb_get_horz(int *, int *, int *); int sb_get_vert(int *, int *, int *); int sb_refresh(void); #endif /*** Functions defined as macros ***/ /* getch() and ungetch() conflict with some DOS libraries */ #define getch() wgetch(stdscr) #define ungetch(ch) PDC_ungetch(ch) #define COLOR_PAIR(n) (((chtype)(n) << PDC_COLOR_SHIFT) & A_COLOR) #define PAIR_NUMBER(n) (((n) & A_COLOR) >> PDC_COLOR_SHIFT) /* These will _only_ work as macros */ #define getbegyx(w, y, x) (y = getbegy(w), x = getbegx(w)) #define getmaxyx(w, y, x) (y = getmaxy(w), x = getmaxx(w)) #define getparyx(w, y, x) (y = getpary(w), x = getparx(w)) #define getyx(w, y, x) (y = getcury(w), x = getcurx(w)) #define getsyx(y, x) { if (curscr->_leaveit) (y)=(x)=-1; \ else getyx(curscr,(y),(x)); } #ifdef NCURSES_MOUSE_VERSION # define getmouse(x) nc_getmouse(x) #endif /* return codes from PDC_getclipboard() and PDC_setclipboard() calls */ #define PDC_CLIP_SUCCESS 0 #define PDC_CLIP_ACCESS_ERROR 1 #define PDC_CLIP_EMPTY 2 #define PDC_CLIP_MEMORY_ERROR 3 /* PDCurses key modifier masks */ #define PDC_KEY_MODIFIER_SHIFT 1 #define PDC_KEY_MODIFIER_CONTROL 2 #define PDC_KEY_MODIFIER_ALT 4 #define PDC_KEY_MODIFIER_NUMLOCK 8 #if defined(__cplusplus) || defined(__cplusplus__) || defined(__CPLUSPLUS) # undef bool } #endif #endif /* __PDCURSES__ */
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/misc/md5.c
.c
9,075
297
/* * This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. */ /* Brutally hacked by John Walker back from ANSI C to K&R (no prototypes) to maintain the tradition that Netfone will compile with Sun's original "cc". */ #include <string.h> #include "md5.h" #ifndef HIGHFIRST #define byteReverse(buf, len) /* Nothing */ #else /* * Note: this code is harmless on little-endian machines. */ void byteReverse(buf, longs) unsigned char *buf; unsigned longs; { uint32_t t; do { t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 | ((unsigned) buf[1] << 8 | buf[0]); *(uint32_t *) buf = t; buf += 4; } while (--longs); } #endif void MD5Transform(uint32_t buf[4], uint32_t in[16]); /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ void MD5Init(ctx) struct MD5Context *ctx; { ctx->buf[0] = 0x67452301; ctx->buf[1] = 0xefcdab89; ctx->buf[2] = 0x98badcfe; ctx->buf[3] = 0x10325476; ctx->bits[0] = 0; ctx->bits[1] = 0; } /* * Update context to reflect the concatenation of another buffer full * of bytes. */ void MD5Update(ctx, buf, len) struct MD5Context *ctx; unsigned char *buf; unsigned len; { uint32_t t; /* Update bitcount */ t = ctx->bits[0]; if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++; /* Carry from low to high */ ctx->bits[1] += len >> 29; t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ /* Handle any leading odd-sized chunks */ if (t) { unsigned char *p = (unsigned char *) ctx->in + t; t = 64 - t; if (len < t) { memcpy(p, buf, len); return; } memcpy(p, buf, t); byteReverse(ctx->in, 16); MD5Transform(ctx->buf, (uint32_t *) ctx->in); buf += t; len -= t; } /* Process data in 64-byte chunks */ while (len >= 64) { memcpy(ctx->in, buf, 64); byteReverse(ctx->in, 16); MD5Transform(ctx->buf, (uint32_t *) ctx->in); buf += 64; len -= 64; } /* Handle any remaining bytes of data. */ memcpy(ctx->in, buf, len); } /* * Final wrapup - pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ void MD5Final(digest, ctx) unsigned char digest[16]; struct MD5Context *ctx; { unsigned count; unsigned char *p; /* Compute number of bytes mod 64 */ count = (ctx->bits[0] >> 3) & 0x3F; /* Set the first char of padding to 0x80. This is safe since there is always at least one byte free */ p = ctx->in + count; *p++ = 0x80; /* Bytes of padding needed to make 64 bytes */ count = 64 - 1 - count; /* Pad out to 56 mod 64 */ if (count < 8) { /* Two lots of padding: Pad the first block to 64 bytes */ memset(p, 0, count); byteReverse(ctx->in, 16); MD5Transform(ctx->buf, (uint32_t *) ctx->in); /* Now fill the next block with 56 bytes */ memset(ctx->in, 0, 56); } else { /* Pad block to 56 bytes */ memset(p, 0, count - 8); } byteReverse(ctx->in, 14); /* Append length in bits and transform */ ((uint32_t *) ctx->in)[14] = ctx->bits[0]; ((uint32_t *) ctx->in)[15] = ctx->bits[1]; MD5Transform(ctx->buf, (uint32_t *) ctx->in); byteReverse((unsigned char *) ctx->buf, 4); memcpy(digest, ctx->buf, 16); memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */ } /* The four core functions - F1 is optimized somewhat */ /* #define F1(x, y, z) (x & y | ~x & z) */ #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) /* This is the central step in the MD5 algorithm. */ #define MD5STEP(f, w, x, y, z, data, s) \ ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x ) /* * The core of the MD5 algorithm, this alters an existing MD5 hash to * reflect the addition of 16 longwords of new data. MD5Update blocks * the data and converts bytes into longwords for this routine. */ void MD5Transform(buf, in) uint32_t buf[4]; uint32_t in[16]; { register uint32_t a, b, c, d; a = buf[0]; b = buf[1]; c = buf[2]; d = buf[3]; MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); buf[0] += a; buf[1] += b; buf[2] += c; buf[3] += d; } /* lh3: the following code is added by me */ #ifdef MD5SUM_MAIN #include <stdio.h> #include <stdlib.h> #include <string.h> #define HEX_STR "0123456789abcdef" static void md5_one(const char *fn) { unsigned char buf[4096], digest[16]; MD5_CTX md5; int l; FILE *fp; fp = strcmp(fn, "-")? fopen(fn, "r") : stdin; if (fp == 0) { fprintf(stderr, "md5sum: %s: No such file or directory\n", fn); exit(1); } MD5Init(&md5); while ((l = fread(buf, 1, 4096, fp)) > 0) MD5Update(&md5, buf, l); MD5Final(digest, &md5); if (fp != stdin) fclose(fp); for (l = 0; l < 16; ++l) printf("%c%c", HEX_STR[digest[l]>>4&0xf], HEX_STR[digest[l]&0xf]); printf(" %s\n", fn); } int main(int argc, char *argv[]) { int i; if (argc == 1) md5_one("-"); else for (i = 1; i < argc; ++i) md5_one(argv[i]); return 0; } #endif
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/misc/md5fa.c
.c
1,550
59
#include <stdio.h> #include <zlib.h> #include "md5.h" #include "kseq.h" #define HEX_STR "0123456789abcdef" KSEQ_INIT(gzFile, gzread) static void md5_one(const char *fn) { MD5_CTX md5_one, md5_all; int l, i, k; gzFile fp; kseq_t *seq; unsigned char unordered[16], digest[16]; for (l = 0; l < 16; ++l) unordered[l] = 0; fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r"); if (fp == 0) { fprintf(stderr, "md5fa: %s: No such file or directory\n", fn); exit(1); } MD5Init(&md5_all); seq = kseq_init(fp); while ((l = kseq_read(seq)) >= 0) { for (i = k = 0; i < seq->seq.l; ++i) { if (islower(seq->seq.s[i])) seq->seq.s[k++] = toupper(seq->seq.s[i]); else if (isupper(seq->seq.s[i])) seq->seq.s[k++] = seq->seq.s[i]; } MD5Init(&md5_one); MD5Update(&md5_one, (unsigned char*)seq->seq.s, k); MD5Final(digest, &md5_one); for (l = 0; l < 16; ++l) { printf("%c%c", HEX_STR[digest[l]>>4&0xf], HEX_STR[digest[l]&0xf]); unordered[l] ^= digest[l]; } printf(" %s %s\n", fn, seq->name.s); MD5Update(&md5_all, (unsigned char*)seq->seq.s, k); } MD5Final(digest, &md5_all); kseq_destroy(seq); for (l = 0; l < 16; ++l) printf("%c%c", HEX_STR[digest[l]>>4&0xf], HEX_STR[digest[l]&0xf]); printf(" %s >ordered\n", fn); for (l = 0; l < 16; ++l) printf("%c%c", HEX_STR[unordered[l]>>4&0xf], HEX_STR[unordered[l]&0xf]); printf(" %s >unordered\n", fn); } int main(int argc, char *argv[]) { int i; if (argc == 1) md5_one("-"); else for (i = 1; i < argc; ++i) md5_one(argv[i]); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/misc/wgsim.c
.c
14,395
420
/* The MIT License Copyright (c) 2008 Genome Research Ltd (GRL). 2011 Heng Li <lh3@live.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* This program is separated from maq's read simulator with Colin * Hercus' modification to allow longer indels. */ #include <stdlib.h> #include <math.h> #include <time.h> #include <assert.h> #include <stdio.h> #include <unistd.h> #include <stdint.h> #include <ctype.h> #include <string.h> #include <zlib.h> #include "kseq.h" KSEQ_INIT(gzFile, gzread) #define PACKAGE_VERSION "0.3.0" const uint8_t nst_nt4_table[256] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5 /*'-'*/, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }; /* Simple normal random number generator, copied from genran.c */ double ran_normal() { static int iset = 0; static double gset; double fac, rsq, v1, v2; if (iset == 0) { do { v1 = 2.0 * drand48() - 1.0; v2 = 2.0 * drand48() - 1.0; rsq = v1 * v1 + v2 * v2; } while (rsq >= 1.0 || rsq == 0.0); fac = sqrt(-2.0 * log(rsq) / rsq); gset = v1 * fac; iset = 1; return v2 * fac; } else { iset = 0; return gset; } } /* wgsim */ enum muttype_t {NOCHANGE = 0, INSERT = 0x1000, SUBSTITUTE = 0xe000, DELETE = 0xf000}; typedef unsigned short mut_t; static mut_t mutmsk = (mut_t)0xf000; typedef struct { int l, m; /* length and maximum buffer size */ mut_t *s; /* sequence */ } mutseq_t; static double ERR_RATE = 0.02; static double MUT_RATE = 0.001; static double INDEL_FRAC = 0.15; static double INDEL_EXTEND = 0.3; static double MAX_N_RATIO = 0.1; void wgsim_mut_diref(const kseq_t *ks, int is_hap, mutseq_t *hap1, mutseq_t *hap2) { int i, deleting = 0; mutseq_t *ret[2]; ret[0] = hap1; ret[1] = hap2; ret[0]->l = ks->seq.l; ret[1]->l = ks->seq.l; ret[0]->m = ks->seq.m; ret[1]->m = ks->seq.m; ret[0]->s = (mut_t *)calloc(ks->seq.m, sizeof(mut_t)); ret[1]->s = (mut_t *)calloc(ks->seq.m, sizeof(mut_t)); for (i = 0; i != ks->seq.l; ++i) { int c; c = ret[0]->s[i] = ret[1]->s[i] = (mut_t)nst_nt4_table[(int)ks->seq.s[i]]; if (deleting) { if (drand48() < INDEL_EXTEND) { if (deleting & 1) ret[0]->s[i] |= DELETE; if (deleting & 2) ret[1]->s[i] |= DELETE; continue; } else deleting = 0; } if (c < 4 && drand48() < MUT_RATE) { // mutation if (drand48() >= INDEL_FRAC) { // substitution double r = drand48(); c = (c + (int)(r * 3.0 + 1)) & 3; if (is_hap || drand48() < 0.333333) { // hom ret[0]->s[i] = ret[1]->s[i] = SUBSTITUTE|c; } else { // het ret[drand48()<0.5?0:1]->s[i] = SUBSTITUTE|c; } } else { // indel if (drand48() < 0.5) { // deletion if (is_hap || drand48() < 0.333333) { // hom-del ret[0]->s[i] = ret[1]->s[i] = DELETE; deleting = 3; } else { // het-del deleting = drand48()<0.5?1:2; ret[deleting-1]->s[i] = DELETE; } } else { // insertion int num_ins = 0, ins = 0; do { num_ins++; ins = (ins << 2) | (int)(drand48() * 4.0); } while (num_ins < 4 && drand48() < INDEL_EXTEND); if (is_hap || drand48() < 0.333333) { // hom-ins ret[0]->s[i] = ret[1]->s[i] = (num_ins << 12) | (ins << 4) | c; } else { // het-ins ret[drand48()<0.5?0:1]->s[i] = (num_ins << 12) | (ins << 4) | c; } } } } } } void wgsim_print_mutref(const char *name, const kseq_t *ks, mutseq_t *hap1, mutseq_t *hap2) { int i; for (i = 0; i != ks->seq.l; ++i) { int c[3]; c[0] = nst_nt4_table[(int)ks->seq.s[i]]; c[1] = hap1->s[i]; c[2] = hap2->s[i]; if (c[0] >= 4) continue; if ((c[1] & mutmsk) != NOCHANGE || (c[2] & mutmsk) != NOCHANGE) { printf("%s\t%d\t", name, i+1); if (c[1] == c[2]) { // hom if ((c[1]&mutmsk) == SUBSTITUTE) { // substitution printf("%c\t%c\t-\n", "ACGTN"[c[0]], "ACGTN"[c[1]&0xf]); } else if ((c[1]&mutmsk) == DELETE) { // del printf("%c\t-\t-\n", "ACGTN"[c[0]]); } else if (((c[1] & mutmsk) >> 12) <= 5) { // ins printf("-\t"); int n = (c[1]&mutmsk) >> 12, ins = c[1] >> 4; while (n > 0) { putchar("ACGTN"[ins & 0x3]); ins >>= 2; n--; } printf("\t-\n"); } else assert(0); } else { // het if ((c[1]&mutmsk) == SUBSTITUTE || (c[2]&mutmsk) == SUBSTITUTE) { // substitution printf("%c\t%c\t+\n", "ACGTN"[c[0]], "XACMGRSVTWYHKDBN"[1<<(c[1]&0x3)|1<<(c[2]&0x3)]); } else if ((c[1]&mutmsk) == DELETE) { printf("%c\t-\t+\n", "ACGTN"[c[0]]); } else if ((c[2]&mutmsk) == DELETE) { printf("%c\t-\t+\n", "ACGTN"[c[0]]); } else if (((c[1] & mutmsk) >> 12) <= 4) { // ins1 printf("-\t"); int n = (c[1]&mutmsk) >> 12, ins = c[1] >> 4; while (n > 0) { putchar("ACGTN"[ins & 0x3]); ins >>= 2; n--; } printf("\t+\n"); } else if (((c[2] & mutmsk) >> 12) <= 5) { // ins2 printf("-\t"); int n = (c[2]&mutmsk) >> 12, ins = c[2] >> 4; while (n > 0) { putchar("ACGTN"[ins & 0x3]); ins >>= 2; n--; } printf("\t+\n"); } else assert(0); } } } } void wgsim_core(FILE *fpout1, FILE *fpout2, const char *fn, int is_hap, uint64_t N, int dist, int std_dev, int size_l, int size_r) { kseq_t *ks; mutseq_t rseq[2]; gzFile fp_fa; uint64_t tot_len, ii; int i, l, n_ref; char *qstr; int size[2], Q, max_size; uint8_t *tmp_seq[2]; mut_t *target; l = size_l > size_r? size_l : size_r; qstr = (char*)calloc(l+1, 1); tmp_seq[0] = (uint8_t*)calloc(l+2, 1); tmp_seq[1] = (uint8_t*)calloc(l+2, 1); size[0] = size_l; size[1] = size_r; max_size = size_l > size_r? size_l : size_r; Q = (ERR_RATE == 0.0)? 'I' : (int)(-10.0 * log(ERR_RATE) / log(10.0) + 0.499) + 33; fp_fa = gzopen(fn, "r"); ks = kseq_init(fp_fa); tot_len = n_ref = 0; fprintf(stderr, "[%s] calculating the total length of the reference sequence...\n", __func__); while ((l = kseq_read(ks)) >= 0) { tot_len += l; ++n_ref; } fprintf(stderr, "[%s] %d sequences, total length: %llu\n", __func__, n_ref, (long long)tot_len); kseq_destroy(ks); gzclose(fp_fa); fp_fa = gzopen(fn, "r"); ks = kseq_init(fp_fa); while ((l = kseq_read(ks)) >= 0) { uint64_t n_pairs = (uint64_t)((long double)l / tot_len * N + 0.5); if (l < dist + 3 * std_dev) { fprintf(stderr, "[%s] skip sequence '%s' as it is shorter than %d!\n", __func__, ks->name.s, dist + 3 * std_dev); continue; } // generate mutations and print them out wgsim_mut_diref(ks, is_hap, rseq, rseq+1); wgsim_print_mutref(ks->name.s, ks, rseq, rseq+1); for (ii = 0; ii != n_pairs; ++ii) { // the core loop double ran; int d, pos, s[2], is_flip = 0; int n_sub[2], n_indel[2], n_err[2], ext_coor[2], j, k; FILE *fpo[2]; do { // avoid boundary failure ran = ran_normal(); ran = ran * std_dev + dist; d = (int)(ran + 0.5); d = d > max_size? d : max_size; pos = (int)((l - d + 1) * drand48()); } while (pos < 0 || pos >= ks->seq.l || pos + d - 1 >= ks->seq.l); // flip or not if (drand48() < 0.5) { fpo[0] = fpout1; fpo[1] = fpout2; s[0] = size[0]; s[1] = size[1]; } else { fpo[1] = fpout1; fpo[0] = fpout2; s[1] = size[0]; s[0] = size[1]; is_flip = 1; } // generate the read sequences target = rseq[drand48()<0.5?0:1].s; // haplotype from which the reads are generated n_sub[0] = n_sub[1] = n_indel[0] = n_indel[1] = n_err[0] = n_err[1] = 0; #define __gen_read(x, start, iter) do { \ for (i = (start), k = 0, ext_coor[x] = -10; i >= 0 && i < ks->seq.l && k < s[x]; iter) { \ int c = target[i], mut_type = c & mutmsk; \ if (ext_coor[x] < 0) { \ if (mut_type != NOCHANGE && mut_type != SUBSTITUTE) continue; \ ext_coor[x] = i; \ } \ if (mut_type == DELETE) ++n_indel[x]; \ else if (mut_type == NOCHANGE || mut_type == SUBSTITUTE) { \ tmp_seq[x][k++] = c & 0xf; \ if (mut_type == SUBSTITUTE) ++n_sub[x]; \ } else { \ int n, ins; \ ++n_indel[x]; \ tmp_seq[x][k++] = c & 0xf; \ for (n = mut_type>>12, ins = c>>4; n > 0 && k < s[x]; --n, ins >>= 2) \ tmp_seq[x][k++] = ins & 0x3; \ } \ } \ if (k != s[x]) ext_coor[x] = -10; \ } while (0) __gen_read(0, pos, ++i); __gen_read(1, pos + d - 1, --i); for (k = 0; k < s[1]; ++k) tmp_seq[1][k] = tmp_seq[1][k] < 4? 3 - tmp_seq[1][k] : 4; // complement if (ext_coor[0] < 0 || ext_coor[1] < 0) { // fail to generate the read(s) --ii; continue; } // generate sequencing errors for (j = 0; j < 2; ++j) { int n_n = 0; for (i = 0; i < s[j]; ++i) { int c = tmp_seq[j][i]; if (c >= 4) { // actually c should be never larger than 4 if everything is correct c = 4; ++n_n; } else if (drand48() < ERR_RATE) { // c = (c + (int)(drand48() * 3.0 + 1)) & 3; // random sequencing errors c = (c + 1) & 3; // recurrent sequencing errors ++n_err[j]; } tmp_seq[j][i] = c; } if ((double)n_n / s[j] > MAX_N_RATIO) break; } if (j < 2) { // too many ambiguous bases on one of the reads --ii; continue; } // print for (j = 0; j < 2; ++j) { for (i = 0; i < s[j]; ++i) qstr[i] = Q; qstr[i] = 0; fprintf(fpo[j], "@%s_%u_%u_%d:%d:%d_%d:%d:%d_%llx/%d\n", ks->name.s, ext_coor[0]+1, ext_coor[1]+1, n_err[0], n_sub[0], n_indel[0], n_err[1], n_sub[1], n_indel[1], (long long)ii, j==0? is_flip+1 : 2-is_flip); for (i = 0; i < s[j]; ++i) fputc("ACGTN"[(int)tmp_seq[j][i]], fpo[j]); fprintf(fpo[j], "\n+\n%s\n", qstr); } } free(rseq[0].s); free(rseq[1].s); } kseq_destroy(ks); gzclose(fp_fa); free(qstr); free(tmp_seq[0]); free(tmp_seq[1]); } static int simu_usage() { fprintf(stderr, "\n"); fprintf(stderr, "Program: wgsim (short read simulator)\n"); fprintf(stderr, "Version: %s\n", PACKAGE_VERSION); fprintf(stderr, "Contact: Heng Li <lh3@sanger.ac.uk>\n\n"); fprintf(stderr, "Usage: wgsim [options] <in.ref.fa> <out.read1.fq> <out.read2.fq>\n\n"); fprintf(stderr, "Options: -e FLOAT base error rate [%.3f]\n", ERR_RATE); fprintf(stderr, " -d INT outer distance between the two ends [500]\n"); fprintf(stderr, " -s INT standard deviation [50]\n"); fprintf(stderr, " -N INT number of read pairs [1000000]\n"); fprintf(stderr, " -1 INT length of the first read [70]\n"); fprintf(stderr, " -2 INT length of the second read [70]\n"); fprintf(stderr, " -r FLOAT rate of mutations [%.4f]\n", MUT_RATE); fprintf(stderr, " -R FLOAT fraction of indels [%.2f]\n", INDEL_FRAC); fprintf(stderr, " -X FLOAT probability an indel is extended [%.2f]\n", INDEL_EXTEND); fprintf(stderr, " -S INT seed for random generator [-1]\n"); fprintf(stderr, " -h haplotype mode\n"); fprintf(stderr, "\n"); return 1; } int main(int argc, char *argv[]) { int64_t N; int dist, std_dev, c, size_l, size_r, is_hap = 0; FILE *fpout1, *fpout2; int seed = -1; N = 1000000; dist = 500; std_dev = 50; size_l = size_r = 70; while ((c = getopt(argc, argv, "e:d:s:N:1:2:r:R:hX:S:")) >= 0) { switch (c) { case 'd': dist = atoi(optarg); break; case 's': std_dev = atoi(optarg); break; case 'N': N = atoi(optarg); break; case '1': size_l = atoi(optarg); break; case '2': size_r = atoi(optarg); break; case 'e': ERR_RATE = atof(optarg); break; case 'r': MUT_RATE = atof(optarg); break; case 'R': INDEL_FRAC = atof(optarg); break; case 'X': INDEL_EXTEND = atof(optarg); break; case 'S': seed = atoi(optarg); break; case 'h': is_hap = 1; break; } } if (argc - optind < 3) return simu_usage(); fpout1 = fopen(argv[optind+1], "w"); fpout2 = fopen(argv[optind+2], "w"); if (!fpout1 || !fpout2) { fprintf(stderr, "[wgsim] file open error\n"); return 1; } srand48(seed > 0? seed : time(0)); wgsim_core(fpout1, fpout2, argv[optind], is_hap, N, dist, std_dev, size_l, size_r); fclose(fpout1); fclose(fpout2); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/misc/bamcheck.c
.c
59,193
1,522
/* Author: petr.danecek@sanger gcc -Wall -Winline -g -O2 -I ~/git/samtools bamcheck.c -o bamcheck -lm -lz -L ~/git/samtools -lbam -lpthread Assumptions, approximations and other issues: - GC-depth graph does not split reads, the starting position determines which bin is incremented. There are small overlaps between bins (max readlen-1). However, the bins are big (20k). - coverage distribution ignores softclips and deletions - some stats require sorted BAMs - GC content graph can have an untidy, step-like pattern when BAM contains multiple read lengths. - 'bases mapped' (stats->nbases_mapped) is calculated from read lengths given by BAM (core.l_qseq) - With the -t option, the whole reads are used. Except for the number of mapped bases (cigar) counts, no splicing is done, no indels or soft clips are considered, even small overlap is good enough to include the read in the stats. */ #define BAMCHECK_VERSION "2012-09-04" #define _ISOC99_SOURCE #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <math.h> #include <ctype.h> #include <getopt.h> #include <errno.h> #include <assert.h> #include "faidx.h" #include "khash.h" #include "sam.h" #include "sam_header.h" #include "razf.h" #define BWA_MIN_RDLEN 35 #define IS_PAIRED(bam) ((bam)->core.flag&BAM_FPAIRED && !((bam)->core.flag&BAM_FUNMAP) && !((bam)->core.flag&BAM_FMUNMAP)) #define IS_UNMAPPED(bam) ((bam)->core.flag&BAM_FUNMAP) #define IS_REVERSE(bam) ((bam)->core.flag&BAM_FREVERSE) #define IS_MATE_REVERSE(bam) ((bam)->core.flag&BAM_FMREVERSE) #define IS_READ1(bam) ((bam)->core.flag&BAM_FREAD1) #define IS_READ2(bam) ((bam)->core.flag&BAM_FREAD2) #define IS_DUP(bam) ((bam)->core.flag&BAM_FDUP) typedef struct { int32_t line_len, line_blen; int64_t len; uint64_t offset; } faidx1_t; KHASH_MAP_INIT_STR(kh_faidx, faidx1_t) KHASH_MAP_INIT_STR(kh_bam_tid, int) KHASH_MAP_INIT_STR(kh_rg, const char *) struct __faidx_t { RAZF *rz; int n, m; char **name; khash_t(kh_faidx) *hash; }; typedef struct { float gc; uint32_t depth; } gc_depth_t; // For coverage distribution, a simple pileup typedef struct { int64_t pos; int size, start; int *buffer; } round_buffer_t; typedef struct { uint32_t from, to; } pos_t; typedef struct { int npos,mpos,cpos; pos_t *pos; } regions_t; typedef struct { // Parameters int trim_qual; // bwa trim quality // Dimensions of the quality histogram holder (quals_1st,quals_2nd), GC content holder (gc_1st,gc_2nd), // insert size histogram holder int nquals; // The number of quality bins int nbases; // The maximum sequence length the allocated array can hold int nisize; // The maximum insert size that the allocated array can hold int ngc; // The size of gc_1st and gc_2nd int nindels; // The maximum indel length for indel distribution // Arrays for the histogram data uint64_t *quals_1st, *quals_2nd; uint64_t *gc_1st, *gc_2nd; uint64_t *isize_inward, *isize_outward, *isize_other; uint64_t *acgt_cycles; uint64_t *read_lengths; uint64_t *insertions, *deletions; uint64_t *ins_cycles_1st, *ins_cycles_2nd, *del_cycles_1st, *del_cycles_2nd; // The extremes encountered int max_len; // Maximum read length int max_qual; // Maximum quality float isize_main_bulk; // There are always some unrealistically big insert sizes, report only the main part int is_sorted; // Summary numbers uint64_t total_len; uint64_t total_len_dup; uint64_t nreads_1st; uint64_t nreads_2nd; uint64_t nreads_filtered; uint64_t nreads_dup; uint64_t nreads_unmapped; uint64_t nreads_unpaired; uint64_t nreads_paired; uint64_t nreads_anomalous; uint64_t nreads_mq0; uint64_t nbases_mapped; uint64_t nbases_mapped_cigar; uint64_t nbases_trimmed; // bwa trimmed bases uint64_t nmismatches; uint64_t nreads_QCfailed, nreads_secondary; // GC-depth related data uint32_t ngcd, igcd; // The maximum number of GC depth bins and index of the current bin gc_depth_t *gcd; // The GC-depth bins holder int gcd_bin_size; // The size of GC-depth bin uint32_t gcd_ref_size; // The approximate size of the genome int32_t tid, gcd_pos; // Position of the current bin int32_t pos; // Position of the last read // Coverage distribution related data int ncov; // The number of coverage bins uint64_t *cov; // The coverage frequencies int cov_min,cov_max,cov_step; // Minimum, maximum coverage and size of the coverage bins round_buffer_t cov_rbuf; // Pileup round buffer // Mismatches by read cycle uint8_t *rseq_buf; // A buffer for reference sequence to check the mismatches against int mrseq_buf; // The size of the buffer int32_t rseq_pos; // The coordinate of the first base in the buffer int32_t nrseq_buf; // The used part of the buffer uint64_t *mpc_buf; // Mismatches per cycle // Filters int filter_readlen; // Target regions int nregions, reg_from,reg_to; regions_t *regions; // Auxiliary data int flag_require, flag_filter; double sum_qual; // For calculating average quality value samfile_t *sam; khash_t(kh_rg) *rg_hash; // Read groups to include, the array is null-terminated faidx_t *fai; // Reference sequence for GC-depth graph int argc; // Command line arguments to be printed on the output char **argv; } stats_t; void error(const char *format, ...); void bam_init_header_hash(bam_header_t *header); int is_in_regions(bam1_t *bam_line, stats_t *stats); // Coverage distribution methods inline int coverage_idx(int min, int max, int n, int step, int depth) { if ( depth < min ) return 0; if ( depth > max ) return n-1; return 1 + (depth - min) / step; } inline int round_buffer_lidx2ridx(int offset, int size, int64_t refpos, int64_t pos) { return (offset + (pos-refpos) % size) % size; } void round_buffer_flush(stats_t *stats, int64_t pos) { int ibuf,idp; if ( pos==stats->cov_rbuf.pos ) return; int64_t new_pos = pos; if ( pos==-1 || pos - stats->cov_rbuf.pos >= stats->cov_rbuf.size ) { // Flush the whole buffer, but in sequential order, pos = stats->cov_rbuf.pos + stats->cov_rbuf.size - 1; } if ( pos < stats->cov_rbuf.pos ) error("Expected coordinates in ascending order, got %ld after %ld\n", pos,stats->cov_rbuf.pos); int ifrom = stats->cov_rbuf.start; int ito = round_buffer_lidx2ridx(stats->cov_rbuf.start,stats->cov_rbuf.size,stats->cov_rbuf.pos,pos-1); if ( ifrom>ito ) { for (ibuf=ifrom; ibuf<stats->cov_rbuf.size; ibuf++) { if ( !stats->cov_rbuf.buffer[ibuf] ) continue; idp = coverage_idx(stats->cov_min,stats->cov_max,stats->ncov,stats->cov_step,stats->cov_rbuf.buffer[ibuf]); stats->cov[idp]++; stats->cov_rbuf.buffer[ibuf] = 0; } ifrom = 0; } for (ibuf=ifrom; ibuf<=ito; ibuf++) { if ( !stats->cov_rbuf.buffer[ibuf] ) continue; idp = coverage_idx(stats->cov_min,stats->cov_max,stats->ncov,stats->cov_step,stats->cov_rbuf.buffer[ibuf]); stats->cov[idp]++; stats->cov_rbuf.buffer[ibuf] = 0; } stats->cov_rbuf.start = (new_pos==-1) ? 0 : round_buffer_lidx2ridx(stats->cov_rbuf.start,stats->cov_rbuf.size,stats->cov_rbuf.pos,pos); stats->cov_rbuf.pos = new_pos; } void round_buffer_insert_read(round_buffer_t *rbuf, int64_t from, int64_t to) { if ( to-from >= rbuf->size ) error("The read length too big (%d), please increase the buffer length (currently %d)\n", to-from+1,rbuf->size); if ( from < rbuf->pos ) error("The reads are not sorted (%ld comes after %ld).\n", from,rbuf->pos); int ifrom,ito,ibuf; ifrom = round_buffer_lidx2ridx(rbuf->start,rbuf->size,rbuf->pos,from); ito = round_buffer_lidx2ridx(rbuf->start,rbuf->size,rbuf->pos,to); if ( ifrom>ito ) { for (ibuf=ifrom; ibuf<rbuf->size; ibuf++) rbuf->buffer[ibuf]++; ifrom = 0; } for (ibuf=ifrom; ibuf<=ito; ibuf++) rbuf->buffer[ibuf]++; } // Calculate the number of bases in the read trimmed by BWA int bwa_trim_read(int trim_qual, uint8_t *quals, int len, int reverse) { if ( len<BWA_MIN_RDLEN ) return 0; // Although the name implies that the read cannot be trimmed to more than BWA_MIN_RDLEN, // the calculation can in fact trim it to (BWA_MIN_RDLEN-1). (bwa_trim_read in bwa/bwaseqio.c). int max_trimmed = len - BWA_MIN_RDLEN + 1; int l, sum=0, max_sum=0, max_l=0; for (l=0; l<max_trimmed; l++) { sum += trim_qual - quals[ reverse ? l : len-1-l ]; if ( sum<0 ) break; if ( sum>max_sum ) { max_sum = sum; // This is the correct way, but bwa clips from some reason one base less // max_l = l+1; max_l = l; } } return max_l; } void count_indels(stats_t *stats,bam1_t *bam_line) { int is_fwd = IS_REVERSE(bam_line) ? 0 : 1; int is_1st = IS_READ1(bam_line) ? 1 : 0; int icig; int icycle = 0; int read_len = bam_line->core.l_qseq; for (icig=0; icig<bam_line->core.n_cigar; icig++) { // Conversion from uint32_t to MIDNSHP // 0123456 // MIDNSHP int cig = bam1_cigar(bam_line)[icig] & BAM_CIGAR_MASK; int ncig = bam1_cigar(bam_line)[icig] >> BAM_CIGAR_SHIFT; if ( cig==1 ) { int idx = is_fwd ? icycle : read_len-icycle-ncig; if ( idx<0 ) error("FIXME: read_len=%d vs icycle=%d\n", read_len,icycle); if ( idx >= stats->nbases || idx<0 ) error("FIXME: %d vs %d, %s:%d %s\n", idx,stats->nbases, stats->sam->header->target_name[bam_line->core.tid],bam_line->core.pos+1,bam1_qname(bam_line)); if ( is_1st ) stats->ins_cycles_1st[idx]++; else stats->ins_cycles_2nd[idx]++; icycle += ncig; if ( ncig<=stats->nindels ) stats->insertions[ncig-1]++; continue; } if ( cig==2 ) { int idx = is_fwd ? icycle-1 : read_len-icycle-1; if ( idx<0 ) continue; // discard meaningless deletions if ( idx >= stats->nbases ) error("FIXME: %d vs %d\n", idx,stats->nbases); if ( is_1st ) stats->del_cycles_1st[idx]++; else stats->del_cycles_2nd[idx]++; if ( ncig<=stats->nindels ) stats->deletions[ncig-1]++; continue; } if ( cig!=3 && cig!=5 ) icycle += ncig; } } void count_mismatches_per_cycle(stats_t *stats,bam1_t *bam_line) { int is_fwd = IS_REVERSE(bam_line) ? 0 : 1; int icig,iread=0,icycle=0; int iref = bam_line->core.pos - stats->rseq_pos; int read_len = bam_line->core.l_qseq; uint8_t *read = bam1_seq(bam_line); uint8_t *quals = bam1_qual(bam_line); uint64_t *mpc_buf = stats->mpc_buf; for (icig=0; icig<bam_line->core.n_cigar; icig++) { // Conversion from uint32_t to MIDNSHP // 0123456 // MIDNSHP int cig = bam1_cigar(bam_line)[icig] & BAM_CIGAR_MASK; int ncig = bam1_cigar(bam_line)[icig] >> BAM_CIGAR_SHIFT; if ( cig==1 ) { iread += ncig; icycle += ncig; continue; } if ( cig==2 ) { iref += ncig; continue; } if ( cig==4 ) { icycle += ncig; // Soft-clips are present in the sequence, but the position of the read marks a start of non-clipped sequence // iref += ncig; iread += ncig; continue; } if ( cig==5 ) { icycle += ncig; continue; } // Ignore H and N CIGARs. The letter are inserted e.g. by TopHat and often require very large // chunk of refseq in memory. Not very frequent and not noticable in the stats. if ( cig==3 || cig==5 ) continue; if ( cig!=0 ) error("TODO: cigar %d, %s:%d %s\n", cig,stats->sam->header->target_name[bam_line->core.tid],bam_line->core.pos+1,bam1_qname(bam_line)); if ( ncig+iref > stats->nrseq_buf ) error("FIXME: %d+%d > %d, %s, %s:%d\n",ncig,iref,stats->nrseq_buf, bam1_qname(bam_line),stats->sam->header->target_name[bam_line->core.tid],bam_line->core.pos+1); int im; for (im=0; im<ncig; im++) { uint8_t cread = bam1_seqi(read,iread); uint8_t cref = stats->rseq_buf[iref]; // ---------------15 // =ACMGRSVTWYHKDBN if ( cread==15 ) { int idx = is_fwd ? icycle : read_len-icycle-1; if ( idx>stats->max_len ) error("mpc: %d>%d\n",idx,stats->max_len); idx = idx*stats->nquals; if ( idx>=stats->nquals*stats->nbases ) error("FIXME: mpc_buf overflow\n"); mpc_buf[idx]++; } else if ( cref && cread && cref!=cread ) { uint8_t qual = quals[iread] + 1; if ( qual>=stats->nquals ) error("TODO: quality too high %d>=%d (%s %d %s)\n", qual,stats->nquals, stats->sam->header->target_name[bam_line->core.tid],bam_line->core.pos+1,bam1_qname(bam_line)); int idx = is_fwd ? icycle : read_len-icycle-1; if ( idx>stats->max_len ) error("mpc: %d>%d\n",idx,stats->max_len); idx = idx*stats->nquals + qual; if ( idx>=stats->nquals*stats->nbases ) error("FIXME: mpc_buf overflow\n"); mpc_buf[idx]++; } iref++; iread++; icycle++; } } } void read_ref_seq(stats_t *stats,int32_t tid,int32_t pos) { khash_t(kh_faidx) *h; khiter_t iter; faidx1_t val; char *chr, c; faidx_t *fai = stats->fai; h = fai->hash; chr = stats->sam->header->target_name[tid]; // ID of the sequence name iter = kh_get(kh_faidx, h, chr); if (iter == kh_end(h)) error("No such reference sequence [%s]?\n", chr); val = kh_value(h, iter); // Check the boundaries if (pos >= val.len) error("Was the bam file mapped with the reference sequence supplied?" " A read mapped beyond the end of the chromosome (%s:%d, chromosome length %d).\n", chr,pos,val.len); int size = stats->mrseq_buf; // The buffer extends beyond the chromosome end. Later the rest will be filled with N's. if (size+pos > val.len) size = val.len-pos; // Position the razf reader razf_seek(fai->rz, val.offset + pos / val.line_blen * val.line_len + pos % val.line_blen, SEEK_SET); uint8_t *ptr = stats->rseq_buf; int nread = 0; while ( nread<size && razf_read(fai->rz,&c,1) && !fai->rz->z_err ) { if ( !isgraph(c) ) continue; // Conversion between uint8_t coding and ACGT // -12-4---8------- // =ACMGRSVTWYHKDBN if ( c=='A' || c=='a' ) *ptr = 1; else if ( c=='C' || c=='c' ) *ptr = 2; else if ( c=='G' || c=='g' ) *ptr = 4; else if ( c=='T' || c=='t' ) *ptr = 8; else *ptr = 0; ptr++; nread++; } if ( nread < stats->mrseq_buf ) { memset(ptr,0, stats->mrseq_buf - nread); nread = stats->mrseq_buf; } stats->nrseq_buf = nread; stats->rseq_pos = pos; stats->tid = tid; } float fai_gc_content(stats_t *stats, int pos, int len) { uint32_t gc,count,c; int i = pos - stats->rseq_pos, ito = i + len; assert( i>=0 && ito<=stats->nrseq_buf ); // Count GC content gc = count = 0; for (; i<ito; i++) { c = stats->rseq_buf[i]; if ( c==2 || c==4 ) { gc++; count++; } else if ( c==1 || c==8 ) count++; } return count ? (float)gc/count : 0; } void realloc_rseq_buffer(stats_t *stats) { int n = stats->nbases*10; if ( stats->gcd_bin_size > n ) n = stats->gcd_bin_size; if ( stats->mrseq_buf<n ) { stats->rseq_buf = realloc(stats->rseq_buf,sizeof(uint8_t)*n); stats->mrseq_buf = n; } } void realloc_gcd_buffer(stats_t *stats, int seq_len) { if ( seq_len >= stats->gcd_bin_size ) error("The --GC-depth bin size (%d) is set too low for the read length %d\n", stats->gcd_bin_size, seq_len); int n = 1 + stats->gcd_ref_size / (stats->gcd_bin_size - seq_len); if ( n <= stats->igcd ) error("The --GC-depth bin size is too small or reference genome too big; please decrease the bin size or increase the reference length\n"); if ( n > stats->ngcd ) { stats->gcd = realloc(stats->gcd, n*sizeof(gc_depth_t)); if ( !stats->gcd ) error("Could not realloc GCD buffer, too many chromosomes or the genome too long?? [%u %u]\n", stats->ngcd,n); memset(&(stats->gcd[stats->ngcd]),0,(n-stats->ngcd)*sizeof(gc_depth_t)); stats->ngcd = n; } realloc_rseq_buffer(stats); } void realloc_buffers(stats_t *stats, int seq_len) { int n = 2*(1 + seq_len - stats->nbases) + stats->nbases; stats->quals_1st = realloc(stats->quals_1st, n*stats->nquals*sizeof(uint64_t)); if ( !stats->quals_1st ) error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*stats->nquals*sizeof(uint64_t)); memset(stats->quals_1st + stats->nbases*stats->nquals, 0, (n-stats->nbases)*stats->nquals*sizeof(uint64_t)); stats->quals_2nd = realloc(stats->quals_2nd, n*stats->nquals*sizeof(uint64_t)); if ( !stats->quals_2nd ) error("Could not realloc buffers, the sequence too long: %d (2x%ld)\n", seq_len,n*stats->nquals*sizeof(uint64_t)); memset(stats->quals_2nd + stats->nbases*stats->nquals, 0, (n-stats->nbases)*stats->nquals*sizeof(uint64_t)); if ( stats->mpc_buf ) { stats->mpc_buf = realloc(stats->mpc_buf, n*stats->nquals*sizeof(uint64_t)); if ( !stats->mpc_buf ) error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*stats->nquals*sizeof(uint64_t)); memset(stats->mpc_buf + stats->nbases*stats->nquals, 0, (n-stats->nbases)*stats->nquals*sizeof(uint64_t)); } stats->acgt_cycles = realloc(stats->acgt_cycles, n*4*sizeof(uint64_t)); if ( !stats->acgt_cycles ) error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*4*sizeof(uint64_t)); memset(stats->acgt_cycles + stats->nbases*4, 0, (n-stats->nbases)*4*sizeof(uint64_t)); stats->read_lengths = realloc(stats->read_lengths, n*sizeof(uint64_t)); if ( !stats->read_lengths ) error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t)); memset(stats->read_lengths + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t)); stats->insertions = realloc(stats->insertions, n*sizeof(uint64_t)); if ( !stats->insertions ) error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t)); memset(stats->insertions + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t)); stats->deletions = realloc(stats->deletions, n*sizeof(uint64_t)); if ( !stats->deletions ) error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t)); memset(stats->deletions + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t)); stats->ins_cycles_1st = realloc(stats->ins_cycles_1st, (n+1)*sizeof(uint64_t)); if ( !stats->ins_cycles_1st ) error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,(n+1)*sizeof(uint64_t)); memset(stats->ins_cycles_1st + stats->nbases + 1, 0, (n-stats->nbases)*sizeof(uint64_t)); stats->ins_cycles_2nd = realloc(stats->ins_cycles_2nd, (n+1)*sizeof(uint64_t)); if ( !stats->ins_cycles_2nd ) error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,(n+1)*sizeof(uint64_t)); memset(stats->ins_cycles_2nd + stats->nbases + 1, 0, (n-stats->nbases)*sizeof(uint64_t)); stats->del_cycles_1st = realloc(stats->del_cycles_1st, (n+1)*sizeof(uint64_t)); if ( !stats->del_cycles_1st ) error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,(n+1)*sizeof(uint64_t)); memset(stats->del_cycles_1st + stats->nbases + 1, 0, (n-stats->nbases)*sizeof(uint64_t)); stats->del_cycles_2nd = realloc(stats->del_cycles_2nd, (n+1)*sizeof(uint64_t)); if ( !stats->del_cycles_2nd ) error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,(n+1)*sizeof(uint64_t)); memset(stats->del_cycles_2nd + stats->nbases + 1, 0, (n-stats->nbases)*sizeof(uint64_t)); stats->nbases = n; // Realloc the coverage distribution buffer int *rbuffer = calloc(sizeof(int),seq_len*5); n = stats->cov_rbuf.size-stats->cov_rbuf.start; memcpy(rbuffer,stats->cov_rbuf.buffer+stats->cov_rbuf.start,n); if ( stats->cov_rbuf.start>1 ) memcpy(rbuffer+n,stats->cov_rbuf.buffer,stats->cov_rbuf.start); stats->cov_rbuf.start = 0; free(stats->cov_rbuf.buffer); stats->cov_rbuf.buffer = rbuffer; stats->cov_rbuf.size = seq_len*5; realloc_rseq_buffer(stats); } void collect_stats(bam1_t *bam_line, stats_t *stats) { if ( stats->rg_hash ) { const uint8_t *rg = bam_aux_get(bam_line, "RG"); if ( !rg ) return; khiter_t k = kh_get(kh_rg, stats->rg_hash, (const char*)(rg + 1)); if ( k == kh_end(stats->rg_hash) ) return; } if ( stats->flag_require && (bam_line->core.flag & stats->flag_require)!=stats->flag_require ) { stats->nreads_filtered++; return; } if ( stats->flag_filter && (bam_line->core.flag & stats->flag_filter) ) { stats->nreads_filtered++; return; } if ( !is_in_regions(bam_line,stats) ) return; if ( stats->filter_readlen!=-1 && bam_line->core.l_qseq!=stats->filter_readlen ) return; if ( bam_line->core.flag & BAM_FQCFAIL ) stats->nreads_QCfailed++; if ( bam_line->core.flag & BAM_FSECONDARY ) stats->nreads_secondary++; int seq_len = bam_line->core.l_qseq; if ( !seq_len ) return; if ( seq_len >= stats->nbases ) realloc_buffers(stats,seq_len); if ( stats->max_len<seq_len ) stats->max_len = seq_len; stats->read_lengths[seq_len]++; // Count GC and ACGT per cycle uint8_t base, *seq = bam1_seq(bam_line); int gc_count = 0; int i; int reverse = IS_REVERSE(bam_line); for (i=0; i<seq_len; i++) { // Conversion from uint8_t coding to ACGT // -12-4---8------- // =ACMGRSVTWYHKDBN // 01 2 3 base = bam1_seqi(seq,i); base /= 2; if ( base==1 || base==2 ) gc_count++; else if ( base>2 ) base=3; if ( 4*(reverse ? seq_len-i-1 : i) + base >= stats->nbases*4 ) error("FIXME: acgt_cycles\n"); stats->acgt_cycles[ 4*(reverse ? seq_len-i-1 : i) + base ]++; } int gc_idx_min = gc_count*(stats->ngc-1)/seq_len; int gc_idx_max = (gc_count+1)*(stats->ngc-1)/seq_len; if ( gc_idx_max >= stats->ngc ) gc_idx_max = stats->ngc - 1; // Determine which array (1st or 2nd read) will these stats go to, // trim low quality bases from end the same way BWA does, // fill GC histogram uint64_t *quals; uint8_t *bam_quals = bam1_qual(bam_line); if ( bam_line->core.flag&BAM_FREAD2 ) { quals = stats->quals_2nd; stats->nreads_2nd++; for (i=gc_idx_min; i<gc_idx_max; i++) stats->gc_2nd[i]++; } else { quals = stats->quals_1st; stats->nreads_1st++; for (i=gc_idx_min; i<gc_idx_max; i++) stats->gc_1st[i]++; } if ( stats->trim_qual>0 ) stats->nbases_trimmed += bwa_trim_read(stats->trim_qual, bam_quals, seq_len, reverse); // Quality histogram and average quality for (i=0; i<seq_len; i++) { uint8_t qual = bam_quals[ reverse ? seq_len-i-1 : i]; if ( qual>=stats->nquals ) error("TODO: quality too high %d>=%d (%s %d %s)\n", qual,stats->nquals,stats->sam->header->target_name[bam_line->core.tid],bam_line->core.pos+1,bam1_qname(bam_line)); if ( qual>stats->max_qual ) stats->max_qual = qual; quals[ i*stats->nquals+qual ]++; stats->sum_qual += qual; } // Look at the flags and increment appropriate counters (mapped, paired, etc) if ( IS_UNMAPPED(bam_line) ) stats->nreads_unmapped++; else { if ( !bam_line->core.qual ) stats->nreads_mq0++; count_indels(stats,bam_line); if ( !IS_PAIRED(bam_line) ) stats->nreads_unpaired++; else { stats->nreads_paired++; if ( bam_line->core.tid!=bam_line->core.mtid ) stats->nreads_anomalous++; // The insert size is tricky, because for long inserts the libraries are // prepared differently and the pairs point in other direction. BWA does // not set the paired flag for them. Similar thing is true also for 454 // reads. Mates mapped to different chromosomes have isize==0. int32_t isize = bam_line->core.isize; if ( isize<0 ) isize = -isize; if ( isize >= stats->nisize ) isize = stats->nisize-1; if ( isize>0 || bam_line->core.tid==bam_line->core.mtid ) { int pos_fst = bam_line->core.mpos - bam_line->core.pos; int is_fst = IS_READ1(bam_line) ? 1 : -1; int is_fwd = IS_REVERSE(bam_line) ? -1 : 1; int is_mfwd = IS_MATE_REVERSE(bam_line) ? -1 : 1; if ( is_fwd*is_mfwd>0 ) stats->isize_other[isize]++; else if ( is_fst*pos_fst>0 ) { if ( is_fst*is_fwd>0 ) stats->isize_inward[isize]++; else stats->isize_outward[isize]++; } else if ( is_fst*pos_fst<0 ) { if ( is_fst*is_fwd>0 ) stats->isize_outward[isize]++; else stats->isize_inward[isize]++; } } } // Number of mismatches uint8_t *nm = bam_aux_get(bam_line,"NM"); if (nm) stats->nmismatches += bam_aux2i(nm); // Number of mapped bases from cigar // Conversion from uint32_t to MIDNSHP // 012-4-- // MIDNSHP if ( bam_line->core.n_cigar == 0) error("FIXME: mapped read with no cigar?\n"); int readlen=seq_len; if ( stats->regions ) { // Count only on-target bases int iref = bam_line->core.pos + 1; for (i=0; i<bam_line->core.n_cigar; i++) { int cig = bam1_cigar(bam_line)[i]&BAM_CIGAR_MASK; int ncig = bam1_cigar(bam_line)[i]>>BAM_CIGAR_SHIFT; if ( cig==2 ) readlen += ncig; else if ( cig==0 ) { if ( iref < stats->reg_from ) ncig -= stats->reg_from-iref; else if ( iref+ncig-1 > stats->reg_to ) ncig -= iref+ncig-1 - stats->reg_to; if ( ncig<0 ) ncig = 0; stats->nbases_mapped_cigar += ncig; iref += bam1_cigar(bam_line)[i]>>BAM_CIGAR_SHIFT; } else if ( cig==1 ) { iref += ncig; if ( iref>=stats->reg_from && iref<=stats->reg_to ) stats->nbases_mapped_cigar += ncig; } } } else { // Count the whole read for (i=0; i<bam_line->core.n_cigar; i++) { if ( (bam1_cigar(bam_line)[i]&BAM_CIGAR_MASK)==0 || (bam1_cigar(bam_line)[i]&BAM_CIGAR_MASK)==1 ) stats->nbases_mapped_cigar += bam1_cigar(bam_line)[i]>>BAM_CIGAR_SHIFT; if ( (bam1_cigar(bam_line)[i]&BAM_CIGAR_MASK)==2 ) readlen += bam1_cigar(bam_line)[i]>>BAM_CIGAR_SHIFT; } } stats->nbases_mapped += seq_len; if ( stats->tid==bam_line->core.tid && bam_line->core.pos<stats->pos ) stats->is_sorted = 0; stats->pos = bam_line->core.pos; if ( stats->is_sorted ) { if ( stats->tid==-1 || stats->tid!=bam_line->core.tid ) round_buffer_flush(stats,-1); // Mismatches per cycle and GC-depth graph. For simplicity, reads overlapping GCD bins // are not splitted which results in up to seq_len-1 overlaps. The default bin size is // 20kbp, so the effect is negligible. if ( stats->fai ) { int inc_ref = 0, inc_gcd = 0; // First pass or new chromosome if ( stats->rseq_pos==-1 || stats->tid != bam_line->core.tid ) { inc_ref=1; inc_gcd=1; } // Read goes beyond the end of the rseq buffer else if ( stats->rseq_pos+stats->nrseq_buf < bam_line->core.pos+readlen ) { inc_ref=1; inc_gcd=1; } // Read overlaps the next gcd bin else if ( stats->gcd_pos+stats->gcd_bin_size < bam_line->core.pos+readlen ) { inc_gcd = 1; if ( stats->rseq_pos+stats->nrseq_buf < bam_line->core.pos+stats->gcd_bin_size ) inc_ref = 1; } if ( inc_gcd ) { stats->igcd++; if ( stats->igcd >= stats->ngcd ) realloc_gcd_buffer(stats, readlen); if ( inc_ref ) read_ref_seq(stats,bam_line->core.tid,bam_line->core.pos); stats->gcd_pos = bam_line->core.pos; stats->gcd[ stats->igcd ].gc = fai_gc_content(stats, stats->gcd_pos, stats->gcd_bin_size); } count_mismatches_per_cycle(stats,bam_line); } // No reference and first pass, new chromosome or sequence going beyond the end of the gcd bin else if ( stats->gcd_pos==-1 || stats->tid != bam_line->core.tid || bam_line->core.pos - stats->gcd_pos > stats->gcd_bin_size ) { // First pass or a new chromosome stats->tid = bam_line->core.tid; stats->gcd_pos = bam_line->core.pos; stats->igcd++; if ( stats->igcd >= stats->ngcd ) realloc_gcd_buffer(stats, readlen); } stats->gcd[ stats->igcd ].depth++; // When no reference sequence is given, approximate the GC from the read (much shorter window, but otherwise OK) if ( !stats->fai ) stats->gcd[ stats->igcd ].gc += (float) gc_count / seq_len; // Coverage distribution graph round_buffer_flush(stats,bam_line->core.pos); round_buffer_insert_read(&(stats->cov_rbuf),bam_line->core.pos,bam_line->core.pos+seq_len-1); } } stats->total_len += seq_len; if ( IS_DUP(bam_line) ) { stats->total_len_dup += seq_len; stats->nreads_dup++; } } // Sort by GC and depth #define GCD_t(x) ((gc_depth_t *)x) static int gcd_cmp(const void *a, const void *b) { if ( GCD_t(a)->gc < GCD_t(b)->gc ) return -1; if ( GCD_t(a)->gc > GCD_t(b)->gc ) return 1; if ( GCD_t(a)->depth < GCD_t(b)->depth ) return -1; if ( GCD_t(a)->depth > GCD_t(b)->depth ) return 1; return 0; } #undef GCD_t float gcd_percentile(gc_depth_t *gcd, int N, int p) { float n,d; int k; n = p*(N+1)/100; k = n; if ( k<=0 ) return gcd[0].depth; if ( k>=N ) return gcd[N-1].depth; d = n - k; return gcd[k-1].depth + d*(gcd[k].depth - gcd[k-1].depth); } void output_stats(stats_t *stats) { // Calculate average insert size and standard deviation (from the main bulk data only) int isize, ibulk=0; uint64_t nisize=0, nisize_inward=0, nisize_outward=0, nisize_other=0; for (isize=0; isize<stats->nisize; isize++) { // Each pair was counted twice stats->isize_inward[isize] *= 0.5; stats->isize_outward[isize] *= 0.5; stats->isize_other[isize] *= 0.5; nisize_inward += stats->isize_inward[isize]; nisize_outward += stats->isize_outward[isize]; nisize_other += stats->isize_other[isize]; nisize += stats->isize_inward[isize] + stats->isize_outward[isize] + stats->isize_other[isize]; } double bulk=0, avg_isize=0, sd_isize=0; for (isize=0; isize<stats->nisize; isize++) { bulk += stats->isize_inward[isize] + stats->isize_outward[isize] + stats->isize_other[isize]; avg_isize += isize * (stats->isize_inward[isize] + stats->isize_outward[isize] + stats->isize_other[isize]); if ( bulk/nisize > stats->isize_main_bulk ) { ibulk = isize+1; nisize = bulk; break; } } avg_isize /= nisize ? nisize : 1; for (isize=1; isize<ibulk; isize++) sd_isize += (stats->isize_inward[isize] + stats->isize_outward[isize] + stats->isize_other[isize]) * (isize-avg_isize)*(isize-avg_isize) / nisize; sd_isize = sqrt(sd_isize); printf("# This file was produced by bamcheck (%s)\n",BAMCHECK_VERSION); printf("# The command line was: %s",stats->argv[0]); int i; for (i=1; i<stats->argc; i++) printf(" %s",stats->argv[i]); printf("\n"); printf("# Summary Numbers. Use `grep ^SN | cut -f 2-` to extract this part.\n"); printf("SN\traw total sequences:\t%ld\n", (long)(stats->nreads_filtered+stats->nreads_1st+stats->nreads_2nd)); printf("SN\tfiltered sequences:\t%ld\n", (long)stats->nreads_filtered); printf("SN\tsequences:\t%ld\n", (long)(stats->nreads_1st+stats->nreads_2nd)); printf("SN\tis paired:\t%d\n", stats->nreads_1st&&stats->nreads_2nd ? 1 : 0); printf("SN\tis sorted:\t%d\n", stats->is_sorted ? 1 : 0); printf("SN\t1st fragments:\t%ld\n", (long)stats->nreads_1st); printf("SN\tlast fragments:\t%ld\n", (long)stats->nreads_2nd); printf("SN\treads mapped:\t%ld\n", (long)(stats->nreads_paired+stats->nreads_unpaired)); printf("SN\treads unmapped:\t%ld\n", (long)stats->nreads_unmapped); printf("SN\treads unpaired:\t%ld\n", (long)stats->nreads_unpaired); printf("SN\treads paired:\t%ld\n", (long)stats->nreads_paired); printf("SN\treads duplicated:\t%ld\n", (long)stats->nreads_dup); printf("SN\treads MQ0:\t%ld\n", (long)stats->nreads_mq0); printf("SN\treads QC failed:\t%ld\n", (long)stats->nreads_QCfailed); printf("SN\tnon-primary alignments:\t%ld\n", (long)stats->nreads_secondary); printf("SN\ttotal length:\t%ld\n", (long)stats->total_len); printf("SN\tbases mapped:\t%ld\n", (long)stats->nbases_mapped); printf("SN\tbases mapped (cigar):\t%ld\n", (long)stats->nbases_mapped_cigar); printf("SN\tbases trimmed:\t%ld\n", (long)stats->nbases_trimmed); printf("SN\tbases duplicated:\t%ld\n", (long)stats->total_len_dup); printf("SN\tmismatches:\t%ld\n", (long)stats->nmismatches); printf("SN\terror rate:\t%e\n", (float)stats->nmismatches/stats->nbases_mapped_cigar); float avg_read_length = (stats->nreads_1st+stats->nreads_2nd)?stats->total_len/(stats->nreads_1st+stats->nreads_2nd):0; printf("SN\taverage length:\t%.0f\n", avg_read_length); printf("SN\tmaximum length:\t%d\n", stats->max_len); printf("SN\taverage quality:\t%.1f\n", stats->total_len?stats->sum_qual/stats->total_len:0); printf("SN\tinsert size average:\t%.1f\n", avg_isize); printf("SN\tinsert size standard deviation:\t%.1f\n", sd_isize); printf("SN\tinward oriented pairs:\t%ld\n", (long)nisize_inward); printf("SN\toutward oriented pairs:\t%ld\n", (long)nisize_outward); printf("SN\tpairs with other orientation:\t%ld\n", (long)nisize_other); printf("SN\tpairs on different chromosomes:\t%ld\n", (long)stats->nreads_anomalous/2); int ibase,iqual; if ( stats->max_len<stats->nbases ) stats->max_len++; if ( stats->max_qual+1<stats->nquals ) stats->max_qual++; printf("# First Fragment Qualitites. Use `grep ^FFQ | cut -f 2-` to extract this part.\n"); printf("# Columns correspond to qualities and rows to cycles. First column is the cycle number.\n"); for (ibase=0; ibase<stats->max_len; ibase++) { printf("FFQ\t%d",ibase+1); for (iqual=0; iqual<=stats->max_qual; iqual++) { printf("\t%ld", (long)stats->quals_1st[ibase*stats->nquals+iqual]); } printf("\n"); } printf("# Last Fragment Qualitites. Use `grep ^LFQ | cut -f 2-` to extract this part.\n"); printf("# Columns correspond to qualities and rows to cycles. First column is the cycle number.\n"); for (ibase=0; ibase<stats->max_len; ibase++) { printf("LFQ\t%d",ibase+1); for (iqual=0; iqual<=stats->max_qual; iqual++) { printf("\t%ld", (long)stats->quals_2nd[ibase*stats->nquals+iqual]); } printf("\n"); } if ( stats->mpc_buf ) { printf("# Mismatches per cycle and quality. Use `grep ^MPC | cut -f 2-` to extract this part.\n"); printf("# Columns correspond to qualities, rows to cycles. First column is the cycle number, second\n"); printf("# is the number of N's and the rest is the number of mismatches\n"); for (ibase=0; ibase<stats->max_len; ibase++) { printf("MPC\t%d",ibase+1); for (iqual=0; iqual<=stats->max_qual; iqual++) { printf("\t%ld", (long)stats->mpc_buf[ibase*stats->nquals+iqual]); } printf("\n"); } } printf("# GC Content of first fragments. Use `grep ^GCF | cut -f 2-` to extract this part.\n"); int ibase_prev = 0; for (ibase=0; ibase<stats->ngc; ibase++) { if ( stats->gc_1st[ibase]==stats->gc_1st[ibase_prev] ) continue; printf("GCF\t%.2f\t%ld\n", (ibase+ibase_prev)*0.5*100./(stats->ngc-1), (long)stats->gc_1st[ibase_prev]); ibase_prev = ibase; } printf("# GC Content of last fragments. Use `grep ^GCL | cut -f 2-` to extract this part.\n"); ibase_prev = 0; for (ibase=0; ibase<stats->ngc; ibase++) { if ( stats->gc_2nd[ibase]==stats->gc_2nd[ibase_prev] ) continue; printf("GCL\t%.2f\t%ld\n", (ibase+ibase_prev)*0.5*100./(stats->ngc-1), (long)stats->gc_2nd[ibase_prev]); ibase_prev = ibase; } printf("# ACGT content per cycle. Use `grep ^GCC | cut -f 2-` to extract this part. The columns are: cycle, and A,C,G,T counts [%%]\n"); for (ibase=0; ibase<stats->max_len; ibase++) { uint64_t *ptr = &(stats->acgt_cycles[ibase*4]); uint64_t sum = ptr[0]+ptr[1]+ptr[2]+ptr[3]; if ( ! sum ) continue; printf("GCC\t%d\t%.2f\t%.2f\t%.2f\t%.2f\n", ibase,100.*ptr[0]/sum,100.*ptr[1]/sum,100.*ptr[2]/sum,100.*ptr[3]/sum); } printf("# Insert sizes. Use `grep ^IS | cut -f 2-` to extract this part. The columns are: pairs total, inward oriented pairs, outward oriented pairs, other pairs\n"); for (isize=0; isize<ibulk; isize++) printf("IS\t%d\t%ld\t%ld\t%ld\t%ld\n", isize, (long)(stats->isize_inward[isize]+stats->isize_outward[isize]+stats->isize_other[isize]), (long)stats->isize_inward[isize], (long)stats->isize_outward[isize], (long)stats->isize_other[isize]); printf("# Read lengths. Use `grep ^RL | cut -f 2-` to extract this part. The columns are: read length, count\n"); int ilen; for (ilen=0; ilen<stats->max_len; ilen++) { if ( stats->read_lengths[ilen]>0 ) printf("RL\t%d\t%ld\n", ilen, (long)stats->read_lengths[ilen]); } printf("# Indel distribution. Use `grep ^ID | cut -f 2-` to extract this part. The columns are: length, number of insertions, number of deletions\n"); for (ilen=0; ilen<stats->nindels; ilen++) { if ( stats->insertions[ilen]>0 || stats->deletions[ilen]>0 ) printf("ID\t%d\t%ld\t%ld\n", ilen+1, (long)stats->insertions[ilen], (long)stats->deletions[ilen]); } printf("# Indels per cycle. Use `grep ^IC | cut -f 2-` to extract this part. The columns are: cycle, number of insertions (fwd), .. (rev) , number of deletions (fwd), .. (rev)\n"); for (ilen=0; ilen<=stats->nbases; ilen++) { // For deletions we print the index of the cycle before the deleted base (1-based) and for insertions // the index of the cycle of the first inserted base (also 1-based) if ( stats->ins_cycles_1st[ilen]>0 || stats->ins_cycles_2nd[ilen]>0 || stats->del_cycles_1st[ilen]>0 || stats->del_cycles_2nd[ilen]>0 ) printf("IC\t%d\t%ld\t%ld\t%ld\t%ld\n", ilen+1, (long)stats->ins_cycles_1st[ilen], (long)stats->ins_cycles_2nd[ilen], (long)stats->del_cycles_1st[ilen], (long)stats->del_cycles_2nd[ilen]); } printf("# Coverage distribution. Use `grep ^COV | cut -f 2-` to extract this part.\n"); if ( stats->cov[0] ) printf("COV\t[<%d]\t%d\t%ld\n",stats->cov_min,stats->cov_min-1, (long)stats->cov[0]); int icov; for (icov=1; icov<stats->ncov-1; icov++) if ( stats->cov[icov] ) printf("COV\t[%d-%d]\t%d\t%ld\n",stats->cov_min + (icov-1)*stats->cov_step, stats->cov_min + icov*stats->cov_step-1,stats->cov_min + icov*stats->cov_step-1, (long)stats->cov[icov]); if ( stats->cov[stats->ncov-1] ) printf("COV\t[%d<]\t%d\t%ld\n",stats->cov_min + (stats->ncov-2)*stats->cov_step-1,stats->cov_min + (stats->ncov-2)*stats->cov_step-1, (long)stats->cov[stats->ncov-1]); // Calculate average GC content, then sort by GC and depth printf("# GC-depth. Use `grep ^GCD | cut -f 2-` to extract this part. The columns are: GC%%, unique sequence percentiles, 10th, 25th, 50th, 75th and 90th depth percentile\n"); uint32_t igcd; for (igcd=0; igcd<stats->igcd; igcd++) { if ( stats->fai ) stats->gcd[igcd].gc = round(100. * stats->gcd[igcd].gc); else if ( stats->gcd[igcd].depth ) stats->gcd[igcd].gc = round(100. * stats->gcd[igcd].gc / stats->gcd[igcd].depth); } qsort(stats->gcd, stats->igcd+1, sizeof(gc_depth_t), gcd_cmp); igcd = 0; while ( igcd < stats->igcd ) { // Calculate percentiles (10,25,50,75,90th) for the current GC content and print uint32_t nbins=0, itmp=igcd; float gc = stats->gcd[igcd].gc; while ( itmp<stats->igcd && fabs(stats->gcd[itmp].gc-gc)<0.1 ) { nbins++; itmp++; } printf("GCD\t%.1f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n", gc, (igcd+nbins+1)*100./(stats->igcd+1), gcd_percentile(&(stats->gcd[igcd]),nbins,10) *avg_read_length/stats->gcd_bin_size, gcd_percentile(&(stats->gcd[igcd]),nbins,25) *avg_read_length/stats->gcd_bin_size, gcd_percentile(&(stats->gcd[igcd]),nbins,50) *avg_read_length/stats->gcd_bin_size, gcd_percentile(&(stats->gcd[igcd]),nbins,75) *avg_read_length/stats->gcd_bin_size, gcd_percentile(&(stats->gcd[igcd]),nbins,90) *avg_read_length/stats->gcd_bin_size ); igcd += nbins; } } size_t mygetline(char **line, size_t *n, FILE *fp) { if (line == NULL || n == NULL || fp == NULL) { errno = EINVAL; return -1; } if (*n==0 || !*line) { *line = NULL; *n = 0; } size_t nread=0; int c; while ((c=getc(fp))!= EOF && c!='\n') { if ( ++nread>=*n ) { *n += 255; *line = realloc(*line, sizeof(char)*(*n)); } (*line)[nread-1] = c; } if ( nread>=*n ) { *n += 255; *line = realloc(*line, sizeof(char)*(*n)); } (*line)[nread] = 0; return nread>0 ? nread : -1; } void init_regions(stats_t *stats, char *file) { khiter_t iter; khash_t(kh_bam_tid) *header_hash; bam_init_header_hash(stats->sam->header); header_hash = (khash_t(kh_bam_tid)*)stats->sam->header->hash; FILE *fp = fopen(file,"r"); if ( !fp ) error("%s: %s\n",file,strerror(errno)); char *line = NULL; size_t len = 0; ssize_t nread; int warned = 0; int prev_tid=-1, prev_pos=-1; while ((nread = mygetline(&line, &len, fp)) != -1) { if ( line[0] == '#' ) continue; int i = 0; while ( i<nread && !isspace(line[i]) ) i++; if ( i>=nread ) error("Could not parse the file: %s [%s]\n", file,line); line[i] = 0; iter = kh_get(kh_bam_tid, header_hash, line); int tid = kh_val(header_hash, iter); if ( iter == kh_end(header_hash) ) { if ( !warned ) fprintf(stderr,"Warning: Some sequences not present in the BAM, e.g. \"%s\". This message is printed only once.\n", line); warned = 1; continue; } if ( tid >= stats->nregions ) { stats->regions = realloc(stats->regions,sizeof(regions_t)*(stats->nregions+100)); int j; for (j=stats->nregions; j<stats->nregions+100; j++) { stats->regions[j].npos = stats->regions[j].mpos = stats->regions[j].cpos = 0; stats->regions[j].pos = NULL; } stats->nregions += 100; } int npos = stats->regions[tid].npos; if ( npos >= stats->regions[tid].mpos ) { stats->regions[tid].mpos += 1000; stats->regions[tid].pos = realloc(stats->regions[tid].pos,sizeof(pos_t)*stats->regions[tid].mpos); } if ( (sscanf(line+i+1,"%d %d",&stats->regions[tid].pos[npos].from,&stats->regions[tid].pos[npos].to))!=2 ) error("Could not parse the region [%s]\n"); if ( prev_tid==-1 || prev_tid!=tid ) { prev_tid = tid; prev_pos = stats->regions[tid].pos[npos].from; } if ( prev_pos>stats->regions[tid].pos[npos].from ) error("The positions are not in chromosomal order (%s:%d comes after %d)\n", line,stats->regions[tid].pos[npos].from,prev_pos); stats->regions[tid].npos++; } if (line) free(line); if ( !stats->regions ) error("Unable to map the -t sequences to the BAM sequences.\n"); fclose(fp); } void destroy_regions(stats_t *stats) { int i; for (i=0; i<stats->nregions; i++) { if ( !stats->regions[i].mpos ) continue; free(stats->regions[i].pos); } if ( stats->regions ) free(stats->regions); } static int fetch_read(const bam1_t *bam_line, void *data) { collect_stats((bam1_t*)bam_line,(stats_t*)data); return 1; } void reset_regions(stats_t *stats) { int i; for (i=0; i<stats->nregions; i++) stats->regions[i].cpos = 0; } int is_in_regions(bam1_t *bam_line, stats_t *stats) { if ( !stats->regions ) return 1; if ( bam_line->core.tid >= stats->nregions || bam_line->core.tid<0 ) return 0; if ( !stats->is_sorted ) error("The BAM must be sorted in order for -t to work.\n"); regions_t *reg = &stats->regions[bam_line->core.tid]; if ( reg->cpos==reg->npos ) return 0; // done for this chr // Find a matching interval or skip this read. No splicing of reads is done, no indels or soft clips considered, // even small overlap is enough to include the read in the stats. int i = reg->cpos; while ( i<reg->npos && reg->pos[i].to<=bam_line->core.pos ) i++; if ( i>=reg->npos ) { reg->cpos = reg->npos; return 0; } if ( bam_line->core.pos + bam_line->core.l_qseq + 1 < reg->pos[i].from ) return 0; reg->cpos = i; stats->reg_from = reg->pos[i].from; stats->reg_to = reg->pos[i].to; return 1; } void init_group_id(stats_t *stats, char *id) { if ( !stats->sam->header->dict ) stats->sam->header->dict = sam_header_parse2(stats->sam->header->text); void *iter = stats->sam->header->dict; const char *key, *val; int n = 0; stats->rg_hash = kh_init(kh_rg); while ( (iter = sam_header2key_val(iter, "RG","ID","SM", &key, &val)) ) { if ( !strcmp(id,key) || (val && !strcmp(id,val)) ) { khiter_t k = kh_get(kh_rg, stats->rg_hash, key); if ( k != kh_end(stats->rg_hash) ) fprintf(stderr, "[init_group_id] The group ID not unique: \"%s\"\n", key); int ret; k = kh_put(kh_rg, stats->rg_hash, key, &ret); kh_value(stats->rg_hash, k) = val; n++; } } if ( !n ) error("The sample or read group \"%s\" not present.\n", id); } void error(const char *format, ...) { if ( !format ) { printf("Version: %s\n", BAMCHECK_VERSION); printf("About: The program collects statistics from BAM files. The output can be visualized using plot-bamcheck.\n"); printf("Usage: bamcheck [OPTIONS] file.bam\n"); printf(" bamcheck [OPTIONS] file.bam chr:from-to\n"); printf("Options:\n"); printf(" -c, --coverage <int>,<int>,<int> Coverage distribution min,max,step [1,1000,1]\n"); printf(" -d, --remove-dups Exlude from statistics reads marked as duplicates\n"); printf(" -f, --required-flag <int> Required flag, 0 for unset [0]\n"); printf(" -F, --filtering-flag <int> Filtering flag, 0 for unset [0]\n"); printf(" --GC-depth <float,float> Bin size for GC-depth graph and the maximum reference length [2e4,4.2e9]\n"); printf(" -h, --help This help message\n"); printf(" -i, --insert-size <int> Maximum insert size [8000]\n"); printf(" -I, --id <string> Include only listed read group or sample name\n"); printf(" -l, --read-length <int> Include in the statistics only reads with the given read length []\n"); printf(" -m, --most-inserts <float> Report only the main part of inserts [0.99]\n"); printf(" -q, --trim-quality <int> The BWA trimming parameter [0]\n"); printf(" -r, --ref-seq <file> Reference sequence (required for GC-depth calculation).\n"); printf(" -t, --target-regions <file> Do stats in these regions only. Tab-delimited file chr,from,to, 1-based, inclusive.\n"); printf(" -s, --sam Input is SAM\n"); printf("\n"); } else { va_list ap; va_start(ap, format); vfprintf(stderr, format, ap); va_end(ap); } exit(-1); } int main(int argc, char *argv[]) { char *targets = NULL; char *bam_fname = NULL; char *group_id = NULL; samfile_t *sam = NULL; char in_mode[5]; stats_t *stats = calloc(1,sizeof(stats_t)); stats->ngc = 200; stats->nquals = 256; stats->nbases = 300; stats->nisize = 8000; stats->max_len = 30; stats->max_qual = 40; stats->isize_main_bulk = 0.99; // There are always outliers at the far end stats->gcd_bin_size = 20e3; stats->gcd_ref_size = 4.2e9; stats->rseq_pos = -1; stats->tid = stats->gcd_pos = -1; stats->igcd = 0; stats->is_sorted = 1; stats->cov_min = 1; stats->cov_max = 1000; stats->cov_step = 1; stats->argc = argc; stats->argv = argv; stats->filter_readlen = -1; stats->nindels = stats->nbases; strcpy(in_mode, "rb"); static struct option loptions[] = { {"help",0,0,'h'}, {"remove-dups",0,0,'d'}, {"sam",0,0,'s'}, {"ref-seq",1,0,'r'}, {"coverage",1,0,'c'}, {"read-length",1,0,'l'}, {"insert-size",1,0,'i'}, {"most-inserts",1,0,'m'}, {"trim-quality",1,0,'q'}, {"target-regions",0,0,'t'}, {"required-flag",1,0,'f'}, {"filtering-flag",0,0,'F'}, {"id",1,0,'I'}, {"GC-depth",1,0,1}, {0,0,0,0} }; int opt; while ( (opt=getopt_long(argc,argv,"?hdsr:c:l:i:t:m:q:f:F:I:1:",loptions,NULL))>0 ) { switch (opt) { case 'f': stats->flag_require=strtol(optarg,0,0); break; case 'F': stats->flag_filter=strtol(optarg,0,0); break; case 'd': stats->flag_filter|=BAM_FDUP; break; case 's': strcpy(in_mode, "r"); break; case 'r': stats->fai = fai_load(optarg); if (stats->fai==0) error("Could not load faidx: %s\n", optarg); break; case 1 : { float flen,fbin; if ( sscanf(optarg,"%f,%f",&fbin,&flen)!= 2 ) error("Unable to parse --GC-depth %s\n", optarg); stats->gcd_bin_size = fbin; stats->gcd_ref_size = flen; } break; case 'c': if ( sscanf(optarg,"%d,%d,%d",&stats->cov_min,&stats->cov_max,&stats->cov_step)!= 3 ) error("Unable to parse -c %s\n", optarg); break; case 'l': stats->filter_readlen = atoi(optarg); break; case 'i': stats->nisize = atoi(optarg); break; case 'm': stats->isize_main_bulk = atof(optarg); break; case 'q': stats->trim_qual = atoi(optarg); break; case 't': targets = optarg; break; case 'I': group_id = optarg; break; case '?': case 'h': error(NULL); default: error("Unknown argument: %s\n", optarg); } } if ( optind<argc ) bam_fname = argv[optind++]; if ( !bam_fname ) { if ( isatty(fileno((FILE *)stdin)) ) error(NULL); bam_fname = "-"; } // Init structures // .. coverage bins and round buffer if ( stats->cov_step > stats->cov_max - stats->cov_min + 1 ) { stats->cov_step = stats->cov_max - stats->cov_min; if ( stats->cov_step <= 0 ) stats->cov_step = 1; } stats->ncov = 3 + (stats->cov_max-stats->cov_min) / stats->cov_step; stats->cov_max = stats->cov_min + ((stats->cov_max-stats->cov_min)/stats->cov_step +1)*stats->cov_step - 1; stats->cov = calloc(sizeof(uint64_t),stats->ncov); stats->cov_rbuf.size = stats->nbases*5; stats->cov_rbuf.buffer = calloc(sizeof(int32_t),stats->cov_rbuf.size); // .. bam if ((sam = samopen(bam_fname, in_mode, NULL)) == 0) error("Failed to open: %s\n", bam_fname); stats->sam = sam; if ( group_id ) init_group_id(stats, group_id); bam1_t *bam_line = bam_init1(); // .. arrays stats->quals_1st = calloc(stats->nquals*stats->nbases,sizeof(uint64_t)); stats->quals_2nd = calloc(stats->nquals*stats->nbases,sizeof(uint64_t)); stats->gc_1st = calloc(stats->ngc,sizeof(uint64_t)); stats->gc_2nd = calloc(stats->ngc,sizeof(uint64_t)); stats->isize_inward = calloc(stats->nisize,sizeof(uint64_t)); stats->isize_outward = calloc(stats->nisize,sizeof(uint64_t)); stats->isize_other = calloc(stats->nisize,sizeof(uint64_t)); stats->gcd = calloc(stats->ngcd,sizeof(gc_depth_t)); stats->mpc_buf = stats->fai ? calloc(stats->nquals*stats->nbases,sizeof(uint64_t)) : NULL; stats->acgt_cycles = calloc(4*stats->nbases,sizeof(uint64_t)); stats->read_lengths = calloc(stats->nbases,sizeof(uint64_t)); stats->insertions = calloc(stats->nbases,sizeof(uint64_t)); stats->deletions = calloc(stats->nbases,sizeof(uint64_t)); stats->ins_cycles_1st = calloc(stats->nbases+1,sizeof(uint64_t)); stats->ins_cycles_2nd = calloc(stats->nbases+1,sizeof(uint64_t)); stats->del_cycles_1st = calloc(stats->nbases+1,sizeof(uint64_t)); stats->del_cycles_2nd = calloc(stats->nbases+1,sizeof(uint64_t)); realloc_rseq_buffer(stats); if ( targets ) init_regions(stats, targets); // Collect statistics if ( optind<argc ) { // Collect stats in selected regions only bam_index_t *bam_idx = bam_index_load(bam_fname); if (bam_idx == 0) error("Random alignment retrieval only works for indexed BAM files.\n"); int i; for (i=optind; i<argc; i++) { int tid, beg, end; bam_parse_region(stats->sam->header, argv[i], &tid, &beg, &end); if ( tid < 0 ) continue; reset_regions(stats); bam_fetch(stats->sam->x.bam, bam_idx, tid, beg, end, stats, fetch_read); } bam_index_destroy(bam_idx); } else { // Stream through the entire BAM ignoring off-target regions if -t is given while (samread(sam,bam_line) >= 0) collect_stats(bam_line,stats); } round_buffer_flush(stats,-1); output_stats(stats); bam_destroy1(bam_line); samclose(stats->sam); if (stats->fai) fai_destroy(stats->fai); free(stats->cov_rbuf.buffer); free(stats->cov); free(stats->quals_1st); free(stats->quals_2nd); free(stats->gc_1st); free(stats->gc_2nd); free(stats->isize_inward); free(stats->isize_outward); free(stats->isize_other); free(stats->gcd); free(stats->rseq_buf); free(stats->mpc_buf); free(stats->acgt_cycles); free(stats->read_lengths); free(stats->insertions); free(stats->deletions); free(stats->ins_cycles_1st); free(stats->ins_cycles_2nd); free(stats->del_cycles_1st); free(stats->del_cycles_2nd); destroy_regions(stats); free(stats); if ( stats->rg_hash ) kh_destroy(kh_rg, stats->rg_hash); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/misc/varfilter.py
.py
5,783
206
#!/software/bin/python # Author: lh3, converted to python and modified to add -C option by Aylwyn Scally # # About: # varfilter.py is a port of Heng's samtools.pl varFilter script into # python, with an additional -C INT option. This option sets a minimum # consensus score, above which the script will output a pileup line # wherever it _could have_ called a variant, even if none is actually # called (i.e. hom-ref positions). This is important if you want to # subsequently merge the calls with those for another individual to get a # synoptic view of calls at each site. Without this option, and in all # other respects, it behaves like samtools.pl varFilter. # # Aylwyn Scally as6@sanger.ac.uk # Filtration code: # # C low CNS quality (hom-ref only) # d low depth # D high depth # W too many SNPs in a window (SNP only) # G close to a high-quality indel (SNP only) # Q low RMS mapping quality (SNP only) # g close to another indel with higher quality (indel only) # s low SNP quality (SNP only) # i low indel quality (indel only) import sys import getopt def usage(): print '''usage: varfilter.py [options] [cns-pileup] Options: -Q INT minimum RMS mapping quality for SNPs -q INT minimum RMS mapping quality for gaps -d INT minimum read depth -D INT maximum read depth -S INT minimum SNP quality -i INT minimum indel quality -C INT minimum consensus quality for hom-ref sites -G INT min indel score for nearby SNP filtering -w INT SNP within INT bp around a gap to be filtered -W INT window size for filtering dense SNPs -N INT max number of SNPs in a window -l INT window size for filtering adjacent gaps -p print filtered variants''' def varFilter_aux(first, is_print): try: if first[1] == 0: sys.stdout.write("\t".join(first[4:]) + "\n") elif is_print: sys.stderr.write("\t".join(["UQdDWGgsiCX"[first[1]]] + first[4:]) + "\n") except IOError: sys.exit() mindepth = 3 maxdepth = 100 gapgapwin = 30 minsnpmapq = 25 mingapmapq = 10 minindelscore = 25 scorefactor = 100 snpgapwin = 10 densesnpwin = 10 densesnps = 2 printfilt = False minsnpq = 0 minindelq = 0 mincnsq = 0 try: options, args = getopt.gnu_getopt(sys.argv[1:], 'pq:d:D:l:Q:w:W:N:G:S:i:C:', []) except getopt.GetoptError: usage() sys.exit(2) for (oflag, oarg) in options: if oflag == '-d': mindepth = int(oarg) if oflag == '-D': maxdepth = int(oarg) if oflag == '-l': gapgapwin = int(oarg) if oflag == '-Q': minsnpmapq = int(oarg) if oflag == '-q': mingapmapq = int(oarg) if oflag == '-G': minindelscore = int(oarg) if oflag == '-s': scorefactor = int(oarg) if oflag == '-w': snpgapwin = int(oarg) if oflag == '-W': densesnpwin = int(oarg) if oflag == '-C': mincnsq = int(oarg) if oflag == '-N': densesnps = int(oarg) if oflag == '-p': printfilt = True if oflag == '-S': minsnpq = int(oarg) if oflag == '-i': minindelq = int(oarg) if len(args) < 1: inp = sys.stdin else: inp = open(args[0]) # calculate the window size max_dist = max(gapgapwin, snpgapwin, densesnpwin) staging = [] for t in (line.strip().split() for line in inp): (flt, score) = (0, -1) # non-var sites if t[3] == '*/*': continue is_snp = t[2].upper() != t[3].upper() if not (is_snp or mincnsq): continue # clear the out-of-range elements while staging: # Still on the same chromosome and the first element's window still affects this position? if staging[0][4] == t[0] and int(staging[0][5]) + staging[0][2] + max_dist >= int(t[1]): break varFilter_aux(staging.pop(0), printfilt) # first a simple filter if int(t[7]) < mindepth: flt = 2 elif int(t[7]) > maxdepth: flt = 3 if t[2] == '*': # an indel if minindelq and minindelq > int(t[5]): flt = 8 elif is_snp: if minsnpq and minsnpq> int(t[5]): flt = 7 else: if mincnsq and mincnsq > int(t[4]): flt = 9 # site dependent filters dlen = 0 if flt == 0: if t[2] == '*': # an indel # If deletion, remember the length of the deletion (a,b) = t[3].split('/') alen = len(a) - 1 blen = len(b) - 1 if alen>blen: if a[0] == '-': dlen=alen elif b[0] == '-': dlen=blen if int(t[6]) < mingapmapq: flt = 1 # filtering SNPs if int(t[5]) >= minindelscore: for x in (y for y in staging if y[3]): # Is it a SNP and is it outside the SNP filter window? if x[0] >= 0 or int(x[5]) + x[2] + snpgapwin < int(t[1]): continue if x[1] == 0: x[1] = 5 # calculate the filtering score (different from indel quality) score = int(t[5]) if t[8] != '*': score += scorefactor * int(t[10]) if t[9] != '*': score += scorefactor * int(t[11]) # check the staging list for indel filtering for x in (y for y in staging if y[3]): # Is it a SNP and is it outside the gap filter window if x[0] < 0 or int(x[5]) + x[2] + gapgapwin < int(t[1]): continue if x[0] < score: x[1] = 6 else: flt = 6 break else: # a SNP or hom-ref if int(t[6]) < minsnpmapq: flt = 1 # check adjacent SNPs k = 1 for x in (y for y in staging if y[3]): if x[0] < 0 and int(x[5]) + x[2] + densesnpwin >= int(t[1]) and (x[1] == 0 or x[1] == 4 or x[1] == 5): k += 1 # filtering is necessary if k > densesnps: flt = 4 for x in (y for y in staging if y[3]): if x[0] < 0 and int(x[5]) + x[2] + densesnpwin >= int(t[1]) and x[1] == 0: x[1] = 4 else: # then check gap filter for x in (y for y in staging if y[3]): if x[0] < 0 or int(x[5]) + x[2] + snpgapwin < int(t[1]): continue if x[0] >= minindelscore: flt = 5 break staging.append([score, flt, dlen, is_snp] + t) # output the last few elements in the staging list while staging: varFilter_aux(staging.pop(0), printfilt)
Python
2D
mitenjain/nanopore
submodules/samtools-0.1.19/misc/maq2sam.c
.c
4,597
174
#include <string.h> #include <zlib.h> #include <stdio.h> #include <inttypes.h> #include <stdlib.h> #include <assert.h> #define PACKAGE_VERSION "r439" //#define MAQ_LONGREADS #ifdef MAQ_LONGREADS # define MAX_READLEN 128 #else # define MAX_READLEN 64 #endif #define MAX_NAMELEN 36 #define MAQMAP_FORMAT_OLD 0 #define MAQMAP_FORMAT_NEW -1 #define PAIRFLAG_FF 0x01 #define PAIRFLAG_FR 0x02 #define PAIRFLAG_RF 0x04 #define PAIRFLAG_RR 0x08 #define PAIRFLAG_PAIRED 0x10 #define PAIRFLAG_DIFFCHR 0x20 #define PAIRFLAG_NOMATCH 0x40 #define PAIRFLAG_SW 0x80 typedef struct { uint8_t seq[MAX_READLEN]; /* the last base is the single-end mapping quality. */ uint8_t size, map_qual, info1, info2, c[2], flag, alt_qual; uint32_t seqid, pos; int dist; char name[MAX_NAMELEN]; } maqmap1_t; typedef struct { int format, n_ref; char **ref_name; uint64_t n_mapped_reads; maqmap1_t *mapped_reads; } maqmap_t; maqmap_t *maq_new_maqmap() { maqmap_t *mm = (maqmap_t*)calloc(1, sizeof(maqmap_t)); mm->format = MAQMAP_FORMAT_NEW; return mm; } void maq_delete_maqmap(maqmap_t *mm) { int i; if (mm == 0) return; for (i = 0; i < mm->n_ref; ++i) free(mm->ref_name[i]); free(mm->ref_name); free(mm->mapped_reads); free(mm); } maqmap_t *maqmap_read_header(gzFile fp) { maqmap_t *mm; int k, len; mm = maq_new_maqmap(); gzread(fp, &mm->format, sizeof(int)); if (mm->format != MAQMAP_FORMAT_NEW) { if (mm->format > 0) { fprintf(stderr, "** Obsolete map format is detected. Please use 'mapass2maq' command to convert the format.\n"); exit(3); } assert(mm->format == MAQMAP_FORMAT_NEW); } gzread(fp, &mm->n_ref, sizeof(int)); mm->ref_name = (char**)calloc(mm->n_ref, sizeof(char*)); for (k = 0; k != mm->n_ref; ++k) { gzread(fp, &len, sizeof(int)); mm->ref_name[k] = (char*)malloc(len * sizeof(char)); gzread(fp, mm->ref_name[k], len); } /* read number of mapped reads */ gzread(fp, &mm->n_mapped_reads, sizeof(uint64_t)); return mm; } void maq2tam_core(gzFile fp, const char *rg) { maqmap_t *mm; maqmap1_t mm1, *m1; int ret; m1 = &mm1; mm = maqmap_read_header(fp); while ((ret = gzread(fp, m1, sizeof(maqmap1_t))) == sizeof(maqmap1_t)) { int j, flag = 0, se_mapq = m1->seq[MAX_READLEN-1]; if (m1->flag) flag |= 1; if ((m1->flag&PAIRFLAG_PAIRED) || ((m1->flag&PAIRFLAG_SW) && m1->flag != 192)) flag |= 2; if (m1->flag == 192) flag |= 4; if (m1->flag == 64) flag |= 8; if (m1->pos&1) flag |= 0x10; if ((flag&1) && m1->dist != 0) { int c; if (m1->dist > 0) { if (m1->flag&(PAIRFLAG_FF|PAIRFLAG_RF)) c = 0; else if (m1->flag&(PAIRFLAG_FR|PAIRFLAG_RR)) c = 1; else c = m1->pos&1; } else { if (m1->flag&(PAIRFLAG_FF|PAIRFLAG_FR)) c = 0; else if (m1->flag&(PAIRFLAG_RF|PAIRFLAG_RR)) c = 1; else c = m1->pos&1; } if (c) flag |= 0x20; } if (m1->flag) { int l = strlen(m1->name); if (m1->name[l-2] == '/') { flag |= (m1->name[l-1] == '1')? 0x40 : 0x80; m1->name[l-2] = '\0'; } } printf("%s\t%d\t", m1->name, flag); printf("%s\t%d\t", mm->ref_name[m1->seqid], (m1->pos>>1)+1); if (m1->flag == 130) { int c = (int8_t)m1->seq[MAX_READLEN-1]; printf("%d\t", m1->alt_qual); if (c == 0) printf("%dM\t", m1->size); else { if (c > 0) printf("%dM%dI%dM\t", m1->map_qual, c, m1->size - m1->map_qual - c); else printf("%dM%dD%dM\t", m1->map_qual, -c, m1->size - m1->map_qual); } se_mapq = 0; // zero SE mapQ for reads aligned by SW } else { if (flag&4) printf("0\t*\t"); else printf("%d\t%dM\t", m1->map_qual, m1->size); } printf("*\t0\t%d\t", m1->dist); for (j = 0; j != m1->size; ++j) { if (m1->seq[j] == 0) putchar('N'); else putchar("ACGT"[m1->seq[j]>>6&3]); } putchar('\t'); for (j = 0; j != m1->size; ++j) putchar((m1->seq[j]&0x3f) + 33); putchar('\t'); if (rg) printf("RG:Z:%s\t", rg); if (flag&4) { // unmapped printf("MF:i:%d\n", m1->flag); } else { printf("MF:i:%d\t", m1->flag); if (m1->flag) printf("AM:i:%d\tSM:i:%d\t", m1->alt_qual, se_mapq); printf("NM:i:%d\tUQ:i:%d\tH0:i:%d\tH1:i:%d\n", m1->info1&0xf, m1->info2, m1->c[0], m1->c[1]); } } if (ret > 0) fprintf(stderr, "Truncated! Continue anyway.\n"); maq_delete_maqmap(mm); } int main(int argc, char *argv[]) { gzFile fp; if (argc == 1) { fprintf(stderr, "Version: %s\n", PACKAGE_VERSION); fprintf(stderr, "Usage: maq2sam <in.map> [<readGroup>]\n"); return 1; } fp = strcmp(argv[1], "-")? gzopen(argv[1], "r") : gzdopen(fileno(stdin), "r"); maq2tam_core(fp, argc > 2? argv[2] : 0); gzclose(fp); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/misc/md5.h
.h
1,701
58
/* This file is adapted from a program in this page: http://www.fourmilab.ch/md5/ The original source code does not work on 64-bit machines due to the wrong typedef "uint32". I also added prototypes. -lh3 */ #ifndef MD5_H #define MD5_H /* The following tests optimise behaviour on little-endian machines, where there is no need to reverse the byte order of 32 bit words in the MD5 computation. By default, HIGHFIRST is defined, which indicates we're running on a big-endian (most significant byte first) machine, on which the byteReverse function in md5.c must be invoked. However, byteReverse is coded in such a way that it is an identity function when run on a little-endian machine, so calling it on such a platform causes no harm apart from wasting time. If the platform is known to be little-endian, we speed things up by undefining HIGHFIRST, which defines byteReverse as a null macro. Doing things in this manner insures we work on new platforms regardless of their byte order. */ #define HIGHFIRST #if __LITTLE_ENDIAN__ != 0 #undef HIGHFIRST #endif #include <stdint.h> struct MD5Context { uint32_t buf[4]; uint32_t bits[2]; unsigned char in[64]; }; void MD5Init(struct MD5Context *ctx); void MD5Update(struct MD5Context *ctx, unsigned char *buf, unsigned len); void MD5Final(unsigned char digest[16], struct MD5Context *ctx); /* * This is needed to make RSAREF happy on some MS-DOS compilers. */ typedef struct MD5Context MD5_CTX; /* Define CHECK_HARDWARE_PROPERTIES to have main,c verify byte order and uint32_t settings. */ #define CHECK_HARDWARE_PROPERTIES #endif /* !MD5_H */
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/misc/ace2sam.c
.c
9,953
250
/* The MIT License Copyright (c) 2011 Heng Li <lh3@live.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <zlib.h> #include "kstring.h" #include "kseq.h" KSTREAM_INIT(gzFile, gzread, 16384) #define N_TMPSTR 5 #define LINE_LEN 60 // append a CIGAR operation plus length #define write_cigar(_c, _n, _m, _v) do { \ if (_n == _m) { \ _m = _m? _m<<1 : 4; \ _c = realloc(_c, _m * sizeof(unsigned)); \ } \ _c[_n++] = (_v); \ } while (0) // a fatal error static void fatal(const char *msg) { fprintf(stderr, "E %s\n", msg); exit(1); } // remove pads static void remove_pads(const kstring_t *src, kstring_t *dst) { int i, j; dst->l = 0; kputsn(src->s, src->l, dst); for (i = j = 0; i < dst->l; ++i) if (dst->s[i] != '*') dst->s[j++] = dst->s[i]; dst->s[j] = 0; dst->l = j; } int main(int argc, char *argv[]) { gzFile fp; kstream_t *ks; kstring_t s, t[N_TMPSTR]; int dret, i, k, af_n, af_max, af_i, c, is_padded = 0, write_cns = 0, *p2u = 0; long m_cigar = 0, n_cigar = 0; unsigned *af, *cigar = 0; while ((c = getopt(argc, argv, "pc")) >= 0) { switch (c) { case 'p': is_padded = 1; break; case 'c': write_cns = 1; break; } } if (argc == optind) { fprintf(stderr, "\nUsage: ace2sam [-pc] <in.ace>\n\n"); fprintf(stderr, "Options: -p output padded SAM\n"); fprintf(stderr, " -c write the contig sequence in SAM\n\n"); fprintf(stderr, "Notes: 1. Fields must appear in the following order: (CO->[BQ]->(AF)->(RD->QA))\n"); fprintf(stderr, " 2. The order of reads in AF and in RD must be identical\n"); fprintf(stderr, " 3. Except in BQ, words and numbers must be separated by a single SPACE or TAB\n"); fprintf(stderr, " 4. This program writes the headerless SAM to stdout and header to stderr\n\n"); return 1; } s.l = s.m = 0; s.s = 0; af_n = af_max = af_i = 0; af = 0; for (i = 0; i < N_TMPSTR; ++i) t[i].l = t[i].m = 0, t[i].s = 0; fp = strcmp(argv[1], "-")? gzopen(argv[optind], "r") : gzdopen(fileno(stdin), "r"); ks = ks_init(fp); while (ks_getuntil(ks, 0, &s, &dret) >= 0) { if (strcmp(s.s, "CO") == 0) { // contig sequence kstring_t *cns; t[0].l = t[1].l = t[2].l = t[3].l = t[4].l = 0; // 0: name; 1: padded ctg; 2: unpadded ctg/padded read; 3: unpadded read; 4: SAM line af_n = af_i = 0; // reset the af array ks_getuntil(ks, 0, &s, &dret); kputs(s.s, &t[0]); // contig name ks_getuntil(ks, '\n', &s, &dret); // read the whole line while (ks_getuntil(ks, '\n', &s, &dret) >= 0 && s.l > 0) kputsn(s.s, s.l, &t[1]); // read the padded consensus sequence remove_pads(&t[1], &t[2]); // construct the unpadded sequence // compute the array for mapping padded positions to unpadded positions p2u = realloc(p2u, t[1].m * sizeof(int)); for (i = k = 0; i < t[1].l; ++i) { p2u[i] = k; if (t[1].s[i] != '*') ++k; } // write out the SAM header and contig sequences fprintf(stderr, "H @SQ\tSN:%s\tLN:%ld\n", t[0].s, t[is_padded?1:2].l); // The SAM header line cns = &t[is_padded?1:2]; fprintf(stderr, "S >%s\n", t[0].s); for (i = 0; i < cns->l; i += LINE_LEN) { fputs("S ", stderr); for (k = 0; k < LINE_LEN && i + k < cns->l; ++k) fputc(cns->s[i + k], stderr); fputc('\n', stderr); } #define __padded2cigar(sp) do { \ int i, l_M = 0, l_D = 0; \ for (i = 0; i < sp.l; ++i) { \ if (sp.s[i] == '*') { \ if (l_M) write_cigar(cigar, n_cigar, m_cigar, l_M<<4); \ ++l_D; l_M = 0; \ } else { \ if (l_D) write_cigar(cigar, n_cigar, m_cigar, l_D<<4 | 2); \ ++l_M; l_D = 0; \ } \ } \ if (l_M) write_cigar(cigar, n_cigar, m_cigar, l_M<<4); \ else write_cigar(cigar, n_cigar, m_cigar, l_D<<4 | 2); \ } while (0) if (write_cns) { // write the consensus SAM line (dummy read) n_cigar = 0; if (is_padded) __padded2cigar(t[1]); else write_cigar(cigar, n_cigar, m_cigar, t[2].l<<4); kputsn(t[0].s, t[0].l, &t[4]); kputs("\t516\t", &t[4]); kputsn(t[0].s, t[0].l, &t[4]); kputs("\t1\t60\t", &t[4]); for (i = 0; i < n_cigar; ++i) { kputw(cigar[i]>>4, &t[4]); kputc("MIDNSHP=X"[cigar[i]&0xf], &t[4]); } kputs("\t*\t0\t0\t", &t[4]); kputsn(t[2].s, t[2].l, &t[4]); kputs("\t*", &t[4]); } } else if (strcmp(s.s, "BQ") == 0) { // contig quality if (t[0].l == 0) fatal("come to 'BQ' before reading 'CO'"); if (dret != '\n') ks_getuntil(ks, '\n', &s, &dret); // read the entire "BQ" line if (write_cns) t[4].s[--t[4].l] = 0; // remove the trailing "*" for (i = 0; i < t[2].l; ++i) { // read the consensus quality int q; if (ks_getuntil(ks, 0, &s, &dret) < 0) fprintf(stderr, "E truncated contig quality\n"); if (s.l) { q = atoi(s.s) + 33; if (q > 126) q = 126; if (write_cns) kputc(q, &t[4]); } else --i; } if (dret != '\n') ks_getuntil(ks, '\n', &s, &dret); ks_getuntil(ks, '\n', &s, &dret); // skip the empty line if (write_cns) puts(t[4].s); t[4].l = 0; } else if (strcmp(s.s, "AF") == 0) { // padded read position int reversed, neg, pos; if (t[0].l == 0) fatal("come to 'AF' before reading 'CO'"); if (write_cns) { if (t[4].l) puts(t[4].s); t[4].l = 0; } ks_getuntil(ks, 0, &s, &dret); // read name ks_getuntil(ks, 0, &s, &dret); reversed = s.s[0] == 'C'? 1 : 0; // strand ks_getuntil(ks, 0, &s, &dret); pos = atoi(s.s); neg = pos < 0? 1 : 0; pos = pos < 0? -pos : pos; // position if (af_n == af_max) { // double the af array af_max = af_max? af_max<<1 : 4; af = realloc(af, af_max * sizeof(unsigned)); } af[af_n++] = pos << 2 | neg << 1 | reversed; // keep the placement information } else if (strcmp(s.s, "RD") == 0) { // read sequence if (af_i >= af_n) fatal("more 'RD' records than 'AF'"); t[2].l = t[3].l = t[4].l = 0; ks_getuntil(ks, 0, &t[4], &dret); // QNAME if (dret != '\n') ks_getuntil(ks, '\n', &s, &dret); // read the entire RD line while (ks_getuntil(ks, '\n', &s, &dret) >= 0 && s.l > 0) kputs(s.s, &t[2]); // read the read sequence } else if (strcmp(s.s, "QA") == 0) { // clipping if (af_i >= af_n) fatal("more 'QA' records than 'AF'"); int beg, end, pos, op; ks_getuntil(ks, 0, &s, &dret); ks_getuntil(ks, 0, &s, &dret); // skip quality clipping ks_getuntil(ks, 0, &s, &dret); beg = atoi(s.s) - 1; // align clipping start ks_getuntil(ks, 0, &s, &dret); end = atoi(s.s); // clipping end if (dret != '\n') ks_getuntil(ks, '\n', &s, &dret); // compute 1-based POS pos = af[af_i]>>2; // retrieve the position information if (af[af_i]>>1&1) pos = -pos; pos += beg; // now pos is the true padded position // generate CIGAR remove_pads(&t[2], &t[3]); // backup the unpadded read sequence n_cigar = 0; if (beg) write_cigar(cigar, n_cigar, m_cigar, beg<<4|4); if (is_padded) { __padded2cigar(t[2]); if (beg && n_cigar > 1) cigar[1] -= beg<<4; // fix the left-hand CIGAR if (end < t[2].l && n_cigar) cigar[n_cigar-1] -= (t[2].l - end)<<4; // fix the right-hand CIGAR } else { // generate flattened CIGAR string for (i = beg, k = pos - 1; i < end; ++i, ++k) t[2].s[i] = t[2].s[i] != '*'? (t[1].s[k] != '*'? 0 : 1) : (t[1].s[k] != '*'? 2 : 6); // generate the proper CIGAR for (i = beg + 1, k = 1, op = t[2].s[beg]; i < end; ++i) { if (op != t[2].s[i]) { write_cigar(cigar, n_cigar, m_cigar, k<<4|op); op = t[2].s[i]; k = 1; } else ++k; } write_cigar(cigar, n_cigar, m_cigar, k<<4|op); // remove unnecessary "P" and possibly merge adjacent operations for (i = 2; i < n_cigar; ++i) { if ((cigar[i]&0xf) != 1 && (cigar[i-1]&0xf) == 6 && (cigar[i-2]&0xf) != 1) { cigar[i-1] = 0; if ((cigar[i]&0xf) == (cigar[i-2]&0xf)) // merge operations cigar[i] += cigar[i-2], cigar[i-2] = 0; } } for (i = k = 0; i < n_cigar; ++i) // squeeze out dumb operations if (cigar[i]) cigar[k++] = cigar[i]; n_cigar = k; } if (end < t[2].l) write_cigar(cigar, n_cigar, m_cigar, (t[2].l - end)<<4|4); // write the SAM line for the read kputc('\t', &t[4]); // QNAME has already been written kputw((af[af_i]&1)? 16 : 0, &t[4]); kputc('\t', &t[4]); // FLAG kputsn(t[0].s, t[0].l, &t[4]); kputc('\t', &t[4]); // RNAME kputw(is_padded? pos : p2u[pos-1]+1, &t[4]); // POS kputs("\t60\t", &t[4]); // MAPQ for (i = 0; i < n_cigar; ++i) { // CIGAR kputw(cigar[i]>>4, &t[4]); kputc("MIDNSHP=X"[cigar[i]&0xf], &t[4]); } kputs("\t*\t0\t0\t", &t[4]); // empty MRNM, MPOS and TLEN kputsn(t[3].s, t[3].l, &t[4]); // unpadded SEQ kputs("\t*", &t[4]); // QUAL puts(t[4].s); // print to stdout ++af_i; } else if (dret != '\n') ks_getuntil(ks, '\n', &s, &dret); } ks_destroy(ks); gzclose(fp); free(af); free(s.s); free(cigar); free(p2u); for (i = 0; i < N_TMPSTR; ++i) free(t[i].s); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/misc/HmmGlocal.java
.java
6,716
178
import java.io.*; import java.lang.*; public class HmmGlocal { private double[] qual2prob; private double cd, ce; // gap open probility [1e-3], gap extension probability [0.1] private int cb; // band width [7] public HmmGlocal(final double d, final double e, final int b) { cd = d; ce = e; cb = b; qual2prob = new double[256]; for (int i = 0; i < 256; ++i) qual2prob[i] = Math.pow(10, -i/10.); } private static int set_u(final int b, final int i, final int k) { int x = i - b; x = x > 0? x : 0; return (k + 1 - x) * 3; } public int hmm_glocal(final byte[] _ref, final byte[] _query, final byte[] _iqual, int[] state, byte[] q) { int i, k; /*** initialization ***/ // change coordinates int l_ref = _ref.length; byte[] ref = new byte[l_ref+1]; for (i = 0; i < l_ref; ++i) ref[i+1] = _ref[i]; // FIXME: this is silly... int l_query = _query.length; byte[] query = new byte[l_query+1]; double[] qual = new double[l_query+1]; for (i = 0; i < l_query; ++i) { query[i+1] = _query[i]; qual[i+1] = qual2prob[_iqual[i]]; } // set band width int bw2, bw = l_ref > l_query? l_ref : l_query; if (bw > cb) bw = cb; if (bw < Math.abs(l_ref - l_query)) bw = Math.abs(l_ref - l_query); bw2 = bw * 2 + 1; // allocate the forward and backward matrices f[][] and b[][] and the scaling array s[] double[][] f = new double[l_query+1][bw2*3 + 6]; double[][] b = new double[l_query+1][bw2*3 + 6]; double[] s = new double[l_query+2]; // initialize transition probabilities double sM, sI, bM, bI; sM = sI = 1. / (2 * l_query + 2); bM = (1 - cd) / l_query; bI = cd / l_query; // (bM+bI)*l_query==1 double[] m = new double[9]; m[0*3+0] = (1 - cd - cd) * (1 - sM); m[0*3+1] = m[0*3+2] = cd * (1 - sM); m[1*3+0] = (1 - ce) * (1 - sI); m[1*3+1] = ce * (1 - sI); m[1*3+2] = 0.; m[2*3+0] = 1 - ce; m[2*3+1] = 0.; m[2*3+2] = ce; /*** forward ***/ // f[0] f[0][set_u(bw, 0, 0)] = s[0] = 1.; { // f[1] double[] fi = f[1]; double sum; int beg = 1, end = l_ref < bw + 1? l_ref : bw + 1, _beg, _end; for (k = beg, sum = 0.; k <= end; ++k) { int u; double e = (ref[k] > 3 || query[1] > 3)? 1. : ref[k] == query[1]? 1. - qual[1] : qual[1] / 3.; u = set_u(bw, 1, k); fi[u+0] = e * bM; fi[u+1] = .25 * bI; sum += fi[u] + fi[u+1]; } // rescale s[1] = sum; _beg = set_u(bw, 1, beg); _end = set_u(bw, 1, end); _end += 2; for (k = _beg; k <= _end; ++k) fi[k] /= sum; } // f[2..l_query] for (i = 2; i <= l_query; ++i) { double[] fi = f[i], fi1 = f[i-1]; double sum, qli = qual[i]; int beg = 1, end = l_ref, x, _beg, _end; byte qyi = query[i]; x = i - bw; beg = beg > x? beg : x; // band start x = i + bw; end = end < x? end : x; // band end for (k = beg, sum = 0.; k <= end; ++k) { int u, v11, v01, v10; double e; e = (ref[k] > 3 || qyi > 3)? 1. : ref[k] == qyi? 1. - qli : qli / 3.; u = set_u(bw, i, k); v11 = set_u(bw, i-1, k-1); v10 = set_u(bw, i-1, k); v01 = set_u(bw, i, k-1); fi[u+0] = e * (m[0] * fi1[v11+0] + m[3] * fi1[v11+1] + m[6] * fi1[v11+2]); fi[u+1] = .25 * (m[1] * fi1[v10+0] + m[4] * fi1[v10+1]); fi[u+2] = m[2] * fi[v01+0] + m[8] * fi[v01+2]; sum += fi[u] + fi[u+1] + fi[u+2]; //System.out.println("("+i+","+k+";"+u+"): "+fi[u]+","+fi[u+1]+","+fi[u+2]); } // rescale s[i] = sum; _beg = set_u(bw, i, beg); _end = set_u(bw, i, end); _end += 2; for (k = _beg, sum = 1./sum; k <= _end; ++k) fi[k] *= sum; } { // f[l_query+1] double sum; for (k = 1, sum = 0.; k <= l_ref; ++k) { int u = set_u(bw, l_query, k); if (u < 3 || u >= bw2*3+3) continue; sum += f[l_query][u+0] * sM + f[l_query][u+1] * sI; } s[l_query+1] = sum; // the last scaling factor } /*** backward ***/ // b[l_query] (b[l_query+1][0]=1 and thus \tilde{b}[][]=1/s[l_query+1]; this is where s[l_query+1] comes from) for (k = 1; k <= l_ref; ++k) { int u = set_u(bw, l_query, k); double[] bi = b[l_query]; if (u < 3 || u >= bw2*3+3) continue; bi[u+0] = sM / s[l_query] / s[l_query+1]; bi[u+1] = sI / s[l_query] / s[l_query+1]; } // b[l_query-1..1] for (i = l_query - 1; i >= 1; --i) { int beg = 1, end = l_ref, x, _beg, _end; double[] bi = b[i], bi1 = b[i+1]; double y = (i > 1)? 1. : 0., qli1 = qual[i+1]; byte qyi1 = query[i+1]; x = i - bw; beg = beg > x? beg : x; x = i + bw; end = end < x? end : x; for (k = end; k >= beg; --k) { int u, v11, v01, v10; double e; u = set_u(bw, i, k); v11 = set_u(bw, i+1, k+1); v10 = set_u(bw, i+1, k); v01 = set_u(bw, i, k+1); e = (k >= l_ref? 0 : (ref[k+1] > 3 || qyi1 > 3)? 1. : ref[k+1] == qyi1? 1. - qli1 : qli1 / 3.) * bi1[v11]; bi[u+0] = e * m[0] + .25 * m[1] * bi1[v10+1] + m[2] * bi[v01+2]; // bi1[v11] has been foled into e. bi[u+1] = e * m[3] + .25 * m[4] * bi1[v10+1]; bi[u+2] = (e * m[6] + m[8] * bi[v01+2]) * y; } // rescale _beg = set_u(bw, i, beg); _end = set_u(bw, i, end); _end += 2; for (k = _beg, y = 1./s[i]; k <= _end; ++k) bi[k] *= y; } double pb; { // b[0] int beg = 1, end = l_ref < bw + 1? l_ref : bw + 1; double sum = 0.; for (k = end; k >= beg; --k) { int u = set_u(bw, 1, k); double e = (ref[k] > 3 || query[1] > 3)? 1. : ref[k] == query[1]? 1. - qual[1] : qual[1] / 3.; if (u < 3 || u >= bw2*3+3) continue; sum += e * b[1][u+0] * bM + .25 * b[1][u+1] * bI; } pb = b[0][set_u(bw, 0, 0)] = sum / s[0]; // if everything works as is expected, pb == 1.0 } int is_diff = Math.abs(pb - 1.) > 1e-7? 1 : 0; /*** MAP ***/ for (i = 1; i <= l_query; ++i) { double sum = 0., max = 0.; double[] fi = f[i], bi = b[i]; int beg = 1, end = l_ref, x, max_k = -1; x = i - bw; beg = beg > x? beg : x; x = i + bw; end = end < x? end : x; for (k = beg; k <= end; ++k) { int u = set_u(bw, i, k); double z; sum += (z = fi[u+0] * bi[u+0]); if (z > max) { max = z; max_k = (k-1)<<2 | 0; } sum += (z = fi[u+1] * bi[u+1]); if (z > max) { max = z; max_k = (k-1)<<2 | 1; } } max /= sum; sum *= s[i]; // if everything works as is expected, sum == 1.0 if (state != null) state[i-1] = max_k; if (q != null) { k = (int)(-4.343 * Math.log(1. - max) + .499); q[i-1] = (byte)(k > 100? 99 : k); } //System.out.println("("+pb+","+sum+")"+" ("+(i-1)+","+(max_k>>2)+","+(max_k&3)+","+max+")"); } return 0; } public static void main(String[] args) { byte[] ref = {'\0', '\1', '\3', '\3', '\1'}; byte[] query = {'\0', '\3', '\3', '\1'}; byte[] qual = new byte[4]; qual[0] = qual[1] = qual[2] = qual[3] = (byte)20; HmmGlocal hg = new HmmGlocal(1e-3, 0.1, 7); hg.hmm_glocal(ref, query, qual, null, null); } }
Java
2D
mitenjain/nanopore
submodules/samtools-0.1.19/examples/chk_indel.c
.c
2,431
84
/* To compile, copy this file to the samtools source code directory and compile with: gcc -g -O2 -Wall chk_indel_rg.c -o chk_indel_rg -Wall -I. -L. -lbam -lz */ #include <string.h> #include "bam.h" typedef struct { long cnt[4]; // short:ins, short:del, long:ins, long:del } rgcnt_t; #include "khash.h" KHASH_MAP_INIT_STR(rgcnt, rgcnt_t) #define MAX_LEN 127 #define Q_THRES 10 #define L_THRES 6 // short: <=L_THRES; otherwise long int main(int argc, char *argv[]) { bamFile fp; bam1_t *b; int i, x; khash_t(rgcnt) *h; khint_t k; if (argc == 1) { fprintf(stderr, "Usage: chk_indel_rg <in.bam>\n\n"); fprintf(stderr, "Output: filename, RG, #ins-in-short-homopolymer, #del-in-short, #ins-in-long, #del-in-long\n"); return 1; } h = kh_init(rgcnt); fp = bam_open(argv[1], "r"); bam_header_destroy(bam_header_read(fp)); // we do not need the header b = bam_init1(); while (bam_read1(fp, b) >= 0) { if (b->core.n_cigar >= 3 && b->core.qual >= Q_THRES) { const uint8_t *seq; const uint32_t *cigar = bam1_cigar(b); char *rg; for (i = 0; i < b->core.n_cigar; ++i) // check if there are 1bp indels if (bam_cigar_oplen(cigar[i]) == 1 && (bam_cigar_op(cigar[i]) == BAM_CDEL || bam_cigar_op(cigar[i]) == BAM_CINS)) break; if (i == b->core.n_cigar) continue; // no 1bp ins or del if ((rg = (char*)bam_aux_get(b, "RG")) == 0) continue; // no RG tag seq = bam1_seq(b); for (i = x = 0; i < b->core.n_cigar; ++i) { int op = bam_cigar_op(cigar[i]); if (bam_cigar_oplen(cigar[i]) == 1 && (op == BAM_CDEL || op == BAM_CINS)) { int c, j, hrun, which; c = bam1_seqi(seq, x); for (j = x + 1, hrun = 0; j < b->core.l_qseq; ++j, ++hrun) // calculate the hompolymer run length if (bam1_seqi(seq, j) != c) break; k = kh_get(rgcnt, h, rg + 1); if (k == kh_end(h)) { // absent char *key = strdup(rg + 1); k = kh_put(rgcnt, h, key, &c); memset(&kh_val(h, k), 0, sizeof(rgcnt_t)); } which = (hrun <= L_THRES? 0 : 1)<<1 | (op == BAM_CINS? 0 : 1); ++kh_val(h, k).cnt[which]; } if (bam_cigar_type(op)&1) ++x; } } } for (k = 0; k != kh_end(h); ++k) { if (!kh_exist(h, k)) continue; printf("%s\t%s", argv[1], kh_key(h, k)); for (i = 0; i < 4; ++i) printf("\t%ld", kh_val(h, k).cnt[i]); putchar('\n'); free((char*)kh_key(h, k)); } bam_destroy1(b); bam_close(fp); kh_destroy(rgcnt, h); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/examples/calDepth.c
.c
1,625
63
#include <stdio.h> #include "sam.h" typedef struct { int beg, end; samfile_t *in; } tmpstruct_t; // callback for bam_fetch() static int fetch_func(const bam1_t *b, void *data) { bam_plbuf_t *buf = (bam_plbuf_t*)data; bam_plbuf_push(b, buf); return 0; } // callback for bam_plbuf_init() static int pileup_func(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pl, void *data) { tmpstruct_t *tmp = (tmpstruct_t*)data; if ((int)pos >= tmp->beg && (int)pos < tmp->end) printf("%s\t%d\t%d\n", tmp->in->header->target_name[tid], pos + 1, n); return 0; } int main(int argc, char *argv[]) { tmpstruct_t tmp; if (argc == 1) { fprintf(stderr, "Usage: calDepth <in.bam> [region]\n"); return 1; } tmp.beg = 0; tmp.end = 0x7fffffff; tmp.in = samopen(argv[1], "rb", 0); if (tmp.in == 0) { fprintf(stderr, "Fail to open BAM file %s\n", argv[1]); return 1; } if (argc == 2) { // if a region is not specified sampileup(tmp.in, -1, pileup_func, &tmp); } else { int ref; bam_index_t *idx; bam_plbuf_t *buf; idx = bam_index_load(argv[1]); // load BAM index if (idx == 0) { fprintf(stderr, "BAM indexing file is not available.\n"); return 1; } bam_parse_region(tmp.in->header, argv[2], &ref, &tmp.beg, &tmp.end); // parse the region if (ref < 0) { fprintf(stderr, "Invalid region %s\n", argv[2]); return 1; } buf = bam_plbuf_init(pileup_func, &tmp); // initialize pileup bam_fetch(tmp.in->x.bam, idx, ref, tmp.beg, tmp.end, buf, fetch_func); bam_plbuf_push(0, buf); // finalize pileup bam_index_destroy(idx); bam_plbuf_destroy(buf); } samclose(tmp.in); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/examples/bam2bed.c
.c
1,428
52
#include <stdio.h> #include "sam.h" static int fetch_func(const bam1_t *b, void *data) { samfile_t *fp = (samfile_t*)data; uint32_t *cigar = bam1_cigar(b); const bam1_core_t *c = &b->core; int i, l; if (b->core.tid < 0) return 0; for (i = l = 0; i < c->n_cigar; ++i) { int op = cigar[i]&0xf; if (op == BAM_CMATCH || op == BAM_CDEL || op == BAM_CREF_SKIP) l += cigar[i]>>4; } printf("%s\t%d\t%d\t%s\t%d\t%c\n", fp->header->target_name[c->tid], c->pos, c->pos + l, bam1_qname(b), c->qual, (c->flag&BAM_FREVERSE)? '-' : '+'); return 0; } int main(int argc, char *argv[]) { samfile_t *fp; if (argc == 1) { fprintf(stderr, "Usage: bam2bed <in.bam> [region]\n"); return 1; } if ((fp = samopen(argv[1], "rb", 0)) == 0) { fprintf(stderr, "bam2bed: Fail to open BAM file %s\n", argv[1]); return 1; } if (argc == 2) { /* if a region is not specified */ bam1_t *b = bam_init1(); while (samread(fp, b) >= 0) fetch_func(b, fp); bam_destroy1(b); } else { int ref, beg, end; bam_index_t *idx; if ((idx = bam_index_load(argv[1])) == 0) { fprintf(stderr, "bam2bed: BAM indexing file is not available.\n"); return 1; } bam_parse_region(fp->header, argv[2], &ref, &beg, &end); if (ref < 0) { fprintf(stderr, "bam2bed: Invalid region %s\n", argv[2]); return 1; } bam_fetch(fp->x.bam, idx, ref, beg, end, fp, fetch_func); bam_index_destroy(idx); } samclose(fp); return 0; }
C
2D
mitenjain/nanopore
submodules/qualimap/scripts/qualimapRscript.r
.r
23,369
721
#!/usr/bin/env Rscript if(!require("optparse")) { install.packages("optparse", repos = "http://cran.r-project.org") } suppressPackageStartupMessages(library("optparse")) # Last modified: 14-VI-2012 option_list <- list( make_option(c("-v", "--verbose"), action="store_true", default=TRUE, help="Print extra output [default]"), make_option(c("-q", "--quietly"), action="store_false", dest="verbose", help="Print little output"), make_option(c("--data1"), type="character", action="store", help="REQUIRED. First file with counts.",default=NULL, metavar="file_counts"), make_option(c("--data2"), type="character", action="store", help="Optional. Second file with counts.",default=NULL, metavar="file_counts"), make_option(c("--name1"), type="character", action="store", help="Optional. Name for the first sample",default="Sample 1", metavar="sample_name"), make_option(c("--name2"), type="character", action="store", help="Optional. Name for the second sample.",default="Sample 2", metavar="sample_name"), make_option(c("--info"), type="character", action="store", help="Optional. Info file.",default=NULL, metavar="file_info"), make_option(c("--groups"), type="character", action="store", help="Optional. File with groups for the --info file." , default=NULL, metavar="file_groups"), make_option(c("-k", "--threshold"), type="integer", action="store", help="Optional. Threshold for the number of counts.",default=5, metavar="counts_threshold"), make_option(c("-o", "--dirOut"), type="character", action="store", help="Optional. Output folder.",default="./", metavar="folder_output"), make_option("--homesrc", type="character", action="store", help="DEVELOPMENTAL. NOT TO BE USED IN THIS VERSION", default="./", metavar="home_src folder") ) opt <- parse_args(OptionParser(option_list=option_list)) #HOMESRC <- "/home/fdgarcia/qualimap/sonia" HOMESRC <- opt$homesrc source(file.path(HOMESRC, "qualimapRfunctions.r")) #datos1 <- "counts1.txt" datos1 <- opt$data1 if(is.null(datos1)){ stop("--data1 is a REQUIRED argument") } datos2 <- opt$data2 # with the same features than datos1 and in the same order if(!file.exists(opt$dirOut)){ dir.create(opt$dirOut, recursive=TRUE) } # cutoff for the number of counts to consider a biological feature as detected k <- opt$threshold cm <- 1.5 # cex.main cl <- 1.2 # cex.lab ca <- 1 # cex.axis cc <- 1.2 # cex nom1 <- opt$name1 nom2 <- opt$name2 if (!is.null(opt$info)){ #file including features ID in "datos1" and biotypes or other classification infobio <- opt$info # NO header if (!is.null(opt$groups)){ agru.biotype <- TRUE # two columns file: 1) all biotypes in infobio 2) group for biotypes file.agru <- opt$groups # NO header }else{ file.agru <- NULL agru.biotype <- FALSE } } ########################################################################### #### DATA fichero1 <- read.delim(datos1, header = FALSE, sep = "\t", as.is = TRUE) misdatos1 <- fichero1[,2] names(misdatos1) <- fichero1[,1] if (is.null(datos2)) { misdatos2 <- NULL } else { fichero2 <- read.delim(datos2, header = FALSE, sep = "\t", as.is = TRUE) misdatos2 <- fichero2[,2] names(misdatos2) <- fichero2[,1] } #### BIOTYPES if (!is.null(opt$info)) { infofile <- read.delim(infobio, header = FALSE, sep = "\t", as.is = TRUE) myinfo <- infofile[,2] names(myinfo) <- infofile[,1] ## Completing files: data & info genes1 <- as.character(names(misdatos1)) genes2 <- as.character(names(misdatos2)) genesI <- as.character(names(myinfo)) if (length(genes2) > 0) { allgenes <- union(genes1, genes2) } else { allgenes <- genes1 } # Completing myinfo unknown <- setdiff(allgenes, genesI) # genes in data without biotype if(length(unknown) > 0) { unk <- rep("unknown", length(unknown)) names(unk) <- unknown myinfo <- c(myinfo, unk) # adding unknown genes (without biotype) write.table(unknown, file = file.path(opt$dirOut, "nogroup.txt"), sep = "\t", row.names = FALSE, col.names = FALSE, quote = FALSE) # file for unknown genes } genesII <- names(myinfo) # Completing my data notdet1 <- setdiff(genesII, genes1) # genes1 not in complete info -> counts=0 if (length(genes2) > 0) { notdet2 <- setdiff(genesII, genes2) # genes2 not in complete info -> counts=0 } else { notdet2 <- NULL } if(length(notdet1) > 0) { ceros1 <- rep(0, length(notdet1)) names(ceros1) <- notdet1 misdatos1 <- c(misdatos1, ceros1) # adding genes with 0s to data nom <- paste(nom1, "nocounts.txt", sep = ".") write.table(notdet1, file = file.path(opt$dirOut, nom), sep = "\t", row.names = FALSE, col.names = FALSE, quote = FALSE) # file for added genes } if(length(notdet2) > 0) { ceros2 <- rep(0, length(notdet2)) names(ceros2) <- notdet2 misdatos2 <- c(misdatos2, ceros2) # adding genes with 0s to data nom <- paste(nom2, "nocounts.txt", sep = ".") write.table(notdet2, file = file.path(opt$dirOut, nom), sep = "\t", row.names = FALSE, col.names = FALSE, quote = FALSE) # file for added genes } # OK files ok1 <- intersect(genes1, genesII) # genes1 with counts and biotype nom <- paste(nom1, "OK.txt", sep = ".") write.table(ok1, file = file.path(opt$dirOut, nom), sep = "\t", row.names = FALSE, col.names = FALSE, quote = FALSE) # file for added genes if (!is.null(notdet2)) { ok2 <- intersect(genes2, genesII) # genes2 with counts and biotype nom <- paste(nom2, "OK.txt", sep = ".") write.table(ok2, file = file.path(opt$dirOut, nom), sep = "\t", row.names = FALSE, col.names = FALSE, quote = FALSE) # file for added genes } ## Sorting files according to genes (all with the same genes) misdatos1 <- misdatos1[genesII] if(!is.null(misdatos2)) { misdatos2 <- misdatos2[genesII] } ## Preparing biotype files if (agru.biotype) { # If you want to group biotypes biogroups <- read.delim(file.agru, header = FALSE, sep = "\t", as.is = TRUE) biogrupos <- unique(biogroups) # Creating a list for groupes of biotypes bio.agru <- vector("list", length = length(table(biogrupos[,2]))) names(bio.agru) <- names(table(biogrupos[,2])) for (i in 1:length(bio.agru)) { bio.agru[[i]] <- biogrupos[is.element(biogrupos[,2], names(bio.agru)[i]),1] } biotipus <- bio.agru bio.agru2 <- NULL for (i in 1:length(bio.agru)) { bio.agru2 <- c(bio.agru2, rep(names(bio.agru)[i], length(bio.agru[[i]]))) } names(bio.agru2) <- unlist(bio.agru) } else { # No grouping biotipus <- as.list(names(table(myinfo))) names(biotipus) <- names(table(myinfo)) bio.agru2 <- names(table(myinfo)) names(bio.agru2) <- bio.agru2 } ########################################################################### ########################################################################### #### FEATURES DETECTION per BIOTYPE if (agru.biotype) { mybioagru <- bio.agru2[myinfo] } else { mybioagru <- myinfo } detect <- misdatos1 > k genome <- 100*table(bio.agru2[myinfo])/sum(table(bio.agru2[myinfo])) ordre <- order(genome, decreasing = TRUE) perdet1 <- genome*table(mybioagru, detect)[,2]/ table(bio.agru2[myinfo])[rownames(table(mybioagru, detect))] perdet2 <- 100*table(mybioagru, detect)[,2]/sum(table(mybioagru, detect)[,2]) ceros <- rep(0, length(genome)) biotable <- as.matrix(rbind(genome[ordre], perdet1[ordre], perdet2[ordre], ceros)) rownames(biotable) <- c("genome", "detectionVSgenome", "detectionVSsample", "ceros") if (is.null(misdatos2)) { # Saving data in a txt file mybiotable <- cbind(colnames(biotable), t(biotable[-4,])) colnames(mybiotable)[1] <- "biotype" write.table(mybiotable, file.path(opt$dirOut, "DetectionPerGroup.txt"), sep = "\t", quote = FALSE, col.names = TRUE, row.names = FALSE) # Plot (1 sample) png(filename = file.path(opt$dirOut, "DetectionPerGroup.png"), width = 3*480*2, height = 3*480, units = "px", pointsize = 3*12) par(mar = c(11, 4, 2, 2), bg = "#e6e6e6") barplot(biotable[c(1,3),], main = "Detection per group", xlab = "", ylab = "%features", axis.lty = 1, legend = FALSE, beside = TRUE, col = c("grey", 2), las = 2, ylim = c(0, 100), border = c("grey", 2)) rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = "white") barplot(biotable[c(1,3),], main = "Detection per group", xlab = "", ylab = "%features", axis.lty = 1, legend = FALSE, beside = TRUE, col = c("grey", 2), las = 2, add = TRUE, ylim = c(0, 100), border = c("grey", 2)) barplot(biotable[c(2,4),], main = "Detection per group", xlab = "", ylab = "%features", axis.lty = 1, legend = FALSE, beside = TRUE, col = c(2, 1), las = 2, density = 30, ylim = c(0, 100), border = 2, add = TRUE) legend(x = "top", bty = "n", horiz = TRUE, fill = c("grey", 2, 2), density = c(NA,30,NA), border = c("grey", 2, 2), legend = c("% in genome", "detected", "% in sample")) garbage <- dev.off() } else { detect2 <- misdatos2>k perdet3 <- genome*table(mybioagru, detect2)[names(genome),2]/ table(bio.agru2[myinfo])[names(genome)] perdet4 <- 100*table(mybioagru, detect2)[,2]/ sum(table(mybioagru, detect2)[,2]) biotable2 <- as.matrix(rbind(genome[ordre], perdet3[ordre], perdet4[ordre], ceros)) rownames(biotable2) <- c("genome", "detectionVSgenome", "detectionVSsample", "ceros") # Saving data in a txt file mybiotable <- cbind(colnames(biotable), t(biotable[-4,])) colnames(mybiotable)[1] <- "biotype" mybiotable2 <- t(biotable2[-c(1,4),]) mybiotable2 <- mybiotable2[rownames(mybiotable),] mybiotable12 <- cbind(mybiotable, mybiotable2) colnames(mybiotable12)[-c(1,2)] <- apply(cbind(colnames(mybiotable12)[-c(1,2)], rep(1:2, each = 2)), 1, paste, collapse = "_") write.table(mybiotable12, file.path(opt$dirOut, "DetectionPerGroup.txt"), sep = "\t", quote = FALSE, col.names = TRUE, row.names = FALSE) # Plot (2 samples) png(filename = file.path(opt$dirOut, "DetectionPerGroup.png"), width = 3*480*2, height = 3*480*2, units = "px", pointsize = 3*12) par(mar = c(11, 4, 2, 2), mfrow = c(2,1), bg = "#e6e6e6") # Datos1 barplot(biotable[c(1,3),], main = paste("Detection per group:", nom1), xlab = "", ylab = "%features", axis.lty = 1, legend = FALSE, beside = TRUE, col = c("grey", 2), las = 2, ylim = c(0, 100), border = c("grey", 2)) rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = "white") barplot(biotable[c(1,3),], main = paste("Detection per group:", nom1), xlab = "", ylab = "%features", axis.lty = 1, legend = FALSE, beside = TRUE, col = c("grey", 2), las = 2, add = TRUE, ylim = c(0, 100), border = c("grey", 2)) barplot(biotable[c(2,4),], main = paste("Detection per group:", nom1), xlab = "", ylab = "%features", axis.lty = 1, legend = FALSE, beside = TRUE, col = c(2, 1), las = 2, density = 30, ylim = c(0, 100), border = 2, add = TRUE) legend(x = "top", bty = "n", horiz = TRUE, fill = c("grey", 2, 2), density = c(NA,30,NA), border = c("grey", 2, 2), legend = c("% in genome", "detected", "% in sample")) # Datos2 barplot(biotable2[c(1,3),], main = paste("Detection per group:", nom2), xlab = "", ylab = "%features", axis.lty = 1, legend = FALSE, beside = TRUE, col = c("grey", 4), las = 2, ylim = c(0, 100), border = c("grey", 4)) rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = "white") barplot(biotable2[c(1,3),], main = paste("Detection per group:", nom2), xlab = "", ylab = "%features", axis.lty = 1, legend = FALSE, beside = TRUE, col = c("grey", 4), las = 2, add = TRUE, ylim = c(0, 100), border = c("grey", 4)) barplot(biotable2[c(2,4),], main = paste("Detection per group:", nom2), xlab = "", ylab = "%features", axis.lty = 1, legend = FALSE, beside = TRUE, col = c(4, 1), las = 2, density = 30, ylim = c(0, 100), border = 4, add = TRUE) legend(x = "top", bty = "n", horiz = TRUE, fill = c("grey", 4, 4), density = c(NA,30,NA), border = c("grey", 4, 4), legend = c("% in genome", "detected", "% in sample")) garbage <- dev.off() } } ########################################################################### ########################################################################### #### SATURATION GLOBAL PLOT png(filename = paste(opt$dirOut, "GlobalSaturation.png", sep=""), width = 3*480, height = 3*480, units = "px", pointsize = 3*12) par(mar = c(5,6,4,6), bg = "#e6e6e6") satur.plot2(datos1 = misdatos1, datos2 = misdatos2, myoutput = file.path(opt$dirOut, "GlobalSaturation.txt"), tit = "Global Saturation Plot", k = k, #yleftlim = NULL, yrightlim = NULL, cex.main = cm, cex.lab = cl, cex.axis = ca, cex = cc, legend = c(nom1, nom2)) garbage <- dev.off() ############################################################################ #### SATURATION PLOTS per BIOTYPE if (!is.null(opt$info)) { satbio.mine <- saturbio.dat(datos1 = misdatos1, datos2 = misdatos2, k = k, infobio = myinfo, biotypes = biotipus) mytable1 <- satbio.mine$depth1 mytable2 <- satbio.mine$depth2 for (i in 1:length(biotipus)) { mytable1 <- cbind(mytable1, satbio.mine$cond1[[i]], satbio.mine$newdet1[[i]]) mytable2 <- cbind(mytable2, satbio.mine$cond2[[i]], satbio.mine$newdet2[[i]]) png(paste(opt$dirOut, names(biotipus)[i],".png", sep = ""), width = 3*480, height = 3*480, pointsize = 3*12) par(mar = c(5,6,4,6), bg = "#e6e6e6") titulo <- paste("Number of features with reads >", k) saturbio.plot(depth1 = satbio.mine$depth1, depth2 = satbio.mine$depth2, sat1 = satbio.mine$cond1[[i]], sat2 = satbio.mine$cond2[[i]], newdet1 = satbio.mine$newdet1[[i]], newdet2 = satbio.mine$newdet2[[i]], bionum = satbio.mine$bionum[i], main = paste(names(biotipus)[i], " (", satbio.mine$bionum[i], ")", sep = ""), legend = c(nom1, nom2), yleftlim = c(0, satbio.mine$bionum[i]), ylabL = titulo, ylabR = "New detections per million reads", cex = cc, cex.main = cm, cex.lab = cl) garbage <- dev.off() } colnames(mytable1) <- c("depth", apply(cbind(rep(c("detec","newdetec"), length(satbio.mine$cond1)), rep(names(satbio.mine$cond1), each = 2)), 1, paste, collapse = "_")) write.table(mytable1, file.path(opt$dirOut, "SaturationPerGroup_1.txt"), sep = "\t", quote = FALSE, col.names = TRUE, row.names = FALSE) if(!is.null(mytable2)) { colnames(mytable2) <- c("depth", apply(cbind(rep(c("detec","newdetec"), length(satbio.mine$cond2)), rep(names(satbio.mine$cond2), each = 2)), 1, paste, collapse = "_")) write.table(mytable2, file.path(opt$dirOut, "SaturationPerGroup_2.txt"), sep = "\t", quote = FALSE, col.names = TRUE, row.names = FALSE) } ############################################################################ ############################################################################ #### COUNTS DISTRIBUTION -- per BIOTYPE countdist.mine <- countsbio.dat(misdatos1, misdatos2, k = k, nbox = 1, infobio = myinfo, biotypes = biotipus) countlist <- countdist.mine$cond1[[1]] for (i in 2:length(countdist.mine$cond1)) { countlist <- c(countlist, countdist.mine$cond1[[i]]) } names(countlist) <- names(countdist.mine$cond1) ysup <- max(sapply(countlist, quantile, probs = 0.75, na.rm = TRUE), na.rm = TRUE)*1.3 if (is.null(misdatos2)) { png(paste(opt$dirOut, "counts_boxplot.png", sep=""), width = 3*480, height = 3*480, pointsize = 3*12) par(mar = c(11,4,6,2), bg = "#e6e6e6") } else { countlist2 <- countdist.mine$cond2[[1]] for (i in 2:length(countdist.mine$cond2)) { countlist2 <- c(countlist2, countdist.mine$cond2[[i]]) } names(countlist2) <- names(countdist.mine$cond2) ysup2 <- max(sapply(countlist2, quantile, probs = 0.75, na.rm = TRUE), na.rm = TRUE)*1.3 ysup <- max(ysup, ysup2, na.rm = TRUE) png(paste(opt$dirOut, "counts_boxplot.png", sep=""), width = 3*480*2, height = 3*480, pointsize = 3*12) par(mar = c(11,4,6,2), mfrow = c(1,2), bg = "#e6e6e6") } boxplot(countlist[ordre], las = 2, main = paste("Counts distribution per group:", nom1), ylim = c(k, ysup), col = 2) rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = "white") boxplot(countlist[ordre], las = 2, main = paste("Counts distribution per group:", nom1), ylim = c(k, ysup), col = 2, add = TRUE, ylab = "Read counts of detected features") cuantos <- sapply(countlist, length) cuantos1 <- which(cuantos == 1) sumant <- sapply(countlist, sum, na.rm = TRUE) sumant0 <- which(sumant == 0) cuantosNA <- intersect(cuantos1, sumant0) cuantos[cuantosNA] <- 0 mtext(cuantos[ordre], 3, at = 1:length(countlist), cex = 1, las = 2) # txt file write.table(unlist(countlist), file.path(opt$dirOut, "Counts_boxplot_1.txt"), sep = "\t", quote = FALSE, col.names = FALSE, row.names = TRUE) if (!is.null(misdatos2)) { write.table(unlist(countlist2), file.path(opt$dirOut, "Counts_boxplot_2.txt"), sep = "\t", quote = FALSE, col.names = FALSE, row.names = TRUE) boxplot(countlist2[ordre], las = 2, main = paste("Counts distribution per group:", nom2), ylim = c(k, ysup), col = 4) rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = "white") boxplot(countlist2[ordre], las = 2, main = paste("Counts distribution per group:", nom2), ylim = c(k, ysup), col = 4, add = TRUE, ylab = "Read counts of detected features") cuantos <- sapply(countlist2, length) cuantos1 <- which(cuantos == 1) sumant <- sapply(countlist2, sum, na.rm = TRUE) sumant0 <- which(sumant == 0) cuantosNA <- intersect(cuantos1, sumant0) cuantos[cuantosNA] <- 0 mtext(cuantos[ordre], 3, at = 1:length(countlist2), cex = 1, las = 2) } garbage <- dev.off() ############################################################################ #### COUNTS DISTRIBUTION -- per BIOTYPE + sequencing depth countbio.mine <- countsbio.dat(misdatos1, misdatos2, k = k, infobio = myinfo, biotypes = biotipus) mytable1 <- c("depth", "--", countbio.mine$depth1) mytable2 <- c("depth", "--", countbio.mine$depth2) mystats <- c("lower_whisker", "lower_quartile", "median", "upper_quartile", "upper_whisker") for (i in 1:length(biotipus)) { mytable1 <- rbind(mytable1, cbind(mystats, names(countbio.mine$cond1)[i], sapply(countbio.mine$cond1[[i]], function(x) { boxplot(x, plot = FALSE)$stats }))) mytable1 <- rbind(mytable1, c("number", names(countbio.mine$cond1)[i], sapply(countbio.mine$cond1[[i]], function(x) { boxplot(x, plot = FALSE)$n }))) mytable2 <- rbind(mytable2, cbind(mystats, names(countbio.mine$cond2)[i], sapply(countbio.mine$cond2[[i]], function(x) { boxplot(x, plot = FALSE)$stats }))) mytable2 <- rbind(mytable2, c("number", names(countbio.mine$cond2)[i], sapply(countbio.mine$cond2[[i]], function(x) { boxplot(x, plot = FALSE)$n }))) png(paste(opt$dirOut, names(biotipus)[i],"_boxplot.png", sep = ""), width = 3*480, height = 3*480, pointsize = 3*12) countbio.plot(depth1 = countbio.mine$depth1, depth2 = countbio.mine$depth2, sat1 = countbio.mine$cond1[[i]], sat2 = countbio.mine$cond2[[i]], bionum = countbio.mine$bionum[[i]], las = 1, cex = 1.2, legend = c(nom1, nom2), main = names(biotipus)[i], ylab = "Read counts of detected features", xlab = "Sequencing Depth (million reads)") garbage <- dev.off() } colnames(mytable1) <- c("stat", "group", paste("depth", 1:length(countbio.mine$depth1), sep = "")) write.table(mytable1, file.path(opt$dirOut, "CountsPerGroup_boxplot_1.txt"), sep = "\t", quote = FALSE, col.names = TRUE, row.names = FALSE) if(!is.null(misdatos2)) { colnames(mytable2) <- c("stat", "group", paste("depth", 1:length(countbio.mine$depth2), sep = "")) write.table(mytable2, file.path(opt$dirOut, "CountsPerGroup_boxplot_2.txt"), sep = "\t", quote = FALSE, col.names = TRUE, row.names = FALSE) } } ############################################################################ #### CORRELATION PLOT if (!is.null(misdatos2)) { png(paste(opt$dirOut, "correlation_plot.png", sep = ""), width = 3*480, height = 3*480, pointsize = 3*12) cor.plot.2D(misdatos1, misdatos2, noplot = 0.001, log.scale = TRUE, xlab = paste("log2(", nom1, "+1)", sep = ""), ylab = paste("log2(", nom2, "+1)", sep = "")) garbage <- dev.off() }
R
2D
mitenjain/nanopore
submodules/qualimap/scripts/utils.r
.r
8,467
227
#if(!require("Repitools",quietly=T)) { source("http://bioconductor.org/biocLite.R"); biocLite("Repitools") } suppressPackageStartupMessages(library(Repitools)) #if(!require("GenomicFeatures",quietly=T)) { source("http://bioconductor.org/biocLite.R"); biocLite("GenomicFeatures") } suppressPackageStartupMessages(require(GenomicFeatures,quietly=T)) suppressPackageStartupMessages(require(rtracklayer,quietly=T)) buildAnnotation <- function(regions=NULL){ #TODO: Make it work for different organisms #TODO: Allow to pass a file with the annotation previously dowloaded #TODO: Think how to construct the annotation for other regions like CpG islands if(is.null(regions)){ stop("ERROR! regions cannot be NULL!") }else{ print(paste("STATUS:Reading regions from",regions)) annot <- import(regions,asRangedData=F) print(paste("Read",length(annot[,1]),"regions")) } annot } txdb2GRanges <- function(txdb){ tmp=unfactor(as.list(txdb)) # TODO: Potential problem with the chromosome names! Right now it is forcing to the format chr1 but maybe that the bam file has other staff annot=GRanges(seqnames=paste("chr",tmp$transcripts$tx_chrom,sep=""),ranges=IRanges(start=tmp$transcripts$tx_start,end=tmp$transcripts$tx_end),strand=tmp$transcripts$tx_strand,tx_name=tmp$transcripts$tx_name,tx_id=tmp$transcripts$tx_id,gene_id=tmp$genes$gene_id[match(tmp$transcripts$tx_id,tmp$genes$tx_id)]) g2tx=values(annot) #Now just keep the longest transcript, that's what we want tmp=width(annot) names(tmp)=values(annot)$tx_name tmp=split(tmp,values(annot)$gene_id) tmp=lapply(tmp,function(u){u[which.max(u)]}) tmp=sapply(tmp,names) annot=annot[match(tmp,values(annot)$tx_name)] annot } getBamFilesFromDFLine <- function(sample){ #print("In getBamFilesFromDFLine") #print(sample) bam.files <- c() for(i in c("medips","input")){ #print(paste(i,sample[i])) bam.files <- if(!is.na(sample[i])) c(bam.files, sample[i]) else bam.files } bam.files } getDataFromMatrix <- function(sample, names, with.NA=F){ #print("In getDataFromMatrix") ret <- c() for(i in 1:nrow(sample)){ for(n in names){ ret <- if(with.NA | !is.na(sample[i,n])) c(ret,as.character(sample[i,n])) else ret } } ret } getBamFilesFromMatrix <- function(sample){ #OBSOLETE: Use getDataFromMatrix(sample1,c("medips","input")) ret -> getDataFromMatrix(sample1,c("medips","input")) ret } #TODO: Allow to pass the design #TODO: Parse from the xml the paramenters up,down,freq,s.width #TODO: Use the replicates and compose them buildFeatureScores <- function(grl.stored=NULL, sample1=NULL, sample2=NULL, design=NULL, annot, up=2000,down=500,freq=100,s.width=300,dist="base"){ # Attention!!! If grl.stored is used, the variable for the GRangeList has to be called grl if(!is.null(grl.stored)){ #print(paste("Loading",grl.stored)) load(grl.stored) sample.names <- names(grl) }else{ medips.files1 <- getDataFromMatrix(sample1,c("medips")) sample.types <- c(getDataFromMatrix(sample1,c("sample.name"))) input.files1 <- getDataFromMatrix(sample1,c("input")) sample.types <- c(sample.types, rep(paste(getDataFromMatrix(sample1,c("sample.name"))[1],"input",sep="-"),length(input.files1))) #medips.files2 <- getDataFromMatrix(sample2,c("medips")) #sample.types <- c(sample.types, getDataFromMatrix(sample2,c("sample.name"))) #input.files2 <- getDataFromMatrix(sample2,c("input")) #sample.types <- c(sample.types, rep(paste(getDataFromMatrix(sample2,c("sample.name"))[1],"input",sep="-"),length(input.files1))) #print("sample.types") #print(sample.types) #bam.files <- c(medips.files1,input.files1,medips.files2,input.files2) bam.files <- c(medips.files1,input.files1) #bam.files <- c(getDataFromMatrix(sample1,c("medips","input")),getDataFromMatrix(sample2,c("medips","input"))) print("STATUS:Processing BAM files:") #print(bam.files) #bam.names <- c(getDataFromMatrix(sample1,c("replicate.name")),getDataFromMatrix(sample2,c("replicate.name"))) bam.names <- c( getDataFromMatrix(sample1,c("replicate.name") ) ) #print("bam.names") #print(bam.names) granges <- lapply(bam.files,BAM2GRanges) grl <- mergeReplicates(GRangesList(granges),sample.types) names(grl) <- unique(sample.types) # With unique we remove the keep only one name per replicate #sample.names <- c(getDataFromMatrix(sample1,c("sample.name"))[1],getDataFromMatrix(sample2,c("sample.name"))[1]) sample.names <- c(getDataFromMatrix(sample1,c("sample.name"))[1]) #print("sample.names") #print(sample.names) } print("STATUS:Building feature scores:") #print(paste("Building featureScores for",names(grl),"up =",up,"down =",down,"freq =",freq,"s.width =",s.width)) fs <- featureScores(grl,annot,up=up,down=down,freq=freq,s.width=s.width,verbose=TRUE,dist=dist) print("STATUS: Features scores built") if (is.null(design)){ #print("TODO! Remove this. Right now it does the default behaviour (substract 1-2 and 3-4)") #l.forScores <- list(tables(fs)[[1]] - tables(fs)[[2]], tables(fs)[[3]] - tables(fs)[[4]]) l.forScores <- list(tables(fs)[[1]] - tables(fs)[[2]]) fs@scores <- l.forScores names(fs) <- sample.names }else{ print("TODO! Consider different designs!") } fs } heatmapCluster <- function(featureScores=NULL,grl.stored=NULL,design=NULL,ma.file=NULL, expr.threshold=NULL,n.clusters=c(25),dirOut,expName,transcripts=NULL, plot.type='heatmap'){ if (!is.null(grl.stored)){ if (!is.null(transcripts)){ annot <- buildAnnotation(transcripts=transcripts) }else{ stop("TODO! Load the annotation file from the file system. Precompute it!") } fs = buildFeatureScores(grl.stored=grl.stored,annot=annot) } else{ fs = featureScores } if(is.null(expr.threshold)){ expr.threshold <- c(0) } for(th in expr.threshold){ for(cl in n.clusters){ if(!is.null(ma.file)){ ma <- read.table(ma.file, header=T,row.names=1) expr <- ma[annot@elementMetadata$tx_name,1] expr[which((expr >= -th & expr <= th))] <- NA }else{ expr=NULL } if (is.null(design)){ #l.forScores <- list(tables(featureScores)[[1]] - tables(featureScores)[[2]], tables(featureScores)[[3]] - tables(featureScores)[[4]]) #featureScores@scores <- l.forScores #file.name <- paste(expName,th,cl,sep="-") file.name <- paste(expName,". ",cl," Clusters",sep="") # We do not support the microarray at this moment print(paste("Creating",file.path(dirOut,paste(file.name,".jpg",sep="")))) jpeg(file.path(dirOut,paste(file.name,".jpg",sep="")),quality=100,h=2400,w=800) cp=clusterPlots(fs,n.clusters=cl,expr=expr,plot.type=plot.type,t.name=file.name) dev.off() browser() #cl <- as.data.frame(getClusters(cp)) report.path <- file.path(dirOut,paste(file=paste(file.name,".txt",sep=""))) cluster.levels = levels(clusters(cp)) for ( cluster.level in cluster.levels ) { write(paste("START_CLUSTER=",cluster.level), report.path, append = TRUE ) t <- attr(annot[which(clusters(cp) == cluster.level)], "elementMetadata") lapply(t, write, report.path, append=TRUE, ncolumns=1000) write("END_CLUSTER\n", report.path, append = TRUE) } print(report.path) # write.table(cl, report.path) } cl } } } # For getting a matrx (is it?) from the ClusterPlot cp getClusters <- function(cp){ cl <- clusters(cp) ids <- values(cp@anno)$gene_id an<-cbind(c,ids) #print(head(an)) an } printClusters <- function() { write(cl, c) } # From functions.R of the NAR paper unfactor=function(var){ if (is.factor(var)){ tmp=names(var) tmpopt=getOption("warn") options(warn=-1) out=as.numeric(levels(var))[as.integer(var)] options(warn=tmpopt) if(any(is.na(out)) & any(is.na(out)!=is.na(var))){ out=as.character(levels(var))[as.integer(var)] } names(out)=tmp }else if(is.data.frame(var)){ #Have to use a loop, since calling apply will return a matrix out=var for(i in 1:dim(var)[2]){ out[,i]=unfactor(var[,i]) } }else if(is.list(var)){ #Mmmmm, recursion out=lapply(var,unfactor) }else{ #The default option out=var } return(out) }
R
2D
mitenjain/nanopore
submodules/qualimap/scripts/countsQC.r
.r
10,716
341
#!/usr/bin/env Rscript suppressPackageStartupMessages(library(optparse)) suppressPackageStartupMessages(library(NOISeq)) option_list <- list( make_option(c("-c", "--compare"), action="store_true", dest="compare", help="Compare conditions"), make_option(c("--input"), type="character", action="store", help="REQUIRED. File describing the input samples.",default=NULL, metavar="input_desc"), make_option(c("--info"), type="character", action="store", help="Optional. Table summarizing gene annotations. Table must include the following: gene name, biotype, length, gc, chromosome, start pos, end pos",default=NULL, metavar="file_info"), #make_option(c("--groups"), type="character", action="store", # help="Optional. File with groups for the --info file." , default=NULL, metavar="file_groups"), make_option(c("-k", "--threshold"), type="integer", action="store", help="Optional. Threshold for the number of counts.",default=0, metavar="counts_threshold"), make_option(c("-o", "--dirOut"), type="character", action="store", help="Optional. Output folder.",default="./counts_qc", metavar="folder_output"), make_option("--homedir", type="character", action="store", help="DEVELOPMENTAL. NOT TO BE USED IN THIS VERSION", default="./", metavar="home_src folder") ) opt <- parse_args(OptionParser(option_list=option_list)) HOMESRC <- opt$homedir source(file.path(HOMESRC, "qualimapRfunctions.r")) input.desc <- opt$input if(is.null(input.desc)){ stop("--input is a REQUIRED argument") } if(!file.exists(opt$dirOut)){ dir.create(opt$dirOut, recursive=TRUE) } # cutoff for the number of counts to consider a biological feature as detected k <- opt$threshold if (is.null(opt$compare)) { compare.conditions <- FALSE } else { compare.conditions <- opt$compare } cm <- 1.5 # cex.main cl <- 1.2 # cex.lab ca <- 1 # cex.axis cc <- 1.2 # cex image.width <- 3*480 image.height <- 3*480 point.size <- 3*12 init.png <- function(path, width = image.width, height = image.height) { png(path, width, height, pointsize = point.size, type="cairo") } # LOAD DATA cat("Reading input data using input description from", input.desc, "\n") counts <- load.counts.data(input.desc) num_samples <- ncol(counts) cat("Num samples:", num_samples, "\n") expr.factors <- data.frame(Conditions = attr(counts, "factors")) #expr.factors <- data.frame(Conditions = gl(2, num_samples/2, labels = c("C1","C2") )) #factors <- data.frame(Tissue = c("Kidney", "Liver", "Kidney", "Liver","Kidney", "Liver","Kidney", "Liver","Kidney", "Liver")) cat("Conditions:\n") expr.factors cat("\n") cat("Compare conditions ", compare.conditions, "\n") if ( compare.conditions == TRUE) { if (num_samples < 2) { stop("Need at least 2 samples to compare conditions") } if (nlevels(expr.factors[,1]) != 2) { stop("Comparison can be performed only for 2 different conditions.") } } # LOAD ANNOTATIONS info.available <- FALSE gene.biotypes <- NULL gene.length <- NULL gene.gc <- NULL gene.loc <- NULL if (!is.null(opt$info)){ cat("Loading annotations from ", opt$info,"\n") ann.data <- read.csv(opt$info, sep = "\t") cat("Loaded annoations for ",nrow(ann.data), "genes\n") gene.biotypes <- ann.data[1] gene.length <- ann.data[2] gene.gc <- ann.data[3] #gene.loc <- ann.data[c(4,5,6)] info.available <- TRUE } else { print("Annotation data is not available.") } if (info.available) { gene.names <- rownames(counts) ann.names <- rownames(ann.data) intersection <- intersect(ann.names, gene.names) if (length(intersection) == 0) { warning("The gene names from counts do not correspond to the names from annotation file.") str(gene.names) str(ann.names) cat("Annotation based analysis is deactivated") info.available <- FALSE } else { cat(length(intersection),"out of",length(gene.names),"annotations from counts file found in annotations file\n") } } str(counts) dim(counts) cat("Init NOISeq data...\n") ns.data <- readData(data = counts, length = gene.length, gc = gene.gc, biotype = gene.biotypes, chromosome = gene.loc, factors = expr.factors ) ############################################################################### #### GLOBAL cat("\nDraw global plots...\n") # Counts Density #plot.new() #plot.window(xlim=c(0,max(transformed.e)), ylim=c(0,0.5)) #axis(1) #axis(2) #title(main=) #plot(density((transformed.e[idx,1])), type='l', col = 1 , xlab="Log2(Counts)", ylab="Density") #legend("right", inset=c(0,0), title="Samples", fill=1:4, legend=colnames(e)) init.png( paste(opt$dirOut, "01_Counts_Density.png",sep="/") ) par(mar=c(5, 4, 4, 8) + 0.1, xpd=TRUE) transformed.counts <- log2(counts + 0.5) for (i in 1:num_samples) { idx <- transformed.counts[,i] > 1 if (i == 1) { plot(density((transformed.counts[idx,i])), type='l', col = i, lwd=2, main="Counts density", xlab="Log2(Counts)", ylab="Density") } else { lines(density((transformed.counts[idx,i])), type='l', col = i, lwd=2) } } legend("right", title="Samples", fill=1:num_samples, legend=colnames(counts)) garbage <- dev.off() # Global saturation cat("Compute saturation..\n") saturation <- dat(ns.data, k = k, ndepth = 8, type = "saturation") init.png(paste(opt$dirOut, "02_Saturation.png", sep = "/") ) explo.plot(saturation, toplot = 1, samples = NULL) garbage <- dev.off() cat("Compute counts per biotype..\n") counts.bio <- dat(ns.data, factor = NULL, type = "countsbio") if (num_samples > 1) { # Workaround for 1-sample bug # Global feature distribution plot init.png(paste(opt$dirOut, "03_Counts_Distribution.png",sep="/")) explo.plot(counts.bio, toplot=1, samples = NULL, plottype = "boxplot") garbage <- dev.off() # Global features with low count init.png(paste(opt$dirOut, "04_Features_With_Low_Counts.png", sep="/")) explo.plot(counts.bio, toplot=1, samples = NULL, plottype = "barplot") garbage <- dev.off() } # TODO: should we include also global estimators for selected groups? ############################################################################### #### PER SAMPLE ANALYSIS cat("Draw per sample plots...\n\n") if (info.available) { cat("Compute bio detection per sample ...\n") bio.detection <- dat(ns.data, k = k, type = "biodetection", factor = NULL) cat("Compute length bias per sample ...\n") length.bias <- dat(ns.data, factor = NULL, type = "lengthbias") cat("Compute GC bias per sample ...\n") gc.bias <- dat(ns.data, factor = NULL, type = "GCbias") } for (i in 1:num_samples) { sample.name <- colnames(counts)[i] cat("Processing sample",sample.name,"\n") sample.outDir <- paste(opt$dirOut, sample.name, sep = "/") if(!file.exists(sample.outDir)){ dir.create(sample.outDir, recursive=TRUE) } # Saturation init.png(paste(sample.outDir,"01_Saturation.png",sep="/")) explo.plot(saturation, toplot = 1, samples = i) garbage <- dev.off() if (info.available) { init.png(paste(sample.outDir, "02_Bio_Detection.png", sep="/")) explo.plot(bio.detection, samples = i) garbage <- dev.off() if (num_samples > 1) { # workaround form 1-sample bug init.png(paste(sample.outDir, "03_Counts_Per_Biotype.png",sep="/")) explo.plot(counts.bio, toplot=1, samples = i, plottype = "boxplot") garbage <- dev.off() } init.png(paste(sample.outDir, "04_Length_Bias.png", sep="/")) explo.plot(length.bias, samples = i, toplot = 1) garbage <- dev.off() init.png(paste(sample.outDir, "05_GC_Bias.png", sep="/")) explo.plot(gc.bias, samples = i, toplot = 1) garbage <- dev.off() } } ############################################################################### #### PER CONDITION ANALYSIS if (compare.conditions == TRUE) { cat ("\nPerforming comparison for conditions\n") cmp.outDir <- paste(opt$dirOut, "Comparison", sep = "/") if(!file.exists(cmp.outDir)){ dir.create(cmp.outDir, recursive=TRUE) } cat("Compute counts per biotype for conditions..\n") counts.bio <- dat(ns.data, factor = "Conditions", type = "countsbio") init.png(paste(cmp.outDir, "01_Counts_Distribution.png",sep="/")) explo.plot(counts.bio, toplot=1, samples = NULL, plottype = "boxplot") garbage <- dev.off() init.png(paste(cmp.outDir, "02_Features_With_Low_Counts.png", sep="/")) explo.plot(counts.bio, toplot=1, samples = NULL, plottype = "barplot") garbage <- dev.off() if (info.available) { cat("Compute bio detection for conditions ...\n") bio.detection <- dat(ns.data, k = k, type = "biodetection", factor = "Conditions") init.png(paste(cmp.outDir, "03_Bio_Detection.png", sep="/"), width = 2*image.width) par(mfrow = c(1,2)) explo.plot(bio.detection, samples = c(1,2)) garbage <- dev.off() #init.png(paste(sample.outDir, "03_Counts_Per_Biotype.png",sep="/")) #explo.plot(counts.bio, toplot=1, samples = i, plottype = "boxplot") #garbage <- dev.off() cat("Compute length bias for conditions ...\n") length.bias <- dat(ns.data, factor = "Conditions", type = "lengthbias") init.png(paste(cmp.outDir, "04_Length_Bias.png", sep="/"), width = 2*image.width) explo.plot(length.bias, samples = NULL, toplot = 1) garbage <- dev.off() cat("Compute GC bias for conditions ...\n") gc.bias <- dat(ns.data, factor = "Conditions", type = "GCbias") init.png(paste(cmp.outDir, "05_GC_Bias.png", sep="/"), width = 2*image.width) explo.plot(gc.bias, samples = NULL, toplot = 1) garbage <- dev.off() } # #### CORRELATION PLOT # # # if (!is.null(misdatos2)) { # # png(paste(opt$dirOut, "correlation_plot.png", sep = ""), # width = 3*480, height = 3*480, pointsize = 3*12) # # cor.plot.2D(misdatos1, misdatos2, noplot = 0.001, log.scale = TRUE, # xlab = paste("log2(", nom1, "+1)", sep = ""), # ylab = paste("log2(", nom2, "+1)", sep = "")) # # garbage <- dev.off() # # } # } cat("CountsQC is successfully finished!\n")
R
2D
mitenjain/nanopore
submodules/qualimap/scripts/init.r
.r
303
12
is.installed <- function(mypkg) is.element(mypkg, installed.packages()[,1]) required.packages <- c('optparse', 'XML', 'Rsamtools', 'Repitools', 'rtracklayer' ) for (package in required.packages) { if (!is.installed(package)) { print (paste("ERROR! Package :", package, ": is missing!")) } }
R
2D
mitenjain/nanopore
submodules/qualimap/scripts/paintLocation.r
.r
4,946
109
#if(!require("optparse")) { install.packages("optparse", repos = "http://cran.r-project.org") } #if(!require("XML")) { install.packages("XML", repos = "http://cran.r-project.org") } suppressPackageStartupMessages(library("optparse")) #if(!require("Repitools")) { #source("http://bioconductor.org/biocLite.R") #biocLite("Repitools") #} #if(!require("Rsamtools")) { #source("http://bioconductor.org/biocLite.R") #biocLite("Rsamtools") #} suppressPackageStartupMessages(library(Repitools)) suppressPackageStartupMessages(library(Rsamtools)) suppressPackageStartupMessages(library(XML)) option_list <- list( make_option(c("-v", "--verbose"), action="store_true", default=TRUE, help="Print extra output [default]"), make_option(c("-q", "--quietly"), action="store_false", dest="verbose", help="Print little output"), make_option(c("--fileConfig"), type="character", action="store", help="REQUIRED. Path to configuartion file.", metavar="file_counts"), make_option(c("--vizType"), type="character", action="store", help="Visualization type. Supported values are heatmap or line", default="heatmap", metavar="file_counts"), make_option("--homedir", type="character", action="store", help="Option allows to launch the script from external tools.", default="./", metavar="home_dir folder") ) opt <- parse_args(OptionParser(option_list=option_list)) HOMEDIR <- opt$homedir viz.type <- opt$viz source(file.path(HOMEDIR, "parseConfig.r")) source(file.path(HOMEDIR, "utils.r")) #opt$fileConfig <- c("../../qualimapEpi/src/configs/config.test.xml") print("STATUS:Parsing arguments:") args <- parseConfig(opt$fileConfig) #print(colnames(args)) #print(args[[1,"microarray"]]) #print("STATUS : Parsed arguments successfully"); sample1 <- unParseDF(args[[1,"sample1"]], c("medips","input","sample.name","replicate.name")) #print(sample1) #print(class(sample1)) #sample2 <- unParseDF(args[[1,"sample2"]], c("medips","input","sample.name","replicate.name")) #print(sample2) geneSelection <- if(!is.na(args[[1,"geneSelection"]])) unParseDF(args[[1,"geneSelection"]], c("file","column")) else NULL #print(geneSelection) regions <- unParseDF(args[[1,"regions"]], c("regions"))[1,1] # [1,1] because it has only one value #print(regions) ma <- if(!is.na(args[[1,"microarray"]])) unParseDF(args[[1,"microarray"]],c("file","threshold")) else NULL ma.file <- if(!is.null(ma)) as.character(ma[1,"file"]) else NULL ma.threshold <- if(!is.null(ma)) as.numeric(ma[,"threshold"]) else c(0) #print(ma) clusters <- if(!is.na(args[[1,"clusters"]])) unParseDF(args[[1,"clusters"]],c("num")) else c(25) # Default 23 clusters #print(clusters) dirOut <- if(!is.na(args[[1,"dirOut"]])) unParseDF(args[[1,"dirOut"]], c("dirOut"))[1,1] else NULL # [1,1] because it has only one value #print(dirOut) dir.create(dirOut,showWarnings = FALSE) expID <- if(!is.na(args[[1,"expID"]])) unParseDF(args[[1,"expID"]], c("expID"))[1,1] else "Clustering Profile" # [1,1] because it has only one value. Default "location" #print(expID) #print("location") #print(args[[1,"location"]]) up=if(!is.na(args[[1,"location"]])) as.numeric(unParseDF(args[[1,"location"]],c("up"))[1,1]) else 2000 #print("up") #print(up) down=if(!is.na(args[[1,"location"]])) as.numeric(unParseDF(args[[1,"location"]],c("down"))[1,1]) else 500 #print("down") #print(down) freq=if(!is.na(args[[1,"location"]])) as.numeric(unParseDF(args[[1,"location"]],c("freq"))[1,1]) else 100 #print("freq") #print(freq) #print("fragment") #print(args[[1,"fragment"]]) fragment=if(!is.na(args[[1,"fragment"]])) as.numeric(unParseDF(args[[1,"fragment"]],c("fragment"))[1,1]) else 300 #print("fragment") #print(fragment) print("STATUS:Building annotations:") annot <- buildAnnotation(regions=regions) #annot <- buildAnnotation() #print(c(as.character(sample1[,"medips"]), as.character(sample2[1,"medips"]))) #annot <- 1 #print("STATUS:Building features scores:") fs <- buildFeatureScores(sample1=sample1,sample2=NULL,annot=annot,up=up,down=down,freq=freq,s.width=fragment) #fs <- buildFeatureScores(grl.stored="/data/medips/analysis/location/Rdata/GRangesList.48.Rdata",annot=annot) #cl.from.fs <- heatmapCluster(featureScores=fs,ma.file=ma.file,expr.threshold=c(as.numeric(ma.threshold)),n.clusters=c(as.numeric(clusters[1,])),dirOut=dirOut,expName=expID,up=up,down=down,freq=freq,s.width=fragment) print("STATUS:Perform clustering:") cl.from.fs <- heatmapCluster(featureScores=fs,ma.file=ma.file,expr.threshold=c(as.numeric(ma.threshold)),n.clusters=c(as.numeric(clusters[1,])),dirOut=dirOut,expName=expID,plot.type=viz.type) #fs <- buildFeatureScores2(sample1=sa:mple1,sample2=sample2,annot=annot)
R
2D
mitenjain/nanopore
submodules/qualimap/scripts/qualimapRfunctions.r
.r
42,920
1,638
#################################################################### ################### Qualimap R Functions #################### #################################################################### # By Sonia Tarazona, Fernando Garcia-Alcalde and Konstantin Okonechnikov # # This function creates input data based on the description file load.counts.data <- function(input.desc) { input.data <- read.table(input.desc, sep= "\t", stringsAsFactors=FALSE) sample.names <- character() conditions <- character() counts <- data.frame() gene.names <- NULL for (i in 1:nrow(input.data)) { sample.names <- c(sample.names, input.data[i,1]) conditions <- c(conditions, input.data[i,2]) path <- input.data[i,3] data.column <- as.numeric(input.data[i,4]) sample.counts <- read.table(path, sep = "\t") if (is.null(gene.names)) { gene.names <- as.character(sample.counts[,1]) head(gene.names) counts <- sample.counts[data.column] } else { counts <- cbind(counts, sample.counts[,data.column]) } } head(counts) head(gene.names) rownames(counts) <- gene.names colnames(counts) <- sample.names attr(counts, "factors") <- as.factor(conditions) counts } #****************************************************************************# ## Function to intersect multiple sets int.mult <- function(lista, todos = NULL) { if(is.null(todos)) { todos <- unlist(lista) } comunes <- todos for(i in 1:length(lista)) { comunes <- intersect(comunes, lista[[i]]) } comunes } #****************************************************************************# ## To count number of non-zero elements noceros <- function (x, num = TRUE, k = 0) { nn <- length(which(x > k)) if (num) { nn } else { if(nn > 0) { which(x > k) } else { NULL } } } #***************************************************************************# ## Saturation Plot (GLOBAL) satur.plot <- function (datos1, datos2, ylim = NULL, k = 0, tit = "Saturation", cex.main = cex.main, cex.lab = cex.lab, cex.axis = cex.axis, cex = cex, legend = c(deparse(substitute(datos1)), deparse(substitute(datos2)))) { # For datos1 n1 <- ncol(as.matrix(datos1)) if (n1 > 1) { muestra1 <- as.list(1:n1) for (i in 2:n1) { combi1 <- combn(n1, i, simplify = FALSE) if( length(combi1) > 20 ) { sub20 <- sample(1:length(combi1), size = 20, replace = FALSE) combi1 <- combi1[sub20] } muestra1 <- append(muestra1, combi1) } varias1 <- vector("list", length = length(muestra1)) names(varias1) <- sapply(muestra1, function(x) { paste("C1.", x, collapse = "", sep = "")}) for (i in 1:length(muestra1)) { varias1[[i]] <- apply(as.matrix(datos1[,muestra1[[i]]]), 1, sum) } satura1 <- data.frame("muestra" = names(varias1), "seq.depth" = sapply(varias1, sum), "noceros" = sapply(varias1, noceros, k = k)) } if (n1 == 1) { total1 <- sum(datos1) satura1 <- NULL for (i in 1:9) { # 10%, 20%, ..., 90% reads (apart 100% is calculated) muestra1 <- rmultinom(10, size = round(total1*i/10,0), prob = datos1) detec1 <- mean(apply(muestra1, 2, noceros, k = k)) satura1 <- rbind(satura1, c(round(total1*i/10,0), detec1)) } satura1 <- rbind(satura1, c(total1, noceros(datos1, k = k))) colnames(satura1) <- c("seq.depth", "noceros") satura1 <- as.data.frame(satura1) } # For datos2 if (!is.null(datos2)) { n2 <- ncol(as.matrix(datos2)) if (n2 > 1) { if (n1 == n2) { muestra2 <- muestra1 } else { muestra2 <- as.list(1:n2) for (i in 2:n2) { combi2 <- combn(n2, i, simplify = FALSE) if (length(combi2) > 20) { sub20 <- sample(1:length(combi2), size = 20, replace = FALSE) combi2 <- combi2[sub20] } muestra2 <- append(muestra2, combi2) } } varias2 <- vector("list", length = length(muestra2)) names(varias2) <- sapply(muestra2, function(x) { paste("C2.", x, collapse = "", sep = "")}) for (i in 1:length(muestra2)) { varias2[[i]] <- apply(as.matrix(datos2[,muestra2[[i]]]), 1, sum) } satura2 <- data.frame("muestra" = names(varias2), "seq.depth" = sapply(varias2, sum), "noceros" = sapply(varias2, noceros, k = k)) } if (n2 == 1) { total2 <- sum(datos2) satura2 <- NULL for (i in 1:9) { # 10%, 20%, ..., 90% reads (apart 100% is calculated) muestra2 <- rmultinom(10, size = round(total2*i/10,0), prob = datos2) detec2 <- mean(apply(muestra2, 2, noceros, k = k)) satura2 <- rbind(satura2, c(round(total2*i/10,0), detec2)) } satura2 <- rbind(satura2, c(total2, noceros(datos2, k = k))) colnames(satura2) <- c("seq.depth", "noceros") satura2 <- as.data.frame(satura2) } if (is.null(ylim)) { ylim <- c(0, NROW(datos1)) } SS1 <- range(satura1$seq.depth/10^6) SS2 <- range(satura2$seq.depth/10^6) xM <- max(SS1[2], SS2[2]) xm <- min(SS1[1], SS2[1]) par(xpd=TRUE, mar=par()$mar+c(0,0,2,0), bg = "#e6e6e6") plot(satura1$seq.depth/10^6, satura1$noceros, pch = 16, col = 2, ylim = ylim, xlim = c(xm, xM), main = tit, type = "o", xlab = "Sequencing Depth (million reads)", ylab = paste("Number of features with reads >", k), cex = 1.5, las = 1, cex.main = cex.main, cex.lab = cex.lab, cex.axis = cex.axis) rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = "white") points(satura1$seq.depth/10^6, satura1$noceros, pch = 16, col = 2, type = "o", cex = 1.5) points(satura2$seq.depth/10^6, satura2$noceros, pch = 16, col = 4, type = "o", cex = 1.5) legend(x = (xm+xM)/2, y = ylim[2]+0.15*diff(ylim), legend = legend, text.col = c(2,4), bty = "n", xjust = 0.5, lty = 1, lwd = 2, col = c(2, 4), cex = cex, horiz = TRUE) par(mar=c(5, 4, 4, 2) + 0.1) } else { if (is.null(ylim)) { ylim <- c(0, NROW(datos1)) } xlim <- range(satura1$seq.depth/10^6) par(bg = "#e6e6e6") plot(satura1$seq.depth/10^6, satura1$noceros, pch = 16, col = 2, ylim = ylim, xlim = xlim, main = tit, type = "o", xlab = "Sequencing Depth (million reads)", ylab = paste("Number of features with reads >", k), cex = 1.5, las = 1, cex.main = cex.main, cex.lab = cex.lab, cex.axis = cex.axis) rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = "white") points(satura1$seq.depth/10^6, satura1$noceros, pch = 16, col = 2, type = "o", cex = 1.5) } } #***************************************************************************# ############################################################################### ############################################################################### ## Data for saturation plot with different biotypes saturbio.dat <- function (datos1, datos2, k = 0, infobio, biotypes, nsim = 5) { # infobio = vector containing biotype for each gene in "datos" # biotypes = list containing groups of biotypes to be studied biog <- lapply(biotypes, function(x) { which(is.element(infobio, x)) }) satura1 <- satura2 <- vector("list", length = length(biotypes)) names(satura1) <- names(satura2) <- names(biotypes) newdet1 <- newdet2 <- vector("list", length = length(biotypes)) names(newdet1) <- names(newdet2) <- names(biotypes) # datos1 n1 <- NCOL(datos1) if (n1 > 1) { # when replicates are available in condition 1 varias1 <- vector("list", length = n1) # counts for each sequencing depth names(varias1) <- paste(1:n1, "rep", sep = "") for(i in 1:n1) { muestra1 <- combn(n1, i, simplify = FALSE) if (length(muestra1) > 20) { sub20 <- sample(1:length(muestra1), size = 20, replace = FALSE) muestra1 <- muestra1[sub20] } sumrepli <- NULL for (com in 1:length(muestra1)) { sumrepli <- cbind(sumrepli, rowSums(as.matrix(datos1[,muestra1[[com]]]))) } varias1[[i]] <- as.matrix(sumrepli) } } if (n1 == 1) { # simulating replicates for datos1 varias1 <- vector("list", length = nsim) # counts for each sequencing depth names(varias1) <- paste("dp", 1:nsim, sep = "") total1 <- sum(datos1) for (i in 1:(nsim-1)) { # total1*i/nbox reads (100% is calculated apart) muestra1 <- rmultinom(10, size = round(total1*i/nsim,0), prob = datos1) varias1[[i]] <- muestra1 } varias1[[nsim]] <- as.matrix(datos1) } seq.depth1 <- sapply(varias1, function(x) { mean(colSums(x)) }) # computing saturation for each biotype (datos1) for (j in 1:length(satura1)) { conbio1 <- lapply(varias1, function(x) { as.matrix(x[biog[[j]],]) }) satura1[[j]] <- sapply(conbio1, function(x) { mean(apply(x, 2, noceros, k = k)) }) } ## computing detection increasing per million reads: condition 1 for (j in 1:length(newdet1)) { puntos1 <- data.frame("x" = seq.depth1, "y" = satura1[[j]]) pendi <- NULL for(i in 2:nrow(puntos1)) { nuevo <- max(0, (puntos1$y[i]-puntos1$y[i-1])/ (puntos1$x[i]-puntos1$x[i-1])) pendi <- c(pendi, nuevo) } pendimil1 <- c(NA, pendi)*1000000 newdet1[[j]] <- pendimil1 } #### datos2 if (!is.null(datos2)) { n2 <- NCOL(datos2) if (n2 > 1) { # when replicates are available in condition 2 varias2 <- vector("list", length = n2) # counts for each sequencing depth names(varias2) <- paste(1:n2, "rep", sep = "") for(i in 1:n2) { muestra2 <- combn(n2, i, simplify = FALSE) if (length(muestra2) > 20) { sub20 <- sample(1:length(muestra2), size = 20, replace = FALSE) muestra2 <- muestra2[sub20] } sumrepli <- NULL for (com in 1:length(muestra2)) { sumrepli <- cbind(sumrepli, rowSums(as.matrix(datos2[,muestra2[[com]]]))) } varias2[[i]] <- as.matrix(sumrepli) } } if (n2 == 1) { # replicates have to be simulated varias2 <- vector("list", length = nsim) # counts for each seq depth names(varias2) <- paste("dp", 1:nsim, sep = "") total2 <- sum(datos2) for (i in 1:(nsim-1)) { # total1*i/nbox reads (100% is calculated apart) muestra2 <- rmultinom(10, size = round(total2*i/nsim,0), prob = datos2) varias2[[i]] <- muestra2 } varias2[[nsim]] <- as.matrix(datos2) } seq.depth2 <- sapply(varias2, function(x) { mean(colSums(x)) }) # computing saturation for each biotype (datos2) for (j in 1:length(satura2)) { conbio2 <- lapply(varias2, function(x) { as.matrix(x[biog[[j]]]) }) satura2[[j]] <- sapply(conbio2, function(x) { mean(apply(x, 2, noceros, k = k)) }) } # computing detection increasing per million reads: condition 2 for (j in 1:length(newdet2)) { puntos2 <- data.frame("x" = seq.depth2, "y" = satura2[[j]]) pendi <- NULL for(i in 2:nrow(puntos2)) { nuevo <- max(0, (puntos2$y[i]-puntos2$y[i-1])/ (puntos2$x[i]-puntos2$x[i-1])) pendi <- c(pendi, nuevo) } pendimil2 <- c(NA, pendi)*1000000 newdet2[[j]] <- pendimil2 } satura <- list("cond1" = satura1, "cond2" = satura2, "bionum" = sapply(biog, length), "depth1" = seq.depth1, "depth2" = seq.depth2, "newdet1" = newdet1, "newdet2" = newdet2) } else { satura <- list("cond1" = satura1, "cond2" = satura2, "bionum" = sapply(biog, length), "depth1" = seq.depth1, "depth2" = NULL, "newdet1" = newdet1, "newdet2" = NULL) } ### Results satura } #*****************************************************************************# ## Saturation plot with different biotypes saturbio.plot <- function(depth1, depth2 = NULL, sat1, sat2 = NULL, bionum, newdet1 = NULL, newdet2 = NULL, xlim = NULL, yleftlim = NULL, yrightlim = NULL, main = "Saturation per biotype", lwdL = 2, lwdR = 20, legend = c("sample1", "sample2"), ylabL = "Number of detected features", ylabR = "New detections per million reads", cex.main = 1, cex.lab = 1, cex.axis = 1, cex = 1) { if (bionum > 0) { if (!is.null(depth2)) { # yleftlim for plot and plot.y2 if (is.null(yleftlim)) { yleftlim <- c(min(c(sat1, sat2)), max(c(sat1, sat2))) } # xlim for plot if (is.null(xlim)) { SS1 <- range(depth1/10^6) SS2 <- range(depth2/10^6) xM <- max(SS1[2], SS2[2]) xm <- min(SS1[1], SS2[1]) xlim <- c(xm, xM) } percen1 <- round(100*max(sat1)/bionum, 1) percen2 <- round(100*max(sat2)/bionum, 1) if(is.null(newdet1)) { # PLOT for detections #par(bg = "#e6e6e6") plot(depth1/10^6, sat1, pch = 16, col = 2, ylim = yleftlim, lwd = lwdL, xlim = xlim, main = main, type = "o", xlab = "Sequencing Depth (million reads)", ylab = ylabL, cex.main = cex.main, cex.lab = cex.lab, las = 1, cex.axis = cex.axis, cex = 1.5) rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = "white") points(depth1/10^6, sat1, pch = 16, col = 2, lwd = lwdL, type = "o", cex = 1.5) points(depth2/10^6, sat2, pch = 16, col = 4, lwd = lwdL, type = "o", cex = 1.5) legend("top", legend = paste(legend, ": ", c(percen1, percen2), "% detected", sep = ""), text.col = c(2,4), bty = "n", lty = 1, lwd = lwdL, col = c(2, 4), cex = 0.9) } else { # yrightlim for plot.y2 if (is.null(yrightlim)) { maxi <- max(na.omit(c(newdet1, newdet2))) if (maxi < 10) { yrightlim <- c(0, max(10,maxi)) } else { yrightlim <- c(0, maxi*1.1) } } # PLOT with 2 axis plot.y2(x = depth1/10^6, yright = newdet1, yleft = sat1, type = c("h", "o"), lwd = c(lwdR, lwdL), xlab = "Sequencing depth (million reads)", xlim = xlim, yrightlim = yrightlim, yleftlim = yleftlim, yylab = c(ylabR, ylabL), pch = c(1,19), col = c("pink",2), main = main, x2 = depth2/10^6, yright2 = newdet2, yleft2 = sat2, col2 = c("lightblue1",4), cex.main = cex.main, cex.lab = cex.lab, cex.axis = cex.axis, cex2 = c(1.5,1.5)) legend.text <- c(paste(legend[1], "(left)"), paste(legend[2], "(left)"), paste(legend[1], "(right)"), paste(legend[2], "(right)"), paste(percen1,"% detected"), paste(percen2,"% detected")) legend.pch <- c(16, 16, 15, 15, 1, 1) legend.col <- c(2, 4, "pink", "lightblue1", 0, 0) legend("top", legend = legend.text, pch = legend.pch, col = legend.col, ncol = 3, bty = "n", cex = 0.9) } } else { ### Only for 1 sample # yleftlim for plot and plot.y2 if (is.null(yleftlim)) { yleftlim <- range(sat1) } # xlim for plot if (is.null(xlim)) { xlim <- range(depth1/10^6) } percen1 <- round(100*max(sat1)/bionum, 1) if(is.null(newdet1)) { # PLOT for detections #par(bg = "#e6e6e6") plot(depth1/10^6, sat1, pch = 16, col = 4, ylim = yleftlim, lwd = lwdL, xlim = xlim, main = main, type = "o", xlab = "Sequencing Depth (million reads)", ylab = ylabL, cex.main = cex.main, cex.lab = cex.lab, las = 1, cex.axis = cex.axis, cex = 1.5) rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = "white") points(depth1/10^6, sat1, pch = 16, col = 2, lwd = lwdL, type = "o", cex = 1.5) legend("top", legend = paste(legend, ": ", percen1, "% detected", sep = ""), text.col = 2, bty = "n", lty = 1, lwd = lwdL, col = 4, cex = 0.9) } else { # yrightlim for plot.y2 if (is.null(yrightlim)) { maxi <- max(na.omit(newdet1)) if (maxi < 10) { yrightlim <- c(0, max(10,maxi)) } else { yrightlim <- c(0, maxi*1.1) } } # PLOT with 2 axis plot.y2(x = depth1/10^6, yright = newdet1, yleft = sat1, type = c("h", "o"), lwd = c(lwdR, lwdL), xlab = "Sequencing depth (million reads)", xlim = xlim, yrightlim = yrightlim, yleftlim = yleftlim, yylab = c(ylabR, ylabL), pch = c(1,19), main = main, col = c("pink",2), cex.main = cex.main, cex.lab = cex.lab, cex.axis = cex.axis, cex2 = c(1.5,1.5)) legend.text <- c("Left axis", "Right axis", paste(percen1,"%detected")) legend.pch = c(16, 15, 1) legend.col = c(2, "pink", 0) legend("top", legend = legend.text, pch = legend.pch, col = legend.col, ncol = 3, cex = 0.9) } } } else { print("Biotype not found in this dataset") } } #*****************************************************************************# ## Counts for detected genes Plot according to BIOTYPES countsbio.dat <- function (datos1, datos2, k = 0, infobio, biotypes, nbox = 5) { # infobio = vector containing biotype for each gene in "datos" # biotypes = list containing groups of biotypes to be studied # nbox = number of different depths to be plotted (only for simulated data) biog <- lapply(biotypes, function(x) { which(is.element(infobio, x)) }) # which genes belong to each biotype satura1 <- satura2 <- vector("list", length = length(biotypes)) names(satura1) <- names(satura2) <- names(biotypes) ### DATOS 1 n1 <- NCOL(datos1) ## replicates available for condition 1 if (n1 > 1) { varias1 <- vector("list", length = n1) # counts for each sequencing depth names(varias1) <- paste(1:n1, "rep", sep = "") for(i in 1:n1) { muestra1 <- combn(n1, i, simplify = FALSE) if (length(muestra1) > 20) { sub20 <- sample(1:length(muestra1), size = 20, replace = FALSE) muestra1 <- muestra1[sub20] } sumrepli <- NULL for (com in 1:length(muestra1)) { sumrepli <- cbind(sumrepli, rowSums(as.matrix(datos1[,muestra1[[com]]]))) } varias1[[i]] <- rowMeans(sumrepli) } } ## replicates simulated for condition 1 if (n1 == 1) { # replicates have to be simulated varias1 <- vector("list", length = nbox) # counts for each sequencing depth names(varias1) <- paste("dp", 1:nbox, sep = "") total1 <- sum(datos1) if (nbox > 1) { for (i in 1:(nbox-1)) { # total1*i/nbox reads (100% is calculated apart) muestra1 <- rmultinom(10, size = round(total1*i/nbox,0), prob = datos1) varias1[[i]] <- rowMeans(muestra1) } } varias1[[nbox]] <- datos1 } seq.depth1 <- sapply(varias1, sum) # sequencing depth for each new sample ## selecting detected genes for each biotype (datos1) for (j in 1:length(satura1)) { satura1[[j]] <- vector("list", length = length(varias1)) names(satura1[[j]]) <- names(varias1) # selecting genes in bioclass j for each sample conbio1 <- lapply(varias1, function(x) { x[biog[[j]]] }) for (i in 1:length(conbio1)) { # selecting the genes with counts > k noK <- noceros(conbio1[[i]], k = k, num = FALSE) if (is.null(noK)) { satura1[[j]][[i]] <- NA } else { satura1[[j]][[i]] <- conbio1[[i]][noK] } } } #### DATOS 2 if (!is.null(datos2)) { n2 <- NCOL(datos2) ## replicates available for condition 2 if (n2 > 1) { varias2 <- vector("list", length = n2) names(varias2) <- paste(1:n2, "rep", sep = "") for (i in 1:n2) { muestra2 <- combn(n2, i, simplify = FALSE) if (length(muestra2) > 20) { sub20 <- sample(1:length(muestra2), size = 20, replace = FALSE) muestra2 <- muestra2[sub20] } sumrepli2 <- NULL for (com in 1:length(muestra2)) { sumrepli2 <- cbind(sumrepli2, rowSums(as.matrix(datos2[,muestra2[[com]]]))) } varias2[[i]] <- rowMeans(sumrepli2) } } ## replicates simulated for condition 2 if (n2 == 1) { # replicates have to be simulated varias2 <- vector("list", length = nbox) # counts for each seq depth names(varias2) <- paste("dp", 1:nbox, sep = "") total2 <- sum(datos2) if (nbox > 1) { for (i in 1:(nbox-1)) { # total1*i/nbox reads (100% is calculated apart) muestra2 <- rmultinom(10, size = round(total2*i/nbox,0), prob = datos2) varias2[[i]] <- rowMeans(muestra2) } } varias2[[nbox]] <- datos2 } seq.depth2 <- sapply(varias2, sum) # sequencing depth for each new sample ## selecting detected genes for each biotype (datos2) for (j in 1:length(satura2)) { satura2[[j]] <- vector("list", length = length(varias2)) names(satura2[[j]]) <- names(varias2) # selecting genes in bioclass j for each sample conbio2 <- lapply(varias2, function(x) { x[biog[[j]]] }) for (i in 1:length(conbio2)) { # selecting the genes with counts > k noK <- noceros(conbio2[[i]], k = k, num = FALSE) if (is.null(noK)) { satura2[[j]][[i]] <- NA } else { satura2[[j]][[i]] <- conbio2[[i]][noK] } } } ## results satura <- list("cond1" = satura1, "cond2" = satura2, "bionum" = sapply(biog, length), "depth1" = seq.depth1, "depth2" = seq.depth2) } else { ## results satura <- list("cond1" = satura1, "cond2" = satura2, "bionum" = sapply(biog, length), "depth1" = seq.depth1, "depth2" = NULL) } satura } #****************************************************************************# ## PLOT: Mean length for detected genes Plot according to BIOTYPES countbio.plot <- function (depth1, depth2, sat1, sat2, bionum, legend = c("sample1", "sample2"), main = "", ylab = "# counts of detected features", xlab = "Sequencing Depth", ylim = NULL, las = 0, cex.main = 1, cex.lab = 1, cex.axis = 1, cex = 1) { if (bionum == 0) { print("Biotype not found in this dataset") } else { if (!is.null(depth2)) { # ylim for plot if (is.null(ylim)) { #maxi <- sapply(c(sat1,sat2), max, na.rm = TRUE) q75 <- sapply(c(sat1,sat2), quantile, probs = 0.75, na.rm = TRUE) #limis <- q75 + 0.2*(maxi - q75) #ylim <- c(0, max(limis, na.rm = TRUE)) ylim <- c(0, suppressWarnings(max(q75, na.rm = TRUE))*1.3) } # boxplots data depth <- c(depth1, depth2) depth <- round(depth/10^6, 1) d.sort <- sort(depth) d.order <- order(depth) n1 <- length(depth1) n2 <- length(depth2) databox <- vector("list", length = n1+n2) names(databox) <- d.sort colo <- NULL for (i in 1:(n1+n2)) { if ( d.order[i] > n1 ) { dd <- d.order[i] - n1 databox[[i]] <- sat2[[dd]] colo <- c(colo, 4) } else { dd <- d.order[i] databox[[i]] <- sat1[[dd]] colo <- c(colo, 2) } } } else { #### only DATOS1 # ylim for plot if (is.null(ylim)) { #maxi <- sapply(sat1, max, na.rm = TRUE) q75 <- sapply(sat1, quantile, probs = 0.75, na.rm = TRUE) #limis <- q75 + 0.001*(maxi - q75) #ylim <- c(0, max(limis, na.rm = TRUE)) ylim <- c(0, suppressWarnings(max(q75, na.rm = TRUE))*1.3) } # boxplots data depth <- round(depth1/10^6,1) n1 <- length(depth1) databox <- sat1 colo <- rep(2, n1) } numNA <- sapply(databox, function(x) { length(which(is.na(x))) }) cuantos <- sapply(databox, length) if (sum(cuantos-numNA) != 0) { # BOXPLOT par(bg = "#e6e6e6") boxplot(databox, col = colo, ylim = ylim, main = main, type = "b", xlab = xlab, ylab = ylab, names = depth, cex.main = cex.main, cex.lab = cex.lab, cex.axis = cex.axis) rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = "white") boxplot(databox, col = colo, ylim = ylim, main = main, type = "b", xlab = xlab, ylab = ylab, names = depth, cex.main = cex.main, cex.lab = cex.lab, cex.axis = cex.axis, add = TRUE) if (!is.null(depth2)) { legend("top", legend = legend, text.col = c(2,4), bty = "o", bg = "white", fill = c(2, 4), cex = cex, horiz = TRUE) } cuantos1 <- which(cuantos == 1) sumant <- sapply(databox, sum, na.rm = TRUE) sumant0 <- which(sumant == 0) cuantosNA <- intersect(cuantos1, sumant0) cuantos[cuantosNA] <- 0 mtext(cuantos, 3, at = 1:length(databox), cex = 0.7*cex, las = las) } else { mismar <- par()$mar par(mar = c(2,2,4,2), bg = "#e6e6e6") plot(1,1, col = "white", xlab = "", ylab = "", xaxt = "n", yaxt = "n", main = main) rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = "white") text(1,1, "No counts found for this class") par(mar = mismar) #print("No features detected for this biotype") } } } #*************************************************************************# ############################################################################# ############## Plot with 2 different Y axis (left and right) ############ ############################################################################# # By Ajay Shah (taken from [R] Plot 2 time series with different y axes # (left and right), # in https://stat.ethz.ch/pipermail/r-help/2004-March/047775.html) # Modified by: Sonia Tarazona ### PARAMETERS (default): # x: data to be drawn on X-axis # yright: data to be drawn on Y right axis # yleft: data to be drawn on Y left axis # yrightlim (range(yright, na.rm = TRUE)): ylim for rigth Y-axis # yleftlim (range(yleft, na.rm = TRUE)): ylim for left Y-axis # xlab (NULL): Label for X-axis # yylab (c("","")): Labels for right and left Y-axis # pch (c(1,2)): Type of symbol for rigth and left data # col (c(1,2)): Color for rigth and left data # linky (TRUE): If TRUE, points are connected by lines. # smooth (0): Friedman's super smoothing # lwds (1): Line width for smoothed line # length (10): Number of tick-marks to be drawn on axis # ...: Other graphical parameters to be added by user (such as main, font, etc.) ### plot.y2 <- function(x, yright, yleft, yrightlim = range(yright, na.rm = TRUE), yleftlim = range(yleft, na.rm = TRUE), xlim = range(x, na.rm = TRUE), xlab = NULL, yylab = c("",""), lwd = c(2,2), pch = c(1,2), col = c(1,2), type = c("o","o"), linky = TRUE, smooth = 0, cex2 = c(1,1), lwds = 1, length = 10, ..., x2 = NULL, yright2 = NULL, yleft2 = NULL, col2 = c(3,4)) { #par(mar = c(5,2,4+2,2), oma = c(0,3,0,3)) #par(mar = c(5,4,4+2,4)) ## Plotting RIGHT axis data #par(bg = "#e6e6e6") plot(x, yright, ylim = yrightlim, axes = FALSE, ylab = "", xlab = xlab, xlim = xlim, pch = pch[1], type = type[1], lwd = lwd[1], col = col[1], ...) rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = "white") points(x, yright, pch = pch[1], type = type[1], lwd = lwd[1], col = col[1], cex = cex2[1], ...) axis(4, pretty(yrightlim, length), col = 1, col.axis = 1, las = 1) if (!is.null(yright2)) { points(x2, yright2, type = type[1], pch = pch[1], lwd = lwd[1], col = col2[1], cex = cex2[1], ...) } #if (linky) lines(x, yright, col = col[1], ...) if (smooth != 0) lines(supsmu(x, yright, span = smooth), col = col[1], lwd = lwds, ...) if(yylab[1]=="") { mtext(deparse(substitute(yright)), side = 4, outer = FALSE, line = 4, col = 1, las = 3, ...) } else { mtext(yylab[1], side = 4, outer = FALSE, line = 4, col = 1, las = 3, ...) } par(new = TRUE)#, xpd = TRUE, mar = c(5,2,4+2,2), oma = c(0,3,0,3)) ## Plotting LEFT axis data plot(x, yleft, ylim = yleftlim, axes = FALSE, ylab = "" , xlab = xlab, xlim = xlim, cex = cex2[2], pch = pch[2], type = type[2], lwd = lwd[2], col = col[2], ...) box() axis(2, pretty(yleftlim, length), col = 1, col.axis = 1, las = 1) if (!is.null(yleft2)) { points(x2, yleft2, type = type[2], pch = pch[2], lwd = lwd[2], col = col2[2], cex = cex2[2], ...) } #if (linky) lines(x, yleft, col = col[2], ...) if (smooth != 0) lines(supsmu(x, yleft, span = smooth), col = col[2], lwd=lwds, ...) if(yylab[2] == "") { mtext(deparse(substitute(yleft)), side = 2, outer = FALSE, line = 4, col = 1, las = 3,...) } else { mtext(yylab[2], side = 2, outer = FALSE, line = 4, col = 1, las = 3,...) } ## X-axis axis(1, at = pretty(xlim, length)) } ############################################################################### ############################################################################### ## Global Saturation Plot including new detection per million reads satur.plot2 <- function (datos1, datos2, myoutput, yleftlim = NULL, yrightlim = NULL, k = 0, tit = "Saturation", cex.main = cex.main, cex.lab = cex.lab, cex.axis = cex.axis, cex = cex, legend = c(deparse(substitute(datos1)), deparse(substitute(datos2)))) { # For datos1 n1 <- ncol(as.matrix(datos1)) if (n1 > 1) { muestra1 <- as.list(1:n1) for (i in 2:n1) { combi1 <- combn(n1, i, simplify = FALSE) if( length(combi1) > 20 ) { sub20 <- sample(1:length(combi1), size = 20, replace = FALSE) combi1 <- combi1[sub20] } muestra1 <- append(muestra1, combi1) } varias1 <- vector("list", length = length(muestra1)) names(varias1) <- sapply(muestra1, function(x) { paste("C1.", x, collapse = "", sep = "")}) for (i in 1:length(muestra1)) { varias1[[i]] <- apply(as.matrix(datos1[,muestra1[[i]]]), 1, sum) } satura1 <- data.frame("muestra" = names(varias1), "seq.depth" = sapply(varias1, sum), "noceros" = sapply(varias1, noceros, k = k)) } if (n1 == 1) { total1 <- sum(datos1) satura1 <- NULL for (i in 1:9) { # 10%, 20%, ..., 90% reads (apart 100% is calculated) muestra1 <- rmultinom(10, size = round(total1*i/10,0), prob = datos1) detec1 <- mean(apply(muestra1, 2, noceros, k = k)) satura1 <- rbind(satura1, c(round(total1*i/10,0), detec1)) } satura1 <- rbind(satura1, c(total1, noceros(datos1, k = k))) colnames(satura1) <- c("seq.depth", "noceros") satura1 <- as.data.frame(satura1) } # new detections (sample 1) puntos1 <- data.frame("x" = satura1$seq.depth, "y" = satura1$noceros) pendi <- NULL for (i in 2:nrow(puntos1)) { nuevo <- max(0, (puntos1$y[i]-puntos1$y[i-1])/ (puntos1$x[i]-puntos1$x[i-1])) pendi <- c(pendi, nuevo) } newdet1 <- c(NA, pendi)*1000000 # For datos2 if (!is.null(datos2)) { n2 <- ncol(as.matrix(datos2)) if (n2 > 1) { if (n1 == n2) { muestra2 <- muestra1 } else { muestra2 <- as.list(1:n2) for (i in 2:n2) { combi2 <- combn(n2, i, simplify = FALSE) if (length(combi2) > 20) { sub20 <- sample(1:length(combi2), size = 20, replace = FALSE) combi2 <- combi2[sub20] } muestra2 <- append(muestra2, combi2) } } varias2 <- vector("list", length = length(muestra2)) names(varias2) <- sapply(muestra2, function(x) { paste("C2.", x, collapse = "", sep = "")}) for (i in 1:length(muestra2)) { varias2[[i]] <- apply(as.matrix(datos2[,muestra2[[i]]]), 1, sum) } satura2 <- data.frame("muestra" = names(varias2), "seq.depth" = sapply(varias2, sum), "noceros" = sapply(varias2, noceros, k = k)) } if (n2 == 1) { total2 <- sum(datos2) satura2 <- NULL for (i in 1:9) { # 10%, 20%, ..., 90% reads (apart 100% is calculated) muestra2 <- rmultinom(10, size = round(total2*i/10,0), prob = datos2) detec2 <- mean(apply(muestra2, 2, noceros, k = k)) satura2 <- rbind(satura2, c(round(total2*i/10,0), detec2)) } satura2 <- rbind(satura2, c(total2, noceros(datos2, k = k))) colnames(satura2) <- c("seq.depth", "noceros") satura2 <- as.data.frame(satura2) } # new detections (sample 2) puntos2 <- data.frame("x" = satura2$seq.depth, "y" = satura2$noceros) pendi <- NULL for (i in 2:nrow(puntos2)) { nuevo <- max(0, (puntos2$y[i]-puntos2$y[i-1])/ (puntos2$x[i]-puntos2$x[i-1])) pendi <- c(pendi, nuevo) } newdet2 <- c(NA, pendi)*1000000 ## PLOT LIMITS # yleftlim for plot.y2 if (is.null(yleftlim)) { yleftlim <- c(0, NROW(datos1)) } # xlim SS1 <- range(satura1$seq.depth/10^6) SS2 <- range(satura2$seq.depth/10^6) xM <- max(SS1[2], SS2[2]) xm <- min(SS1[1], SS2[1]) # yrightlim for plot.y2 if (is.null(yrightlim)) { maxi <- max(na.omit(c(newdet1, newdet2))) if (maxi < 10) { yrightlim <- c(0, max(10,maxi)) } else { yrightlim <- c(0, maxi*1.1) } } ## PLOT for SAMPLES 1 and 2 #par(xpd=TRUE, mar=par()$mar+c(0,0,2,0)) plot.y2(x = satura1$seq.depth/10^6, yright = newdet1, yleft = satura1$noceros, type = c("h", "o"), lwd = c(20,2), pch = c(1, 19), yrightlim = yrightlim, yleftlim = yleftlim, xlim = c(xm, xM), main = tit, xlab = "Sequencing Depth (million reads)", col = c("pink", 2), yylab = c("New detections per million reads", paste("Number of features with reads >", k)), cex2 = c(1.5,1.5), cex.main = cex.main, cex.lab = cex.lab, cex.axis = cex.axis, x2 = satura2$seq.depth/10^6, yright2 = newdet2, yleft2 = satura2$noceros, col2 = c("lightblue1", 4)) legend.text <- c(paste(legend[1], "(left axis)"), paste(legend[2], "(left axis)"), paste(legend[1], "(right axis)"), paste(legend[2], "(right axis)")) legend.pch <- c(16, 16, 15, 15) legend.col <- c(2, 4, "pink", "lightblue1") legend("top", legend = legend.text, pch = legend.pch, col = legend.col, ncol = 2, bty = "n") par(mar=c(5, 4, 4, 2) + 0.1) # txt file for sample 1 and 2 mytxt <- cbind(satura1$seq.depth, satura1$noceros, newdet1, satura2$seq.depth, satura2$noceros, newdet2) colnames(mytxt) <- c("depth1", "detec1", "newdetec1", "depth2", "detec2", "newdetec2") write.table(mytxt, file = myoutput, quote = FALSE, col.names = TRUE, row.names = FALSE, sep = "\t") } else { ## 1 sample ## PLOT LIMITS # yleftlim for plot.y2 if (is.null(yleftlim)) { yleftlim <- c(0, NROW(datos1)) } # xlim xlim <- range(satura1$seq.depth/10^6) # yrightlim for plot.y2 if (is.null(yrightlim)) { maxi <- max(na.omit(newdet1)) if (maxi < 10) { yrightlim <- c(0, max(10,maxi)) } else { yrightlim <- c(0, maxi*1.1) } } ## PLOT for SAMPLE 1 plot.y2(x = satura1$seq.depth/10^6, yright = newdet1, yleft = satura1$noceros, type = c("h", "o"), lwd = c(20,2), pch = c(1, 19), yrightlim = yrightlim, yleftlim = yleftlim, xlim = xlim, main = tit, xlab = "Sequencing Depth (million reads)", col = c("pink", 2), yylab = c("New detections per million reads", paste("Number of features with reads >", k)), cex = c(1.5,1.5), cex.main = cex.main, cex.lab = cex.lab, cex.axis = cex.axis) legend.text <- c("Left axis", "Right axis") legend.pch <- c(16, 15) legend.col <- c(2, "pink") legend("top", legend = legend.text, pch = legend.pch, col = legend.col, ncol = 2, bty = "n") par(mar=c(5, 4, 4, 2) + 0.1) # txt file for sample 1 mytxt <- cbind(satura1$seq.depth, satura1$noceros, newdet1) colnames(mytxt) <- c("depth1", "detec1", "newdetec1") write.table(mytxt, file = myoutput, quote = FALSE, col.names = TRUE, row.names = FALSE, sep = "\t") } } #***************************************************************************# ## Correlation plot between two samples cor.plot <- function(datos1, datos2, log.scale = FALSE, ...) { if (log.scale) { datos1 <- log2(datos1 + 1) datos2 <- log2(datos2 + 1) } plot(datos1, datos2,...) coefLR <- summary(lm(datos2~datos1))$coefficients[,"Estimate"] abline(a = coefLR[1], b = coefLR[2], col = 2, lwd = 2) mycor <- cor(datos1, datos2) myR2 <- round(100*mycor^2,2) my.y <- min(datos2)+0.1*diff(range(datos2)) text(max(datos1), my.y, paste("y =", round(coefLR[1],3), "+", round(coefLR[2],3), "x"), col = 2, adj = 1) text(max(datos1), my.y-0.05*diff(range(datos2)), paste("R2 =", myR2, "%"), col = 2, adj = 1) } ## Function filled.contour with legend filled.contour <- function (x = seq(0, 1, length.out = nrow(z)), y = seq(0, 1, length.out = ncol(z)), z, xlim = range(x, finite = TRUE), ylim = range(y, finite = TRUE), zlim = range(z, finite = TRUE), levels = pretty(zlim, nlevels), nlevels = 20, color.palette = cm.colors, col = color.palette(length(levels) - 1), plot.title, plot.axes, key.title, key.axes, asp = NA, xaxs = "i", yaxs = "i", las = 1, axes = TRUE, frame.plot = axes, key.border = NA, ...) { if (missing(z)) { if (!missing(x)) { if (is.list(x)) { z <- x$z y <- x$y x <- x$x } else { z <- x x <- seq.int(0, 1, length.out = nrow(z)) } } else stop("no 'z' matrix specified") } else if (is.list(x)) { y <- x$y x <- x$x } if (any(diff(x) <= 0) || any(diff(y) <= 0)) stop("increasing 'x' and 'y' values expected") mar.orig <- (par.orig <- par(c("mar", "las", "mfrow")))$mar on.exit(par(par.orig)) w <- (3 + mar.orig[2L]) * par("csi") * 2.54 layout(matrix(c(2, 1), ncol = 2L), widths = c(1, lcm(w))) par(las = las) mar <- mar.orig mar[4L] <- mar[2L] mar[2L] <- 1 par(mar = mar) plot.new() plot.window(xlim = c(0, 1), ylim = range(levels), xaxs = "i", yaxs = "i") rect(0, levels[-length(levels)], 1, levels[-1L], col = col, border=key.border) if (missing(key.axes)) { if (axes) axis(4) } else key.axes box() if (!missing(key.title)) key.title mar <- mar.orig mar[4L] <- 1 par(mar = mar) plot.new() plot.window(xlim, ylim, "", xaxs = xaxs, yaxs = yaxs, asp = asp) if (!is.matrix(z) || nrow(z) <= 1L || ncol(z) <= 1L) stop("no proper 'z' matrix specified") if (!is.double(z)) storage.mode(z) <- "double" if (R.Version()$major > 2) { .filled.contour(as.double(x), as.double(y), z, as.double(levels), col = col) } else { .Internal(filledcontour(as.double(x), as.double(y), z, as.double(levels), col = col)) } if (missing(plot.axes)) { if (axes) { title(main = "", xlab = "", ylab = "") Axis(x, side = 1) Axis(y, side = 2) } } else plot.axes if (frame.plot) box() if (missing(plot.title)) title(...) else plot.title invisible() } ## Contour plot for correlation #library(colorRamps) cor.plot.2D <- function(datos1, datos2, noplot = 0.01, log.scale = TRUE,...) { nozeros <- which(rowSums(cbind(datos1, datos2)) > 0) datos1 <- datos1[nozeros] datos2 <- datos2[nozeros] mycor <- round(cor(datos1, datos2),3) if (log.scale) { datos1 <- log2(datos1 + 1) datos2 <- log2(datos2 + 1) } library(MASS) limx <- quantile(datos1, c(noplot, 1-noplot)) limy <- quantile(datos2, c(noplot, 1-noplot)) d <- kde2d(datos1, datos2, n=100, lims=c(limx, limy)) filled.contour(d, color.palette = topo.colors, main = paste("Pearson's correlation coefficient =", mycor), n=100, key.title = title(main="Density"), key.axes = axis(4),...) }
R
2D
mitenjain/nanopore
submodules/qualimap/scripts/installDependencies.r
.r
536
26
#installing deps if(!require("optparse")) { install.packages("optparse", repos = "http://cran.r-project.org") } if(!require("XML")) { install.packages("XML", repos = "http://cran.r-project.org") } if(!require("Repitools")) { source("http://bioconductor.org/biocLite.R") biocLite("Repitools") } if(!require("Rsamtools")) { source("http://bioconductor.org/biocLite.R") biocLite("Rsamtools") } if(!require("rtracklayer")) { source("http://bioconductor.org/biocLite.R") biocLite("rtracklayer") }
R
2D
mitenjain/nanopore
submodules/qualimap/scripts/parseConfig.r
.r
6,967
234
#if(!require("XML",quietly=T)) { install.packages("XML", repos = "http://cran.r-project.org") } suppressPackageStartupMessages(library("XML",quietly=T)) checkChild <- function(node,name, fileXML="fileConfig"){ if(is.null(node[[name]])){ stop(paste("Node <", as.character(xmlName(node)), "> does not have a child <", name, "> in ", fileXML,sep="")) } } #hasChild <- function(node, name, fileXML="fileConfig") { # if (is.null(node[[name]])) { # return TRUE; # } else { # return FALSE; # } #} parseReplicate <- function(replicate){ checkChild(replicate, "medips") medips = as.character(xmlValue(replicate[["medips"]])) input = as.character(xmlValue(replicate[["input"]])) name = as.character(xmlValue(replicate[["name"]])) d <- data.frame(medips=medips,input=input,name=name) d } parseSample <- function(sample,ord.sample=0){ #print(xmlName(sample)) sample.name <- if(!is.null(xmlAttrs(sample)["name"])) as.character(xmlAttrs(sample)["name"]) else paste("","") #print(sample.name) checkChild(sample, "replicate") parsedMedips <- c() parsedInput <- c() parsedName <- c() i <- 1 for(curRep in xmlChildren(sample)){ if(xmlName(curRep) == "replicate"){ d <- parseReplicate(curRep) #print(as.character(d$medips)) #print(as.character(d$input)) parsedMedips <- c(parsedMedips,as.character(d$medips)) parsedInput <- c(parsedInput,as.character(d$input)) parsedName <- if(!is.na(d$name)) c(parsedName,as.character(d$name)) else c(parsedName, paste(sample.name,as.character(i),sep="_")) i <- i + 1 } } parsed <- data.frame(medips=parsedMedips, input=parsedInput, sample.name=sample.name, replicate.name=parsedName) parsed } parseLocation <- function(pos){ ch.pos <- xmlChildren(pos) #threshold <- if (!is.null(ch.ma[["threshold"]])) xmlValue(ch.ma[["threshold"]]) else NA up <- if (!is.null(ch.pos[["up"]])) xmlValue(ch.pos[["up"]]) else 2000 down <- if (!is.null(ch.pos[["down"]])) xmlValue(ch.pos[["down"]]) else 500 freq <- if (!is.null(ch.pos[["freq"]])) xmlValue(ch.pos[["freq"]]) else 100 d <- data.frame(up=up, down=down, freq=freq) d } parseMicroarray <- function(ma){ #print(xmlName(ma)) checkChild(ma, "file") ch.ma <- xmlChildren(ma) parsedTh <- c() for(th in xmlChildren(ma)){ if(xmlName(th)=="threshold"){ parsedTh <- c(parsedTh, xmlValue(th)) } } #threshold <- if (!is.null(ch.ma[["threshold"]])) xmlValue(ch.ma[["threshold"]]) else NA threshold <- if (!is.null(ch.ma[["threshold"]])) parsedTh else NA d <- data.frame(file=xmlValue(ch.ma[["file"]]), threshold=threshold) d } parseGeneSelection <- function(node){ checkChild(node, "file") ch.node <-xmlChildren(node) column <- if (!is.null(ch.node[["column"]])) xmlValue(ch.node[["column"]]) else 1 d <- data.frame(file=xmlValue(ch.node[["file"]]), column=column) d } parseDirOut <- function(node){ d <- data.frame(dirOut=xmlValue(node)) d } parseRegions <- function(node){ d <- data.frame(regions=xmlValue(node)) d } parseFragment <- function(node){ d <- data.frame(fragment=xmlValue(node)) d } parseExpID <- function(node){ d <- data.frame(expID=xmlValue(node)) d } parseClusters <- function(cls){ checkChild(cls,"num") parsedNums <- c() for(cl in xmlChildren(cls)){ if(xmlName(cl)=="num"){ parsedNums <- c(parsedNums, xmlValue(cl)) } } d <- data.frame(num=parsedNums) #print(d) d } parseConfig <- function(fileXML){ if(!file.exists(fileXML)){ stop(paste("fileConfig ", fileXML, "does not exist")) } r <- xmlRoot(xmlTreeParse(fileXML)) checkChild(r,"samples",fileXML) l.param <- xmlChildren(r) samples <-l.param[["samples"]] checkChild(samples,"sample1",fileXML) l.samples <- xmlChildren(samples) #if (hasChild(samples,"sample2",fileXML)) { # df.sample2 <- parseSample(l.samples[["sample2"]],ord.sample=2) #} df.sample1 <- parseSample(l.samples[["sample1"]],ord.sample=1) #print(df.sample1$medips) #print(df.sample1$input) #print(df.sample2$medips) #print(df.sample2$input) l.microarray <- l.param[["microarray"]] df.microarray <- if(!is.null(l.microarray)) parseMicroarray(l.microarray) else NULL l.geneSelection <- l.param[["geneSelection"]] df.geneSelection <- if(!is.null(l.geneSelection)) parseGeneSelection(l.geneSelection) else NULL checkChild(r,"regions",fileXML) l.regions <- l.param[["regions"]] df.regions <- if(!is.null(l.regions)) parseRegions(l.regions) else NULL l.dirOut <- l.param[["dirOut"]] df.dirOut <- if(!is.null(l.dirOut)) parseDirOut(l.dirOut) else NULL l.expID <- l.param[["expID"]] df.expID <- if(!is.null(l.expID)) parseExpID(l.expID) else NULL if(!is.null(l.param[["clusters"]])){ clusters <- l.param[["clusters"]] l.clusters <- xmlChildren(clusters) df.clusters <- parseClusters(clusters) }else{ df.clusters <- NULL } l.location <- l.param[["location"]] df.location <- if(!is.null(l.location)) parseLocation(l.location) else NULL l.fragment <- l.param[["fragment"]] df.fragment <- if(!is.null(l.fragment)) parseFragment(l.fragment) else NULL parsed <- matrix(list(), nrow=1, ncol=10) #colnames(parsed) <- c("sample1", "sample2", "clusters", "microarray","geneSelection","dirOut","expID","location","fragment") colnames(parsed) <- c("sample1", "mr.empty", "clusters", "microarray","geneSelection","dirOut","expID","location","fragment","regions") #print(df.geneSelection) parsed[[1,"sample1"]] <- df.sample1 #parsed[[1,"sample2"]] <- df.sample2 parsed[[1,"clusters"]] <- if (!is.null(df.clusters)) df.clusters else NA parsed[[1,"microarray"]] <- if (!is.null(df.microarray)) df.microarray else NA parsed[[1,"regions"]] <- df.regions parsed[[1,"geneSelection"]] <- if(!is.null(df.geneSelection)) df.geneSelection else NA parsed[[1,"dirOut"]] <- if(!is.null(df.dirOut)) df.dirOut else NA parsed[[1,"expID"]] <- if(!is.null(df.expID)) df.expID else NA parsed[[1,"location"]] <- if(!is.null(df.location)) df.location else NA parsed[[1,"fragment"]] <- if(!is.null(df.fragment)) df.fragment else NA #parsed <- data.frame(sample1=df.sample1, sample2=df.sample2,microarray=microarray) parsed } unParseDF <- function(d,names){ # d is a data.frame. For example args[[1,"sample1"]] # names is a list of fields to be unparsed. For example c("medips","input","name") # Returns a matrix with as many rows as values and as many column as fields # Example: sample1 <- unParseDF(args[[1,"sample1"]], c("medips","input","name")) mat <- t(apply(d,1,unParseDataFrameLine,names)) # transposition to have rows as samples and columns as "medips","input","name" mat } unParseDataFrameLine <- function(l,names){ # Auxiliar function used by unParseDF so one can use it in apply() # It interrogates the columns selected in names of the line l and creates a list with them ret <- c() for(i in 1:length(names)){ ret <- c(ret,l[names[i]]) } ret }
R
2D
mitenjain/nanopore
scripts/modifyHmm.py
.py
1,264
35
###Modify HMMs output from EM training to normalise for background nucleotide frequencies. from cactus.bar.cactus_expectationMaximisation import Hmm, SYMBOL_NUMBER import sys from nanopore.analyses.utils import setHmmIndelEmissionsToBeFlat, normaliseHmmByReferenceGCContent, modifyHmmEmissionsByExpectedVariationRate, toMatrix import numpy as np def main(): print "ARGS", sys.argv #Load HMM hmm = Hmm.loadHmm(sys.argv[1]) #setHmmIndelEmissionsToBeFlat(hmm) #Normalise background emission frequencies, if requested to GC% given gcContent = float(sys.argv[2]) print "Got GC content", gcContent normaliseHmmByReferenceGCContent(hmm, gcContent) #Modify match emissions by proposed substitution rate substitutionRate = float(sys.argv[3]) print "Got substitution rate", substitutionRate modifyHmmEmissionsByExpectedVariationRate(hmm, substitutionRate) for state in range(0, hmm.stateNumber): n = toMatrix(hmm.emissions[(SYMBOL_NUMBER**2) * state:(SYMBOL_NUMBER**2) * (state+1)]) print "For state, ref frequencies", map(sum, n) print "For state, read frequencies", map(sum, np.transpose(n)) #Write out HMM hmm.write(sys.argv[4]) if __name__ == '__main__': main()
Python
2D
mitenjain/nanopore
scripts/combine_plots_remove_trends.R
.R
6,605
109
#!/usr/bin/env Rscript args <- commandArgs(trailingOnly = T) #thanks SO: http://stackoverflow.com/questions/6602881/text-file-to-list-in-r raw1 <- strsplit(readLines(args[1]), "[[:space:]]+") data1 <- lapply(raw1, tail, n = -1) names(data1) <- lapply(raw1, head, n = 1) data1 <- lapply(data1, as.numeric) pdf(args[2]) library(lattice) data <- list() data$MappedReadLengths <- data1$length data$MismatchesPerReadBase <- data1$mismatches data$ReadIdentity <- data1$identity data$DeletionsPerBase <- data1$deletions data$InsertionsPerBase <- data1$insertions #filter out any read identities that are outside of 3 sd's from mean for fit lines #but still plot the points id.inliers <- which(data$ReadIdentity >= mean(data$ReadIdentity) - 2 * sd(data$ReadIdentity) & data$ReadIdentity <= mean(data$ReadIdentity) + 2 * sd(data$ReadIdentity)) len.inliers <- which(data$MappedReadLengths >= mean(data$MappedReadLengths) - 2 * sd(data$MappedReadLengths) & data$MappedReadLengths <= mean(data$MappedReadLengths) + 2 * sd(data$MappedReadLengths)) mismatches.inliers <- which(data$MismatchesPerReadBase >= mean(data$MismatchesPerReadBase) - 2 * sd(data$MismatchesPerReadBase) & data$MismatchesPerReadBase <= mean(data$MismatchesPerReadBase) + 2 * sd(data$MismatchesPerReadBase)) deletions.inliers <- which(data$DeletionsPerBase >= mean(data$DeletionsPerBase) - 2 * sd(data$DeletionsPerBase) & data$DeletionsPerBase <= mean(data$DeletionsPerBase) + 2 * sd(data$DeletionsPerBase)) insertions.inliers <- which(data$InsertionsPerBase >= mean(data$InsertionsPerBase) - 2 * sd(data$InsertionsPerBase) & data$InsertionsPerBase <= mean(data$InsertionsPerBase) + 2 * sd(data$InsertionsPerBase)) inliers <- intersect(insertions.inliers, intersect(deletions.inliers, intersect(mismatches.inliers, intersect(id.inliers, len.inliers)))) p1 <- xyplot(data$ReadIdentity~data$MappedReadLengths, main=list("Read Identity vs.\nRead Length", cex=0.95), xlab="Read Length", ylab="Read Identity", grid=T, panel=function(...){ panel.smoothScatter(...)}) #panel.abline(lwd=1.2, lm(data$ReadIdentity[inliers]~data$MappedReadLengths[inliers])) #}, #key=simpleKey(paste("R^2 =", as.character(round(summary.lm( #lm(data$ReadIdentity[inliers]~data$MappedReadLengths[inliers]))$adj.r.squared,3)), sep=" "), #points=F, corner=c(1,1), cex=0.9)) p2 <- xyplot((data$InsertionsPerBase+data$DeletionsPerBase)~data$MappedReadLengths, main=list("Indels Per Aligned Base vs.\nRead Length", cex=0.95), xlab="Read Length", ylab="Indels Per Base", grid=T, panel=function(...){ panel.smoothScatter(...)}) #panel.abline(lwd=1.2, lm((data$InsertionsPerBase+data$DeletionsPerBase)[inliers]~data$MappedReadLengths[inliers])) #}, #key=simpleKey(paste("R^2 =", as.character(round(summary.lm( #lm((data$InsertionsPerBase+data$DeletionsPerBase)[inliers]~data$MappedReadLengths[inliers]))$adj.r.squared,3)), sep=" "), #points=F, corner=c(1,1), cex=0.9)) p3 <- xyplot(data$MismatchesPerReadBase~data$MappedReadLengths, main=list("Mismatches Per Aligned Base vs.\nRead Length", cex=0.95), ylab="Mismatches Per Aligned Base", xlab="Read Length", grid=T, panel=function(...){ panel.smoothScatter(...)}) #panel.abline(lwd=1.2, lm(data$MismatchesPerReadBase[inliers]~data$MappedReadLengths[inliers])) #}, #key=simpleKey(paste("R^2 =", as.character(round(summary.lm( #lm(data$MismatchesPerReadBase[inliers]~data$MappedReadLengths[inliers]))$adj.r.squared,3)), sep=" "), #points=F, corner=c(1,1), cex=0.9)) #print the graphs print(p1, position=c(0, 0.5, 0.5, 1), more=T) print(p2, position=c(0.5, 0.5, 1, 1), more=T) print(p3, position=c(0, 0, 0.5, 0.5)) #now time to do more graphs p1 <- xyplot(data$MismatchesPerReadBase~(data$InsertionsPerBase+data$DeletionsPerBase), main=list("Mismatches Per Aligned Base vs.\nIndels Per Aligned Base", cex=0.95), xlab="Indels Per Aligned Base", ylab="Mismatches Per Aligned Base", grid=T, panel=function(...){ panel.smoothScatter(...) panel.abline(lwd=1.2, lm(data$MismatchesPerReadBase[inliers]~(data$InsertionsPerBase+data$DeletionsPerBase)[inliers])) }, key=simpleKey(paste("R^2 =", as.character(round(summary.lm( lm(data$MismatchesPerReadBase~(data$InsertionsPerBase+data$DeletionsPerBase)))$adj.r.squared,3)), sep=" "), points=F, corner=c(0,1), cex=0.9)) p2 <- xyplot((data$InsertionsPerBase+data$DeletionsPerBase)~data$ReadIdentity, main=list("Indels Per Aligned Base vs.\nRead Identity", cex=0.95), xlab="Read Identity", ylab="Indels Per Base", grid=T, panel=function(...){ panel.smoothScatter(...) panel.abline(lwd=1.2, lm((data$InsertionsPerBase+data$DeletionsPerBase)[inliers]~data$ReadIdentity[inliers])) }, key=simpleKey(paste("R^2 =", as.character(round(summary.lm( lm((data$InsertionsPerBase+data$DeletionsPerBase)~data$ReadIdentity))$adj.r.squared,3)), sep=" "), points=F, corner=c(1,1), cex=0.9)) p3 <- xyplot(data$MismatchesPerReadBase~data$ReadIdentity, main=list("Mismatches Per Aligned Base vs.\nRead Identity",cex=0.95), ylab="Mismatches Per Aligned Base", xlab="Read Identity", grid=T, panel=function(...){ panel.smoothScatter(...) panel.abline(lwd=1.2, lm(data$MismatchesPerReadBase[inliers]~data$ReadIdentity[inliers])) }, key=simpleKey(paste("R^2 =", as.character(round(summary.lm( lm((data$InsertionsPerBase+data$DeletionsPerBase)~data$ReadIdentity))$adj.r.squared,3)), sep=" "), points=F, corner=c(1,0), cex=0.9)) p4 <- xyplot(data$InsertionsPerBase~data$DeletionsPerBase, main=list("Insertions Per Aligned Base vs.\nDeletions Per Aligned Base",cex=0.95), xlab="Deletions Per Aligned Base", ylab="Insertions Per Aligned Base", grid=T, panel=function(...){ panel.smoothScatter(...) panel.abline(lwd=1.2, lm(data$InsertionsPerBase[inliers]~data$DeletionsPerBase[inliers])) }, key=simpleKey(paste("R^2 =", as.character(round(summary.lm( lm(data$InsertionsPerBase~data$DeletionsPerBase))$adj.r.squared,3)), sep=" "), points=F, corner=c(1,1), cex=0.9)) #print the graphs print(p1, position=c(0, 0.5, 0.5, 1), more=T) print(p2, position=c(0.5, 0.5, 1, 1), more=T) print(p3, position=c(0, 0, 0.5, 0.5), more=T) print(p4, position=c(0.5, 0, 1, 0.5)) dev.off()
R
2D
mitenjain/nanopore
scripts/fast_pull_averages.py
.py
1,757
57
import xml.etree.cElementTree as ET import sys def find_values(f1, f2, f3): f1 = ET.parse(f1).getroot() f2 = ET.parse(f2).getroot() f3 = ET.parse(f3).getroot() m1 = float(f1.attrib['avgmismatchesPerReadBase']) m2 = float(f2.attrib['avgmismatchesPerReadBase']) m3 = float(f3.attrib['avgmismatchesPerReadBase']) mismatches = str((m1+m2+m3)/3) insert1 = float(f1.attrib['avginsertionsPerReadBase']) insert2 = float(f2.attrib['avginsertionsPerReadBase']) insert3 = float(f3.attrib['avginsertionsPerReadBase']) inserts = str((insert1+insert2+insert3)/3) del1 = float(f1.attrib['avgdeletionsPerReadBase']) del2 = float(f2.attrib['avgdeletionsPerReadBase']) del3 = float(f3.attrib['avgdeletionsPerReadBase']) deletes = str((del1+del2+del3)/3) i1 = float(f1.attrib['avgidentity']) i2 = float(f2.attrib['avgidentity']) i3 = float(f3.attrib['avgidentity']) identity = str((i1+i2+i3)/3) return mismatches, identity, inserts, deletes results = {} for l in open(sys.argv[1]): l = l.rstrip() #analysis = l.split("analysis_")[1].split("/")[0] mapper = l.split(".fa_")[1].split("/")[0] if mapper not in results: results[mapper] = [] results[mapper].append(l) for mapper in results: f1, f2, f3 = results[mapper] results[mapper] = find_values(f1, f2, f3) with open(sys.argv[2],"w") as f: f.write("mapper\tavgMismatch\tavgIdentity\tAvgInsert\tAvgDelete\n") for mapper, [mismatches, identity, inserts, delete] in sorted(results.iteritems(), key = lambda x:x[0]): if "Realign" in mapper and "Em" not in mapper: continue else: f.write("\t".join([mapper, mismatches, identity, inserts, delete])+"\n")
Python
2D
mitenjain/nanopore
scripts/mappability_plots.R
.R
9,667
140
library(lattice) library(latticeExtra) pdf("combined_plots_channel_mappability.pdf")#, type="cairo") #below is hard coded positions on the nanopore labels <- c(125, 126, 127, 128, 253, 254, 255, 256, 381, 382, 383, 384, 509, 510, 511, 512, 121, 122, 123, 124, 249, 250, 251, 252, 377, 378, 379, 380, 505, 506, 507, 508, 117, 118, 119, 120, 245, 246, 247, 248, 373, 374, 375, 376, 501, 502, 503, 504, 113, 114, 115, 116, 241, 242, 243, 244, 369, 370, 371, 372, 497, 498, 499, 500, 109, 110, 111, 112, 237, 238, 239, 240, 365, 366, 367, 368, 493, 494, 495, 496, 105, 106, 107, 108, 233, 234, 235, 236, 361, 362, 363, 364, 489, 490, 491, 492, 101, 102, 103, 104, 229, 230, 231, 232, 357, 358, 359, 360, 485, 486, 487, 488, 97, 98, 99, 100, 225, 226, 227, 228, 353, 354, 355, 356, 481, 482, 483, 484, 93, 94, 95, 96, 221, 222, 223, 224, 349, 350, 351, 352, 477, 478, 479, 480, 89, 90, 91, 92, 217, 218, 219, 220, 345, 346, 347, 348, 473, 474, 475, 476, 85, 86, 87, 88, 213, 214, 215, 216, 341, 342, 343, 344, 469, 470, 471, 472, 81, 82, 83, 84, 209, 210, 211, 212, 337, 338, 339, 340, 465, 466, 467, 468, 77, 78, 79, 80, 205, 206, 207, 208, 333, 334, 335, 336, 461, 462, 463, 464, 73, 74, 75, 76, 201, 202, 203, 204, 329, 330, 331, 332, 457, 458, 459, 460, 69, 70, 71, 72, 197, 198, 199, 200, 325, 326, 327, 328, 453, 454, 455, 456, 65, 66, 67, 68, 193, 194, 195, 196, 321, 322, 323, 324, 449, 450, 451, 452, 61, 62, 63, 64, 189, 190, 191, 192, 317, 318, 319, 320, 445, 446, 447, 448, 57, 58, 59, 60, 185, 186, 187, 188, 313, 314, 315, 316, 441, 442, 443, 444, 53, 54, 55, 56, 181, 182, 183, 184, 309, 310, 311, 312, 437, 438, 439, 440, 49, 50, 51, 52, 177, 178, 179, 180, 305, 306, 307, 308, 433, 434, 435, 436, 45, 46, 47, 48, 173, 174, 175, 176, 301, 302, 303, 304, 429, 430, 431, 432, 41, 42, 43, 44, 169, 170, 171, 172, 297, 298, 299, 300, 425, 426, 427, 428, 37, 38, 39, 40, 165, 166, 167, 168, 293, 294, 295, 296, 421, 422, 423, 424, 33, 34, 35, 36, 161, 162, 163, 164, 289, 290, 291, 292, 417, 418, 419, 420, 29, 30, 31, 32, 157, 158, 159, 160, 285, 286, 287, 288, 413, 414, 415, 416, 25, 26, 27, 28, 153, 154, 155, 156, 281, 282, 283, 284, 409, 410, 411, 412, 21, 22, 23, 24, 149, 150, 151, 152, 277, 278, 279, 280, 405, 406, 407, 408, 17, 18, 19, 20, 145, 146, 147, 148, 273, 274, 275, 276, 401, 402, 403, 404, 13, 14, 15, 16, 141, 142, 143, 144, 269, 270, 271, 272, 397, 398, 399, 400, 9, 10, 11, 12, 137, 138, 139, 140, 265, 266, 267, 268, 393, 394, 395, 396, 5, 6, 7, 8, 133, 134, 135, 136, 261, 262, 263, 264, 389, 390, 391, 392, 1, 2, 3, 4, 129, 130, 131, 132, 257, 258, 259, 260, 385, 386, 387, 388) template1 <- read.table("/hive/users/benedict/nanoporeM13/nanopore/output/analysis_template/experiment_DD_575_R7.3_His_M13_11_21_14_R7.X_2D_V1.9_pass_template.fastq_combinedReference.fa_LastParamsRealignEm/analysis_ChannelMappability/channel_mappability.tsv", row.names=1, header=T) template2 <- read.table("/hive/users/benedict/nanoporeM13/nanopore/output/analysis_template/experiment_DD_575_R7.3_M13_His_11_17_14_R7.X_2D_V1.9_pass_template.fastq_combinedReference.fa_LastParamsRealignEm/analysis_ChannelMappability/channel_mappability.tsv", row.names=1, header=T) template3 <- read.table("/hive/users/benedict/nanoporeM13/nanopore/output/analysis_template/experiment_MA_286_R7.3_His_M13_11_18_14_R7.X_2D_V1.9_pass_template.fastq_combinedReference.fa_LastParamsRealignEm/analysis_ChannelMappability/channel_mappability.tsv", row.names=1, header=T) complement1 <- read.table("/hive/users/benedict/nanoporeM13/nanopore/output/analysis_complement/experiment_DD_575_R7.3_His_M13_11_21_14_R7.X_2D_V1.9_pass_complement.fastq_combinedReference.fa_LastParamsRealignEm/analysis_ChannelMappability/channel_mappability.tsv", row.names=1, header=T) complement2 <- read.table("/hive/users/benedict/nanoporeM13/nanopore/output/analysis_complement/experiment_DD_575_R7.3_M13_His_11_17_14_R7.X_2D_V1.9_pass_complement.fastq_combinedReference.fa_LastParamsRealignEm/analysis_ChannelMappability/channel_mappability.tsv", row.names=1, header=T) complement3 <- read.table("/hive/users/benedict/nanoporeM13/nanopore/output/analysis_complement/experiment_MA_286_R7.3_His_M13_11_18_14_R7.X_2D_V1.9_pass_complement.fastq_combinedReference.fa_LastParamsRealignEm/analysis_ChannelMappability/channel_mappability.tsv", row.names=1, header=T) twod1 <- read.table("/hive/users/benedict/nanoporeM13/nanopore/output/analysis_2D/experiment_DD_575_R7.3_His_M13_11_21_14_R7.X_2D_V1.9_pass_2D.fastq_combinedReference.fa_LastParamsRealignEm/analysis_ChannelMappability/channel_mappability.tsv", row.names=1, header=T) twod2 <- read.table("/hive/users/benedict/nanoporeM13/nanopore/output/analysis_2D/experiment_DD_575_R7.3_M13_His_11_17_14_R7.X_2D_V1.9_pass_2D.fastq_combinedReference.fa_LastParamsRealignEm/analysis_ChannelMappability/channel_mappability.tsv", row.names=1, header=T) twod3 <- read.table("/hive/users/benedict/nanoporeM13/nanopore/output/analysis_2D/experiment_MA_286_R7.3_His_M13_11_18_14_R7.X_2D_V1.9_pass_2D.fastq_combinedReference.fa_LastParamsRealignEm/analysis_ChannelMappability/channel_mappability.tsv", row.names=1, header=T) data <- cbind(template1, template2, template3, complement1, complement2, complement3, twod1, twod2, twod3) #first all read counts counts <- list() largest <- 0 for (i in seq(1, dim(data)[2], 2)) { positions <- labels for (j in 1:length(positions)) { positions[match(c(j), positions)] <- data[j,i] } counts[[ceiling(i/2)]] <- matrix(positions, nrow=16) largest <- max(largest, max(positions)) } b <- seq(1, largest+10, by=round(largest/30)) rotate <- function(x) t(apply(x, 2, rev)) t1 <- levelplot(rotate(counts[[1]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) t2 <- levelplot(rotate(counts[[2]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) t3 <- levelplot(rotate(counts[[3]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) c1 <- levelplot(rotate(counts[[4]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) c2 <- levelplot(rotate(counts[[5]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) c3 <- levelplot(rotate(counts[[6]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) w1 <- levelplot(rotate(counts[[7]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) w2 <- levelplot(rotate(counts[[8]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) w3 <- levelplot(rotate(counts[[9]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) plots <- c(t1, t2, t3, c1, c2, c3, w1, w2, w3) print(plots) #now it is time to do mappable read counts counts <- list() largest <- 0 for (i in seq(2, dim(data)[2], 2)) { #this is the only change positions <- labels for (j in 1:length(positions)) { positions[match(c(j), positions)] <- data[j,i] } counts[[ceiling(i/2)]] <- matrix(positions, nrow=16) largest <- max(largest, max(positions)) } b <- seq(1, largest+10, by=round(largest/30)) rotate <- function(x) t(apply(x, 2, rev)) t1 <- levelplot(rotate(counts[[1]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) t2 <- levelplot(rotate(counts[[2]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) t3 <- levelplot(rotate(counts[[3]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) c1 <- levelplot(rotate(counts[[4]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) c2 <- levelplot(rotate(counts[[5]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) c3 <- levelplot(rotate(counts[[6]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) w1 <- levelplot(rotate(counts[[7]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) w2 <- levelplot(rotate(counts[[8]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) w3 <- levelplot(rotate(counts[[9]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) plots <- c(t1, t2, t3, c1, c2, c3, w1, w2, w3) print(plots) #finally, lets do the percentages counts <- list() largest <- 0 for (i in seq(1, dim(data)[2], 2)) { positions <- labels for (j in 1:length(positions)) { vals <- data[j, i]/data[j+1, i+1] vals[is.nan(vals)] <- 0 positions[match(c(j), positions)] <- vals } counts[[ceiling(i/2)]] <- matrix(positions, nrow=16) largest <- max(largest, max(positions)) } b <- seq(0, 1, 0.05) rotate <- function(x) t(apply(x, 2, rev)) t1 <- levelplot(rotate(counts[[1]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) t2 <- levelplot(rotate(counts[[2]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) t3 <- levelplot(rotate(counts[[3]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) c1 <- levelplot(rotate(counts[[4]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) c2 <- levelplot(rotate(counts[[5]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) c3 <- levelplot(rotate(counts[[6]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) w1 <- levelplot(rotate(counts[[7]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) w2 <- levelplot(rotate(counts[[8]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) w3 <- levelplot(rotate(counts[[9]]), col.regions=colorRampPalette(c("white","red"))(256), at=b) plots <- c(t1, t2, t3, c1, c2, c3, w1, w2, w3) print(plots) dev.off()
R
2D
mitenjain/nanopore
scripts/__init__.py
.py
0
0
null
Python
2D
mitenjain/nanopore
scripts/tex.py
.py
3,164
83
"""Lib for generating latex tables. """ def formatFloat(string, decimals=3): f = float(string) if f == 2147483647: return "NaN" return (("%." + str(decimals) + "f") % f)[1:] def writeDocumentPreliminaries(fileHandle): fileHandle.write("\\documentclass[10pt]{article}\n") fileHandle.write("\\pagenumbering{arabic}\n") fileHandle.write("\\pagestyle{plain}\n") fileHandle.write("\\usepackage{epsfig}\n") fileHandle.write("\\usepackage{url}\n") fileHandle.write("\\usepackage{rotating}\n") fileHandle.write("\\usepackage{multirow}\n") fileHandle.write("\\usepackage{color}\n") fileHandle.write("\\usepackage[table]{xcolor}\n") fileHandle.write("\\setlength{\\evensidemargin}{0in}\n") fileHandle.write("\\setlength{\\oddsidemargin}{0in}\n") fileHandle.write("\\setlength{\\marginparwidth}{1in}\n") fileHandle.write("\\setlength{\\textwidth}{6.5in}\n") fileHandle.write("\\setlength{\\topmargin}{-0.5in}\n") fileHandle.write("\\setlength{\\textheight}{9in}\n") fileHandle.write("\\begin{document}\n") def writeDocumentEnd(fileHandle): fileHandle.write("\\end{document}\n") def writePreliminaries(columnNumber, fileHandle): fileHandle.write("\\begin{sidewaystable}\n\\centering\n") fileHandle.write("\\begin{tabular}{" + ("c"*columnNumber) + "}\n") def writeEnd(fileHandle, tableLabel, caption): fileHandle.write("\\end{tabular}\n") fileHandle.write("\caption{%s}\n" % caption) fileHandle.write("\label{%s}\n" % tableLabel) fileHandle.write("\end{sidewaystable}\n\n") def writeLine(columnNumber, rowNumber, entries, fileHandle, trailingLines=1): updatedEntries = [] for name, x1, x2, y1, y2 in entries: columnNumber = y2 - y1 + 1 updatedEntries.append((y1, x1, x2, name, columnNumber, y2 - y1 == 0)) while y2 - y1 > 0: #Make multiple new entries: y1 += 1 updatedEntries.append((y1, x1, x2, "", columnNumber, y2 - y1 == 0)) updatedEntries.sort() #fileHandle.write("\hline\n") start = True currentRow = 0 row = [] for y1, x1, x2, name, columnNumber, cLine in updatedEntries: if y1 != currentRow: fileHandle.write(" \\\\ %s\n" % " ".join([ "\\cline{%i-%i}" % (x3+1, x4+1) for x3, x4 in row ])) currentRow = y1 row = [] else: if not start: fileHandle.write(" & ") else: start = False if cLine: row.append((x1, x2)) fileHandle.write("\multicolumn{%i}{c}{\multirow{%i}{*}{%s}}" % (x2-x1+1, columnNumber, name)) fileHandle.write(" \\\\\n") for i in xrange(trailingLines): fileHandle.write("\hline\n") def writeRow(entries, fileHandle): fileHandle.write("%s \\\\\n" % " & ".join(entries)) def writeFigure(fileHandle, imageFile, caption, label, width=10): fileHandle.write("\\clearpage\n") fileHandle.write("\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=%scm]{%s}\n\\caption{%s}\n\\label{%s}\n\\end{center}\n\\end{figure}\n\n" % (width, imageFile, caption, label))
Python
2D
mitenjain/nanopore
scripts/extract_from_multiple_coverage_xmls.py
.py
1,468
48
import xml.etree.cElementTree as ET import sys f1 = ET.parse(sys.argv[1]).getroot() f2 = ET.parse(sys.argv[2]).getroot() f3 = ET.parse(sys.argv[3]).getroot() lengths = list() identity = list() coverage = list() insertions = list() deletions = list() mismatches = list() outf = open(sys.argv[4],"w") for c in f1.getchildren(): lengths.append(c.attrib["readLength"]) identity.append(c.attrib["identity"]) insertions.append(c.attrib["insertionsPerReadBase"]) deletions.append(c.attrib["deletionsPerReadBase"]) mismatches.append(c.attrib["mismatchesPerReadBase"]) for c in f2.getchildren(): lengths.append(c.attrib["readLength"]) identity.append(c.attrib["identity"]) insertions.append(c.attrib["insertionsPerReadBase"]) deletions.append(c.attrib["deletionsPerReadBase"]) mismatches.append(c.attrib["mismatchesPerReadBase"]) for c in f3.getchildren(): lengths.append(c.attrib["readLength"]) identity.append(c.attrib["identity"]) insertions.append(c.attrib["insertionsPerReadBase"]) deletions.append(c.attrib["deletionsPerReadBase"]) mismatches.append(c.attrib["mismatchesPerReadBase"]) outf.write("length ") outf.write(" ".join(lengths)+"\n") outf.write("identity ") outf.write(" ".join(identity)+"\n") outf.write("insertions ") outf.write(" ".join(insertions)+"\n") outf.write("deletions ") outf.write(" ".join(deletions)+"\n") outf.write("mismatches ") outf.write(" ".join(mismatches)+"\n") outf.close()
Python
2D
mitenjain/nanopore
scripts/variantTable.py
.py
5,488
106
import sys from tex import * import xml.etree.ElementTree as ET import os.path fileHandle = open(sys.argv[1], 'w') writeDocumentPreliminaries(fileHandle) recall, precision, fscore = {}, {}, {} fileHandle2 = open(sys.argv[2], 'r') tableNumber=1 while 1: l = fileHandle2.readline() if l == '': break tokens = l.split() if len(tokens) == 0 or tokens[0] != "readType": continue writePreliminaries(6, fileHandle) mutFreq = [ 1, 5, 10, 20 ] for i in mutFreq: l = fileHandle2.readline().split() readType = l[0] mapper = l[1] algorithm = l[2] recall[i] = l[4:16][1::3] precision[i] = l[16:28][1::3] fscore[i] = l[28:40][1::3] def fn(x): return "%.2f" % (100*float(x)) #writeRow(("samples", "sequence", "\% mapped", "\% mapped and contiguous", "\% contigious that mapped"), fileHandle) writeLine(6, 1, (("SNV detection using %s reads" % readType, 0, 5, 0, 0),), fileHandle) writeLine(6, 2, (("Metric", 0, 0, 0, 1), ("Mut. Freq.", 1, 1, 0, 1), ("Coverage", 2, 5, 0, 0), ("30", 2, 2, 1, 1), ("60", 3, 3, 1, 1), ("120", 4, 4, 1, 1), ("ALL", 5, 5, 1, 1)), fileHandle) def makeLine(word, hash): line = [ (word, 0, 0, 0, len(mutFreq)-1)] for i in xrange(len(mutFreq)): line.append((str(mutFreq[i]), 1, 1, i, i)) for j in xrange(len(hash[mutFreq[i]])): line.append((fn(hash[mutFreq[i]][j]), j+2, j+2, i, i)) writeLine(6, len(mutFreq), line, fileHandle) makeLine("Recall", recall) makeLine("Precision", precision) makeLine("F-score", fscore) #Format the algorithm/mapper name if mapper == "BlasrParamsChain": mapperName = "tuned Blasr (run using the `-x pacbio' flags)" elif mapper == "LastParamsChain": mapperName = "tuned Last (run using the `-s 2 -T 0 -Q 0 -a 1' flags)" elif mapper == "BlasrParamsRealignTrainedModel40": mapperName = "trained Blasr (Blasr run using the `-x pacbio' flags, realignment done using the described trained EM model)" mapperDescription = [ ] if "marginAlign" in algorithm: mapperDescription.append("Variant calling was performed using posterior match probabilities to integrate over every possible read alignment to the mutated reference sequence, using the initial guide alignment to band the calculations.") else: mapperDescription.append("Variant calling was performed conditioned on the fixed input alignment.") if "ikelihood" in algorithm: mapperDescription.append("Variant calling used a trained substitution matrix to calculate the maximum likelihood base (see method description).") else: mapperDescription.append("Variant calling corresponds to choosing the maximum-frequency/expectation of a non-reference base.") if "cactus" in algorithm: mapperDescription.append("Cactus realignment done using its stock pair-HMM.") if "trained_0" in algorithm: mapperDescription.append("Posterior match probabilities calculated using the EM trained HMM model, without accounting for substitution differences between the given reference and true underlying reference.") if "trained_20" in algorithm: mapperDescription.append("Posterior match probabilities calculated using the EM trained HMM model, accounting for substitution differences between the mutated reference and true underlying reference, assuming 20\% divergence.") if "trained_40" in algorithm: mapperDescription.append("Posterior match probabilities calculated using the EM trained HMM model, accounting for substitution differences between the mutated reference and true underlying reference, assuming 40\% divergence.") mapperDescription.append("Variant calling results shown for a posterior base calling probability threshold that gives the optimal F-score.") mapperDescription.append("Mutation frequency is the approximate proportion of sites mutated in the reference to which reads where aligned, and for which variants were called.") mapperDescription.append("Coverage is the total length of reads sampled divided by the length of the reference. ALL corresponds to using all the reads for a given experiment.") mapperDescription.append("Results shown are across three replicate experiments, and, at each coverage value, three different samplings of the reads. Raw results are available in the supplementary spread-sheet.") writeEnd(fileHandle, "variantCallingTable%i" % tableNumber, "Variant calling on M13 using %s reads starting with the %s mapping algorithm. %s" % (readType, mapperName, " ".join(mapperDescription))) algorithmShrunk = "".join(algorithm.split("_")) caption = "Precision/recall curves showing variant calling performance for four different mutation frequencies: 1, 5, 10 and 20 percent. Variant calling performed using %s reads starting with the %s mapping algorithm. %s" % (readType, mapperName, " ".join(mapperDescription)) ##Write image writeFigure(fileHandle, os.path.join(sys.argv[3], "plots/%s%s/%sROCcurves.pdf" % (readType, mapper, algorithmShrunk)), caption, "variantCallingFigure%i" % tableNumber, width=15) tableNumber += 1 writeDocumentEnd(fileHandle) fileHandle2.close() fileHandle.close()
Python
2D
mitenjain/nanopore
scripts/make_scatter_plot.R
.R
779
20
args <- commandArgs(trailingOnly = T) data <- read.table(args[1],row.names=1,header=T) pdf(args[2]) col1 <- rgb(1,0,0,0.7) col2 <- rgb(0,1,0,0.7) col3 <- rgb(0,0,1,0.7) col4 <- rgb(0,0,0,0.7) cols <- c(rep(col1,3),rep(col2,3),rep(col3,3),rep(col4,3)) plot(data$AvgInsert+data$AvgDelete,data$avgMismatch,pch=c(15,16,17),col=cols,cex=1.5,ylab="Average Mismatch Rate",xlab="Average Indel Rate",main="Mismatch vs. Indel") legend("topright",legend=rownames(data),pch=c(15,16,17),col=cols,cex=0.7) plot(data$AvgInsert,data$AvgDelete,pch=c(15,16,17),col=cols,cex=1.5,ylab="Avg Deleletions Per Aligned Read Base",xlab="Average Insertions Per Aligned Read Base",main="Insertions vs. Deletions") legend("bottomright",legend=rownames(data),pch=c(15,16,17),col=cols,cex=0.7) dev.off()
R
2D
mitenjain/nanopore
scripts/run_blast.sh
.sh
646
22
#!/bin/bash maxThreads=20 batchSystem=parasol defaultJobMemory=8589934592 if [ -e ./jobTree ]; then rm -rf ./jobTree fi if [ -z "$BLASTDB" ]; then echo "Error: environmental variable BLASTDB is not set. Cannot BLAST." exit 1 fi #Set the python path to just these local directories export PYTHONPATH=:../:../submodules:${PYTHONPATH} #Preferentially put the local binaries at the front of the path export PATH=:../submodules/jobTree/bin:./submodules/muscle/:${PATH}: python blast_combined/blast_combined.py --batchSystem=$batchSystem --jobTree=jobTree --defaultMemory=$defaultJobMemory --logInfo --logLevel INFO --stats &> log.txt
Shell
2D
mitenjain/nanopore
scripts/run_muscle.sh
.sh
1,064
51
#!/bin/bash while [[ $# > 1 ]] do key="$1" shift case $key in --template_sam) TEMPLATE_SAM="$1" shift ;; --twoD_sam) TWOD_SAM="$1" shift ;; --complement_sam) COMPLEMENT_SAM="$1" shift ;; esac done if [ ! -e $COMPLEMENT_SAM ]; then echo "$COMPLEMENT_SAM does not exist" exit 1 fi if [ ! -e $TEMPLATE_SAM ]; then echo "$TEMPLATE_SAM does not exist" exit 1 fi if [ ! -e $TWOD_SAM ]; then echo "$TWOD_SAM does not exist" exit 1 fi if [ -e ./jobTree ]; then rm -rf ./jobTree fi maxThreads=4 batchSystem=parasol defaultJobMemory=8589934592 #Set the python path to just these local directories export PYTHONPATH=:../:../submodules:${PYTHONPATH} #Preferentially put the local binaries at the front of the path export PATH=:../submodules/jobTree/bin:./submodules/muscle/:${PATH}: python muscle_compare_2d/muscle_compare_2d.py $TEMPLATE_SAM $COMPLEMENT_SAM $TWOD_SAM --batchSystem=$batchSystem --jobTree=jobTree --defaultMemory=$defaultJobMemory --logInfo --logLevel INFO --stats &> log.txt
Shell
2D
mitenjain/nanopore
scripts/combined_plots.R
.R
6,457
109
#!/usr/bin/env Rscript args <- commandArgs(trailingOnly = T) #thanks SO: http://stackoverflow.com/questions/6602881/text-file-to-list-in-r raw1 <- strsplit(readLines(args[1]), "[[:space:]]+") data1 <- lapply(raw1, tail, n = -1) names(data1) <- lapply(raw1, head, n = 1) data1 <- lapply(data1, as.numeric) pdf(args[2]) library(lattice) data <- list() data$MappedReadLengths <- data1$length data$MismatchesPerReadBase <- data1$mismatches data$ReadIdentity <- data1$identity data$DeletionsPerBase <- data1$deletions data$InsertionsPerBase <- data1$insertions #filter out any read identities that are outside of 3 sd's from mean for fit lines #but still plot the points id.inliers <- which(data$ReadIdentity >= mean(data$ReadIdentity) - 2 * sd(data$ReadIdentity) & data$ReadIdentity <= mean(data$ReadIdentity) + 2 * sd(data$ReadIdentity)) len.inliers <- which(data$MappedReadLengths >= mean(data$MappedReadLengths) - 2 * sd(data$MappedReadLengths) & data$MappedReadLengths <= mean(data$MappedReadLengths) + 2 * sd(data$MappedReadLengths)) mismatches.inliers <- which(data$MismatchesPerReadBase >= mean(data$MismatchesPerReadBase) - 2 * sd(data$MismatchesPerReadBase) & data$MismatchesPerReadBase <= mean(data$MismatchesPerReadBase) + 2 * sd(data$MismatchesPerReadBase)) deletions.inliers <- which(data$DeletionsPerBase >= mean(data$DeletionsPerBase) - 2 * sd(data$DeletionsPerBase) & data$DeletionsPerBase <= mean(data$DeletionsPerBase) + 2 * sd(data$DeletionsPerBase)) insertions.inliers <- which(data$InsertionsPerBase >= mean(data$InsertionsPerBase) - 2 * sd(data$InsertionsPerBase) & data$InsertionsPerBase <= mean(data$InsertionsPerBase) + 2 * sd(data$InsertionsPerBase)) inliers <- intersect(insertions.inliers, intersect(deletions.inliers, intersect(mismatches.inliers, intersect(id.inliers, len.inliers)))) p1 <- xyplot(data$ReadIdentity~data$MappedReadLengths, main=list("Read Identity vs.\nRead Length", cex=0.95), xlab="Read Length", ylab="Read Identity", grid=T, panel=function(...){ panel.smoothScatter(...) panel.abline(lwd=1.2, lm(data$ReadIdentity[inliers]~data$MappedReadLengths[inliers])) }, key=simpleKey(paste("R^2 =", as.character(round(summary.lm( lm(data$ReadIdentity[inliers]~data$MappedReadLengths[inliers]))$adj.r.squared,3)), sep=" "), points=F, corner=c(1,1), cex=0.9)) p2 <- xyplot((data$InsertionsPerBase+data$DeletionsPerBase)~data$MappedReadLengths, main=list("Indels Per Aligned Base vs.\nRead Length", cex=0.95), xlab="Read Length", ylab="Indels Per Base", grid=T, panel=function(...){ panel.smoothScatter(...) panel.abline(lwd=1.2, lm((data$InsertionsPerBase+data$DeletionsPerBase)[inliers]~data$MappedReadLengths[inliers])) }, key=simpleKey(paste("R^2 =", as.character(round(summary.lm( lm((data$InsertionsPerBase+data$DeletionsPerBase)[inliers]~data$MappedReadLengths[inliers]))$adj.r.squared,3)), sep=" "), points=F, corner=c(1,1), cex=0.9)) p3 <- xyplot(data$MismatchesPerReadBase~data$MappedReadLengths, main=list("Mismatches Per Aligned Base vs.\nRead Length", cex=0.95), ylab="Mismatches Per Aligned Base", xlab="Read Length", grid=T, panel=function(...){ panel.smoothScatter(...) panel.abline(lwd=1.2, lm(data$MismatchesPerReadBase[inliers]~data$MappedReadLengths[inliers])) }, key=simpleKey(paste("R^2 =", as.character(round(summary.lm( lm(data$MismatchesPerReadBase[inliers]~data$MappedReadLengths[inliers]))$adj.r.squared,3)), sep=" "), points=F, corner=c(1,1), cex=0.9)) #print the graphs print(p1, position=c(0, 0.5, 0.5, 1), more=T) print(p2, position=c(0.5, 0.5, 1, 1), more=T) print(p3, position=c(0, 0, 0.5, 0.5)) #now time to do more graphs p1 <- xyplot(data$MismatchesPerReadBase~(data$InsertionsPerBase+data$DeletionsPerBase), main=list("Mismatches Per Aligned Base vs.\nIndels Per Aligned Base", cex=0.95), xlab="Indels Per Aligned Base", ylab="Mismatches Per Aligned Base", grid=T, panel=function(...){ panel.smoothScatter(...) panel.lmline(..., lwd=1.2) }, key=simpleKey(paste("R^2 =", as.character(round(summary.lm( lm(data$MismatchesPerReadBase~(data$InsertionsPerBase+data$DeletionsPerBase)))$adj.r.squared,3)), sep=" "), points=F, corner=c(0,1), cex=0.9)) p2 <- xyplot((data$InsertionsPerBase+data$DeletionsPerBase)~data$ReadIdentity, main=list("Indels Per Aligned Base vs.\nRead Identity", cex=0.95), xlab="Read Identity", ylab="Indels Per Base", grid=T, panel=function(...){ panel.smoothScatter(...) panel.abline(lwd=1.2, lm((data$InsertionsPerBase+data$DeletionsPerBase)[inliers]~data$ReadIdentity[inliers])) }, key=simpleKey(paste("R^2 =", as.character(round(summary.lm( lm((data$InsertionsPerBase+data$DeletionsPerBase)~data$ReadIdentity))$adj.r.squared,3)), sep=" "), points=F, corner=c(1,1), cex=0.9)) p3 <- xyplot(data$MismatchesPerReadBase~data$ReadIdentity, main=list("Mismatches Per Aligned Base vs.\nRead Identity",cex=0.95), ylab="Mismatches Per Aligned Base", xlab="Read Identity", grid=T, panel=function(...){ panel.smoothScatter(...) panel.abline(lwd=1.2, lm(data$MismatchesPerReadBase[data$ReadIdentity>0.6]~data$ReadIdentity[data$ReadIdentity>0.6])) }, key=simpleKey(paste("R^2 =", as.character(round(summary.lm( lm((data$InsertionsPerBase+data$DeletionsPerBase)~data$ReadIdentity))$adj.r.squared,3)), sep=" "), points=F, corner=c(0,0), cex=0.9)) p4 <- xyplot(data$InsertionsPerBase~data$DeletionsPerBase, main=list("Insertions Per Aligned Base vs.\nDeletions Per Aligned Base",cex=0.95), xlab="Deletions Per Aligned Base", ylab="Insertions Per Aligned Base", grid=T, panel=function(...){ panel.smoothScatter(...) panel.lmline(..., lwd=1.2) }, key=simpleKey(paste("R^2 =", as.character(round(summary.lm( lm(data$InsertionsPerBase~data$DeletionsPerBase))$adj.r.squared,3)), sep=" "), points=F, corner=c(0,1), cex=0.9)) #print the graphs print(p1, position=c(0, 0.5, 0.5, 1), more=T) print(p2, position=c(0.5, 0.5, 1, 1), more=T) print(p3, position=c(0, 0, 0.5, 0.5), more=T) print(p4, position=c(0.5, 0, 1, 0.5)) dev.off()
R
2D
mitenjain/nanopore
scripts/blast_combined/blast_combined.py
.py
7,750
148
#!/usr/bin/env python import sys, os, pysam from optparse import OptionParser from jobTree.scriptTree.target import Target from jobTree.scriptTree.stack import Stack from jobTree.src.bioio import fastqRead, fastaRead, setLoggingFromOptions, logger, popenCatch, system from itertools import izip, product from collections import Counter, defaultdict """Used to BLAST results from the combined analysis result in order to find the set of reads that truly unmappable. Reports the BLAST results as well as the raw hits, and also reports a fasta of the reads that did not map anywhere, and generates a summary barplot.""" readTypes = ["2D", "template", "complement"] combinedAnalyses = ["LastzParamsRealignEm","LastParamsRealignEm","BwaParamsRealignEm","BlasrParamsRealignEm"]#,"BwaChain","BlasrChain","LastChain","LastzChain"] def parse_blast(blast_handle): """generator to yield blast results for each read, iterating over blast with outfmt="7 qseqid sseqid sscinames stitle" and max_target set to 1""" result = None for line in blast_handle: if "0 hits found" in line: yield (query, result) elif line.startswith("#") and "Query: " in line: query = line.split("Query: ")[-1].rstrip() elif result is None and not line.startswith("#"): result = line.strip().split("\t")[-3::] yield (query, result) elif result is not None and line.startswith("#"): result = None def find_analyses(target, unmappedByReadType, outputDir): outfiles = dict() for readType in unmappedByReadType: outfiles[readType] = list() records = list() for (name, sequence), i in izip(unmappedByReadType[readType].iteritems(), xrange(len(unmappedByReadType[readType]))): records.append(">{}\n{}\n".format(name, sequence)) if i % 10 == 1200 or i == len(unmappedByReadType[readType]) - 1: tmpalign = os.path.join(target.getGlobalTempDir(), str(i) + ".txt") outfiles[readType].append(tmpalign) target.addChildTarget(Target.makeTargetFn(run_blast, args=(records, tmpalign))) records = list() target.setFollowOnTargetFn(merge, args=(outfiles, outputDir)) def run_blast(target, records, tmpalign): query = "".join(records) p = popenCatch('blastn -outfmt "7 qseqid sseqid sscinames stitle" -db nt', stdinString=query) outf = open(tmpalign, "w"); outf.write(p); outf.close() def merge(target, outfiles, outputDir): for readType in outfiles: outf = os.path.join(outputDir, readType + "_blast_out.txt") with open(outf, "w") as outfile: for f in outfiles[readType]: with open(f) as i: outfile.write(i.read()) outfile.close() def main(): parser = OptionParser() Stack.addJobTreeOptions(parser) options, args = parser.parse_args() setLoggingFromOptions(options) outputDir = "blast_combined/output/" if not os.path.exists(outputDir): logger.info("Output dir {} does not exist. Creating.") os.mkdir(outputDir) if len(os.listdir(outputDir)) > 0: logger.info("Output dir not empty.") #find all read fastq files, load into a dict by read type readFastqFiles = dict() for readType in readTypes: readFastqFiles[readType] = [os.path.join("../output/processedReadFastqFiles/", readType, x) for x in os.listdir(os.path.join("../output/processedReadFastqFiles/", readType)) if x.endswith(".fq") or x.endswith(".fastq")] #find all reference fasta files referenceFastaFiles = [x for x in os.listdir("../referenceFastaFiles") if x.endswith(".fasta") or x.endswith(".fa")] #find all sam files that were analyzed using combinedAnalyses samFiles = {} for readType in readTypes: samFiles[readType] = [(readFastqFile, os.path.join("../output", "analysis_" + readType, "experiment_" + os.path.basename(readFastqFile) + "_" + referenceFastaFile + "_" + analysis, "mapping.sam")) for readFastqFile, referenceFastaFile, analysis in product(readFastqFiles[readType], referenceFastaFiles, combinedAnalyses)] mappedByReadType = defaultdict(set) for readType in readTypes: for readFastqFileFullPath, samFile in samFiles[readType]: readFastqFile = os.path.basename(readFastqFileFullPath) mappedNames = {(x.qname, readFastqFile) for x in pysam.Samfile(samFile) if not x.is_unmapped} mappedByReadType[readType] = mappedByReadType[readType].union(mappedNames) unmappedByReadType = defaultdict(dict) for readType in readTypes: for readFastqFileFullPath, samFile in samFiles[readType]: readFastqFile = os.path.basename(readFastqFileFullPath) for name, seq, qual in fastqRead(readFastqFileFullPath): name = name.split(" ")[0] if (name, readFastqFile) not in mappedByReadType[readType]: unmappedByReadType[readType][(name, readFastqFile)] = seq i = Stack(Target.makeTargetFn(find_analyses, args=(unmappedByReadType, outputDir))).startJobTree(options) if i != 0: raise RuntimeError("Got {} failed jobs".format(i)) for readType in readTypes: #build a counter of blast hits and set of read names that did not map blast_hits, no_hits = Counter(), set() for query, result in parse_blast(open(os.path.join(outputDir, readType + "_blast_out.txt"))): if result is None: no_hits.add(query) else: blast_hits[tuple(result)] += 1 #count number of times each hit was seen #write the unmapped hits to a fasta file outf = open(os.path.join(outputDir, readType + "_no_hits.fasta"), "w") for (name, readFastqFile), seq in unmappedByReadType[readType].iteritems(): if name in no_hits: outf.write(">{}\n{}\n".format(name, seq)) outf.close() #write the blast report blast_out = open(os.path.join(outputDir, readType + "_blast_report.txt"), "w") blast_out.write("gi|##|gb|##|\tSpecies\tseqID\tCount\n") #header to output for result, count in sorted(blast_hits.items(), key = lambda x: -int(x[-1])): blast_out.write("{}\t{}\n".format("\t".join(result), count)) blast_out.close() #calculate percents and make a barplot blast_count = sum(blast_hits.values()) unmapped_count = len(unmappedByReadType[readType]) - sum(blast_hits.values()) mapped_count = len(mappedByReadType[readType]) #blast_percent = 1.0 * sum(blast_hits.values()) / (len(mappedByReadType[readType]) + len(unmappedByReadType[readType])) #unmapped_percent = (1.0 * len(unmappedByReadType[readType]) - sum(blast_hits.values())) / (len(mappedByReadType[readType]) + len(unmappedByReadType[readType])) #mapped_percent = 1.0 * len(mappedByReadType[readType]) / (len(mappedByReadType[readType]) + len(unmappedByReadType[readType])) outf = open(os.path.join(outputDir, readType + "percents.txt"),"w") outf.write("\n".join(map(str,[blast_count, unmapped_count, mapped_count]))) outf.close() #system("Rscript blast_combined/barplot_blast.R {} {} {} {} {}".format(blast_percent, unmapped_percent, mapped_percent, readType, os.path.join(outputDir, readType + "_blast_barplot.pdf"))) system("Rscript blast_combined/barplot_blast.R {} {} {} {} {}".format(blast_count, unmapped_count, mapped_count, readType, os.path.join(outputDir, readType + "_blast_barplot.pdf"))) if __name__ == "__main__": from scripts.blast_combined.blast_combined import * main()
Python
2D
mitenjain/nanopore
scripts/blast_combined/__init__.py
.py
0
0
null
Python
2D
mitenjain/nanopore
scripts/blast_combined/make_blast_tex.py
.py
1,101
38
import sys, os readTypes = ["2D","complement","template"] files = [] for f in os.listdir(sys.argv[1]): if f.split("_")[0] in readTypes: readType = f.split("_")[0] if "blast_report.txt" in f and "Fail" not in f: files.append([os.path.join(sys.argv[1], f), readType]) files = sorted(files, key=lambda x: x[1]) with open(sys.argv[2],"w") as f: for infile, readType in files: readType = readType.title() start = """ \clearpage \n \\begin{{longtable}}{{|p{{14cm}}|p{{1.1cm}}|}} \hline \n \multicolumn{{2}}{{|c|}}{{{} Unmapped Reads BLAST Hits}} \\\\ \n Sequence Name & Counts \\\\ \hline \n""".format(readType) end = """ \hline \n \caption{{Table of BLAST hits for {0} reads unmapped by any mapper.}} \n \label{{{0}BlastTable}} \n \end{{longtable}} \n""".format(readType) data = [x.split("\t")[-2:] for x in open(infile)][1:] tmp = [] for x in data: x[0].replace("_","\_") tmp.append(x) f.write(start) for x in tmp: f.write(" & ".join(x)+" \\\\ \n") f.write(end)
Python
2D
mitenjain/nanopore
scripts/blast_combined/barplot_blast.R
.R
542
13
#!/usr/bin/env Rscript # args <- commandArgs(trailingOnly = T) blast <- round(as.numeric(args[1]), 3) unmapped <- round(as.numeric(args[2]), 3) mapped <- round(as.numeric(args[3]), 3) readType <- args[4] pdf(args[5]) q <- barplot(c(blast, unmapped, mapped), names.arg=c("Blast Hits", "Still Unmapped", "Originally Mapped"), col=c("red","blue","green"), main=paste(readType, "Percent of Reads", sep=" ")) text(y=c(blast, unmapped, mapped)+0.02, x=q, labels=paste(as.character(round(c(blast, unmapped, mapped)*100, 3)), "%"), xpd=T) dev.off()
R
2D
mitenjain/nanopore
scripts/muscle_compare_2d/muscle_compare_2d.py
.py
7,051
146
#!/usr/bin/env python import sys, os, pysam from optparse import OptionParser from jobTree.scriptTree.target import Target from jobTree.scriptTree.stack import Stack from jobTree.src.bioio import fastqRead, fastaRead, setLoggingFromOptions, logger from subprocess import Popen, PIPE from itertools import izip """ Analysis script to determine if template/complement reads can be 'rescued' by providing the small region of the reference where the 2D read they combined into aligned. Should be ran via run_muscle.sh, which has three arguments: --template_sam, --twoD_sam, --complement_sam The sam files should be from the same aligner and read/reference set. This program will dig through the nanopore pipeline's directory structure looking for reference and read files. This assumes that you are on the version of the pipeline whereby reads are sorted by type into respective folders (I.E. nanopore/readFastqFiles/template/a_template_file.fastq, etc) """ def find_analyses(target, recordsToAnalyze, templateFastqFiles, complementFastqFiles, references, outputDir): """takes a set of records to analyze and finds the corresponding sequences and creates alignment targets""" files = {"template":[], "complement":[]} logger.info("Finding template analyses") for fastqFile in templateFastqFiles: for name, seq, qual in fastqRead(fastqFile): if name in recordsToAnalyze: outfile = os.path.join(target.getGlobalTempDir(), "template_" + name) files["template"].append(outfile) ref_name, ref_start, ref_stop = recordsToAnalyze[name] ref_seq = references[ref_name][ref_start : ref_stop] analysis = [name, seq, ref_name, ref_seq, outfile] target.addChildTarget(Target.makeTargetFn(analyze, args=analysis)) logger.info("Finding complement analyses") for fastqFile in complementFastqFiles: for name, seq, qual in fastqRead(fastqFile): if name in recordsToAnalyze: outfile = os.path.join(target.getGlobalTempDir(), "complement_" + name) files["complement"].append(outfile) ref_name, ref_start, ref_stop = recordsToAnalyze[name] ref_seq = references[ref_name][ref_start : ref_stop] analysis = [name, seq, ref_name, ref_seq, outfile] target.addChildTarget(Target.makeTargetFn(analyze, args=analysis)) target.setFollowOnTargetFn(merge, args=(files, outputDir)) def analyze(target, name, seq, ref_name, ref_seq, outfile): """main analysis target; runs muscle on each pair of sequences""" outf = open(outfile, "w") p = Popen(["muscle", "-quiet"], stdout=PIPE, stdin=PIPE).communicate(">{}\n{}\n>{}\n{}\n".format(name, seq, ref_name, ref_seq))[0] outf.write(p); outf.close() def merge(target, files, outputDir): """merges all muscle output into one fasta and runs metrics() on each""" for typeof in files: outmetrics = open(os.path.join(outputDir, typeof + "_metrics.tsv"), "w") outmetrics.write("Read\tReference\tMatches\tMismatches\tReadDeletionLength\tReadInsertionLength\tIdentity\tReferenceCoverage\n") for f in files[typeof]: handle = fastaRead(f) name, seq = handle.next() ref_name, ref_seq = handle.next() name = name.lstrip(">"); ref_name = ref_name.lstrip(">") outmetrics.write("\t".join([name, ref_name] + metrics(seq, ref_seq))); outmetrics.write("\n") outmetrics.close() def metrics(seq, ref_seq): """takes in two aligned fasta sequences and calculates identity/coverage metrics""" matches = 0.0; mismatches = 0.0; readDeletionLength = 0.0; readInsertionLength = 0.0 for s, r in izip(seq, ref_seq): if s == "-": readDeletionLength += 1 elif r == "-": readInsertionLength += 1 elif s == r == "-": continue #just in case? elif s == r: matches += 1 elif s != r: mismatches += 1 identity = matches / (matches + mismatches) referenceCoverage = (matches + mismatches) / (matches + mismatches + readDeletionLength) return map(str, [matches, mismatches, readDeletionLength, readInsertionLength, identity, referenceCoverage]) def main(): parser = OptionParser() Stack.addJobTreeOptions(parser) options, args = parser.parse_args() setLoggingFromOptions(options) outputDir = "muscle_compare_2d/output/" if not os.path.exists(outputDir): logger.info("Output dir {} does not exist. Creating.") os.mkdir(outputDir) if len(os.listdir(outputDir)) > 0: logger.info("Output dir not empty.") if len(args) != 3: raise RuntimeError("Error: expected three arguments got %s arguments: %s" % (len(args), " ".join(args))) templateRecords = {x.qname for x in pysam.Samfile(args[0]) if not x.is_unmapped} complementRecords = {x.qname for x in pysam.Samfile(args[1]) if not x.is_unmapped} twodSamFile = pysam.Samfile(args[2]) twodRecords = {x.qname : x for x in twodSamFile if not x.is_unmapped} recordsToAnalyze = dict() for name, record in twodRecords.iteritems(): if name not in templateRecords and name not in complementRecords: ref_name = twodSamFile.getrname(record.tid) ref_start, ref_stop = int(record.aend - record.alen), int(record.aend) recordsToAnalyze[name] = [ref_name, ref_start, ref_stop] if os.path.exists("../readFastqFiles/template/") and os.path.exists("../readFastqFiles/complement"): templateFastqFiles = [os.path.join("../readFastqFiles/template/", x) for x in os.listdir("../readFastqFiles/template/") if x.endswith(".fastq") or x.endswith(".fq")] complementFastqFiles = [os.path.join("../readFastqFiles/complement/", x) for x in os.listdir("../readFastqFiles/complement/") if x.endswith(".fastq") or x.endswith(".fq")] else: raise RuntimeError("Error: readFastqFiles does not contain template and/or complement folders") referenceFastaFiles = [os.path.join("../referenceFastaFiles", x) for x in os.listdir("../referenceFastaFiles") if x.endswith(".fa") or x.endswith(".fasta")] if len(referenceFastaFiles) > 0: references = { y[0].split(" ")[0] : y[1] for x in referenceFastaFiles for y in fastaRead(x) } else: raise RuntimeError("Error: no reference fasta files") if len(recordsToAnalyze) == 0: raise RuntimeError("Error: none of the mappable twoD reads in this set did not map as template/complement.") logger.info("Starting to find analyses to run...") args = (recordsToAnalyze, templateFastqFiles, complementFastqFiles, references, outputDir) i = Stack(Target.makeTargetFn(find_analyses, args=args)).startJobTree(options) if i != 0: raise RuntimeError("Got {} failed jobs".format(i)) if __name__ == "__main__": from scripts.muscle_compare_2d.muscle_compare_2d import * main()
Python
2D
mitenjain/nanopore
scripts/muscle_compare_2d/__init__.py
.py
0
0
null
Python
2D
dean0x7d/pybinding
setup.py
.py
4,982
134
import re import os import sys import shutil import platform from subprocess import check_call, check_output, CalledProcessError from distutils.version import LooseVersion from setuptools import setup, find_packages, Extension from setuptools.command.build_ext import build_ext from setuptools.command.egg_info import manifest_maker if sys.version_info[:2] < (3, 6): print("Python >= 3.6 is required.") sys.exit(-1) class CMakeExtension(Extension): def __init__(self, name, sourcedir=""): super().__init__(name, sources=[]) self.sourcedir = os.path.abspath(sourcedir) class CMakeBuild(build_ext): def run(self): try: out = check_output(["cmake", "--version"]) except OSError: raise RuntimeError("CMake not found. Version 3.1 or newer is required") cmake_version = LooseVersion(re.search(r'version\s*([\d.]+)', out.decode()).group(1)) if cmake_version < "3.1.0": raise RuntimeError("CMake 3.1 or newer is required") for ext in self.extensions: self.build_extension(ext) def build_extension(self, ext): extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name))) cmake_args = ["-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=" + extdir, "-DPYTHON_EXECUTABLE=" + sys.executable] cmake_args += ["-DPB_WERROR=" + os.environ.get("PB_WERROR", "OFF"), "-DPB_TESTS=" + os.environ.get("PB_TESTS", "OFF"), "-DPB_NATIVE_SIMD=" + os.environ.get("PB_NATIVE_SIMD", "ON"), "-DPB_MKL=" + os.environ.get("PB_MKL", "OFF"), "-DPB_CUDA=" + os.environ.get("PB_CUDA", "OFF")] cfg = os.environ.get("PB_BUILD_TYPE", "Release") build_args = ["--config", cfg] if platform.system() == "Windows": cmake_args += ["-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}".format(cfg.upper(), extdir)] cmake_args += ["-A", "x64" if sys.maxsize > 2**32 else "Win32"] build_args += ["--", "/v:m", "/m"] else: cmake_args += ["-DCMAKE_BUILD_TYPE=" + cfg] if "-j" not in os.environ.get("MAKEFLAGS", ""): parallel_jobs = 2 if not os.environ.get("READTHEDOCS") else 1 build_args += ["--", "-j{}".format(parallel_jobs)] env = os.environ.copy() env["CXXFLAGS"] = '{} -DCPB_VERSION=\\"{}\\"'.format(env.get("CXXFLAGS", ""), self.distribution.get_version()) def build(): os.makedirs(self.build_temp, exist_ok=True) check_call(["cmake", ext.sourcedir] + cmake_args, cwd=self.build_temp, env=env) check_call(["cmake", "--build", "."] + build_args, cwd=self.build_temp) try: build() except CalledProcessError: # possible CMake error if the build cache has been copied shutil.rmtree(self.build_temp) # delete build cache and try again build() def about(package): ret = {} filename = os.path.join(os.path.dirname(__file__), package, "__about__.py") with open(filename, 'rb') as file: exec(compile(file.read(), filename, 'exec'), ret) return ret def changelog(): """Return the changes for the latest version only""" if not os.path.exists("changelog.md"): return "" with open("changelog.md", encoding="utf-8") as file: log = file.read() match = re.search(r"## ([\s\S]*?)\n##\s", log) return match.group(1) if match else "" info = about("pybinding") manifest_maker.template = "setup.manifest" setup( name=info['__title__'], version=info['__version__'], description=info['__summary__'], long_description="Documentation: http://pybinding.site/\n\n" + changelog(), url=info['__url__'], license=info['__license__'], keywords="pybinding tight-binding solid-state physics cmt", author=info['__author__'], author_email=info['__email__'], platforms=['Unix', 'Windows'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Physics', 'License :: OSI Approved :: BSD License', 'Programming Language :: C++', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', ], packages=find_packages(exclude=['cppcore', 'cppwrapper', 'test*']) + ['pybinding.tests'], package_dir={'pybinding.tests': 'tests'}, include_package_data=True, ext_modules=[CMakeExtension('_pybinding')], install_requires=['numpy>=1.12', 'scipy>=0.19', 'matplotlib>=2.0', 'pytest>=5.0'], zip_safe=False, cmdclass=dict(build_ext=CMakeBuild) )
Python
2D
dean0x7d/pybinding
changelog.md
.md
15,737
344
# Changelog ## v0.9.5 | 2020-08-30 It has been a long time since the last version was released. The Python ecosystem has changed quite a bit in the meantime and this has led to a number of compatibility issues when installing or running pybinding. The main purpose of this new version is to bring this library back to life with lots of compatibility fixes and general modernization. That said, a couple of new features have also snuck in: site and hopping generators should help with the creation of more general models that were not possible before. They make it possible to create heterostructures and systems with various forms of disorder. Thank you to [@MAndelkovic (Miša Anđelković)](https://github.com/MAndelkovic) for making this release possible! And thanks to everyone who reported the various issues. #### Necromancy * Fixed compatibility issues with Python 3.7 and 3.8. Notably, this fixes the deadlocks as reported in [#17](https://github.com/dean0x7d/pybinding/issues/17), [#21](https://github.com/dean0x7d/pybinding/issues/21), and [#23](https://github.com/dean0x7d/pybinding/issues/23). * Fixed compatibility with new versions of `matplotlib`: the `allow_rasterization` import error ([#11](https://github.com/dean0x7d/pybinding/issues/11)), various warnings, and smaller visual glitches. * Fixed installation errors due to the encoding of the `changelog.md` file ([#7](https://github.com/dean0x7d/pybinding/issues/7)). * Fixed failure to compile the project from source code because the Eigen library's download URL changed ([#14](https://github.com/dean0x7d/pybinding/issues/14)). * Fixed deprecation warnings from the latest versions of `numpy`. * Fixed documentation generation with `sphinx` v2.x. * Dropped support for Python 3.5. You must have Python 3.6 or newer to install this version. #### General bug fixes * Fixed reversed order of `Lattice.reciprocal_vectors()`: it should be `a_n * b_n = 2pi` but it was accidentally `a_n * b_{N-n} = 2pi`. * Fixed incorrect Hamiltonian construction in cases where complex hoppings were used together with translational symmetry. #### New features * Added `@site_generator` which can be used to add new sites independent of the main `Lattice` definition. This is useful for creating heterostructures or defects with various add-atoms. See the new "Generators" section of the tutorial. * `@hopping_generator` has been promoted to a regular feature and added to the tutorial. It's useful for creating additional local hoppings around existing sites or connecting completely new sites which were added by a `@site_generator`. * Added `System.count_neighbors()` which counts the neighbors each site has. Useful for finding edge atoms. Generators can request `system` as an argument so that they can stitch new atoms to the edges. See the API reference for `@site_generator` and `@hopping_generator`. * `@site_state_modifier`s and `@site_position_modifier`s can now be freely ordered. Before this, all state modifiers would be evaluated first and then all position modifiers. Now, they will be evaluated in the exact order in which they are given to `Model`. Take care: this may change the behavior of some existing models but it will give more control to create new models which not possible before. ## v0.9.4 | 2017-07-13 * Fixed issues with multi-orbital models: matrix onsite terms were not set correctly if all the elements on the main diagonal were zero ([#5](https://github.com/dean0x7d/pybinding/issues/5)), hopping terms were being applied asymmetrically for large multi-orbital systems ([#6](https://github.com/dean0x7d/pybinding/issues/6)). Thanks to [@oroszl (László Oroszlány)](https://github.com/oroszl) for reporting the issues. * Fixed KPM Hamiltonian scaling for models with all zeros on the main diagonal but asymmetric spectrum bounds (non-zero KPM scaling factor `b`). * Fixed compilation on certain Linux distributions ([#4](https://github.com/dean0x7d/pybinding/issues/4)). Thanks to [@nu11us (Will Eggleston)](https://github.com/nu11us) for reporting the issue. * Fixed compilation with Visual Studio 2017. * Improved support for plotting slices of multi-layer systems. See "Plotting Guide" > "Model structure" > "Slicing layers" in the documentation. ## v0.9.3 | 2017-05-29 * Added support for Kwant v1.3.x and improved `Model.tokwant()` exporting of multi-orbital models. * Fixed errors when compiling with GCC 6. ## v0.9.2 | 2017-05-26 #### New KPM features and improvements * Added a method for calculating spatial LDOS using KPM. See the "Kernel Polynomial Method" tutorial page and the `KPM.calc_spatial_ldos` API reference. * Improved single-threaded performance of `KPM.calc_dos` by ~2x by switching to a more efficient vectorization method. (Multiple random starter vectors are now computed simultaneously and accelerated using SIMD intrinsics.) * Various KPM methods now take advantage of multiple threads. This improves performance depending on the number of cores on the target machine. (However, for large systems performance is limited by RAM bandwidth, not necessarily core count.) * LDOS calculations for multiple orbitals also take advantage of the same vectorization and multi-threading improvements. Single-orbital LDOS does not benefit from this but it has received its own modest performance tweaks. * Long running KPM calculation now have a progress indicator and estimated completion time. #### General improvements and bug fixes * `StructureMap` can now be sliced using a shape. E.g. `s = pb.rectangle(5, 5); smap2 = smap[s]` which returns a smaller structure map cut down to the given shape. * Plotting the structure of large or periodic systems is slightly faster now. * Added 2D periodic supercells to the "Shape and symmetry" section of the tutorial. * Added a few more examples to the "Plotting guide" (view rotation, separating sites and hoppings and composing multiple plots). * Fixed broken documentation links when using the online search function. * Fixed slow Hamiltonian build when hopping generators are used. ## v0.9.1 | 2017-04-28 * Fixed an issue with multi-orbital models where onsite/hopping modifiers would return unexpected results if a new `energy` array was returned (rather than being modified in place). * Fixed `Solver.calc_spatial_ldos` and `Solver.calc_probability` returning single-orbital results for multi-orbital models. * Fixed slicing of `Structure` objects and made access to the `data` property of `SpatialMap` and `StructureMap` mutable again. ## v0.9.0 | 2017-04-14 #### Updated requirements * This version includes extensive internal improvements and raises the minimum requirements for installation. Starting with this release, only Python >= 3.5 is supported. Newer versions of the scientific Python packages are also required: numpy >= 1.12, scipy >= 0.19 and matplotlib >= 2.0. * On Linux, the minimum compiler requirements have also been increased to get access to C++14 for the core of the library. To compile from source, you'll need GCC >= 5.0 or clang >= 3.5. #### Multi-orbital models * Improved support for models with multiple orbitals, spins and any additional degrees of freedom. These can now be specified simply by inputing a matrix as the onsite or hopping term (instead of a scalar value). For more details, see the "Multi-orbital models" section of the documentation. * Lifted all limits on the number of sublattices and hoppings which can be defined in a `Lattice` object. The previous version was limited to a maximum of 128 onsite and hopping terms per unit cell (but those could be repeated an unlimited number of times to form a complete system). All restrictions are now removed so that the unit cell size is only limited by available memory. In addition, the memory usage of the internal system format has been reduced. * Added a 3-band model of group 6 transition metal dichalcogenides to the Material Repository. The available TMDs include: MoS2, WS2, MoSe2, WSe2, MoTe2, WTe2. These are all monolayers. #### Composite shapes * Complicated system geometries can now be created easily by composing multiple simple shapes. This is done using set operations, e.g. unions, intersections, etc. A complete guide for this functionality is available in the "Composite shapes" section of the documentation. #### Kernel polynomial method * The KPM implementation has been revised and significantly expanded. A guide and several examples are available in the "Kernel polynomial method" section of the documentation (part 9 of the Tutorial). For a complete overview of the available methods and kernels, see the `chebyshev` section of the API reference. * New builtin computation methods include the stochastically-evaluated density of states (DOS) and electrical conductivity (using the Kubo-Bastin approach). * The new low-level interface produces KPM expansion moments which allows users to create their own KPM-based computation routines. * The performance of various KPM computations has been significantly improved for CPUs with AVX support (~1.5x speedup on average, but also up to 2x in some cases with complex numbers). #### Miscellaneous * Added the `pb.save()` and `pb.load()` convenience functions for getting result objects into/out of files. The data is saved in a compressed binary format (Python's builtin `pickle` format with protocol 4 and gzip). Loaded files can be immediately plotted: `result = pb.load("file.pbz")` and then `result.plot()` to see the data. * The eigenvalue solvers now have a `calc_ldos` method for computing the local density of states as a function of energy (in addition to the existing `calc_spatial_ldos`). * Improved plotting of `Lattice` objects. The view can now be rotated by passing the `axis="xz"` argument, or any other combination of x, y and z to define the plotting plane. #### Deprecations and breaking changes * Added `Lattice.add_aliases()` method. The old `Lattice.add_sublattice(..., alias=name)` way of creating aliases is deprecated. * The `greens` module has been deprecated. This functionality is now covered by the KPM methods. * The internal storage format of the `Lattice` and `System` classes has been revised. This shouldn't affect most users who don't need access to the low-level data. ## v0.8.2 | 2017-01-26 * Added support for Python 3.6 (pybinding is available as a binary wheel for Windows and macOS). * Fixed compatibility with matplotlib v2.0. * Fixed a few minor bugs. ## v0.8.1 | 2016-11-11 * Structure plotting functions have been improved with better automatic scaling of lattice site circle sizes and hopping line widths. * Fixed Brillouin zone calculation for cases where the angle between lattice vectors is obtuse ([#1](https://github.com/dean0x7d/pybinding/issues/1)). Thanks to [@obgeneralao (Oliver B Generalao)](https://github.com/obgeneralao) for reporting the issue. * Fixed a flaw in the example of a phosphorene lattice (there were extraneous t5 hoppings). Thanks to Longlong Li for pointing this out. * Fixed missing CUDA source files in PyPI sdist package. * Revised advanced installation instructions: compiling from source code and development. ## v0.8.0 | 2016-07-01 #### New features * Added support for scattering models. Semi-infinite leads can be attached to a finite-sized scattering region. Take a look at the documentation, specifically section 10 of the "Basic Tutorial", for details on how to construct such models. * Added compatibility with [Kwant](http://kwant-project.org/) for transport calculations. A model can be constructed in pybinding and then exported using the `Model.tokwant()` method. This makes it possible to use Kwant's excellent solver for transport problems. While Kwant does have its own model builder, pybinding is much faster in this regard: by two orders of magnitude, see the "Benchmarks" page in the documentation for a performance comparison. * *Experimental:* Initial CUDA implementation of KPM Green's function (only for diagonal elements for now). See the "Experimental Features" section of the documentation. #### Improvements * The performance of the KPM Green's function implementation has been improved significantly: by a factor of 2.5x. The speedup was achieved with CPU code using portable SIMD intrinsics thanks to [libsimdpp](https://github.com/p12tic/libsimdpp). * The Green's function can now be computed for multiple indices simultaneously. * The spatial origin of a lattice can be adjusted using the `Lattice.offset` attribute. See the "Advanced Topics" section. #### Breaking changes * The interface for structure plotting (as used in `System.plot()` and `StructureMap`) has been greatly improved. Some of the changes are not backwards compatible and may require some minor code changes after upgrading. See the "Plotting Guide" section of the documentation for details. * The interfaces for the `Bands` and `StructureMap` result objects have been revised. Specifically, structure maps are now more consistent with ndarrays, so the old `smap.filter(smap.x > 0)` is replaced by `smap2 = smap[smap.x > 0]`. The "Plotting Guide" has a few examples and there is a full method listing in the "API Reference" section. #### Documentation * The API reference has been completely revised and now includes a summary on the main page. * A few advanced topics are now covered, including some aspects of plotting. A few more random examples have also been added. * Experimental features are now documented. #### Bug fixes * Fixed translational symmetry skipping directions for some 2D systems. * Fixed computation of off-diagonal Green's function elements with `opt_level > 0` * Fixed some issues with shapes which were not centered at `(x, y) = (0, 0)`. ## v0.7.2 | 2016-03-14 * Lots of improvements to the documentation. The tutorial pages can now be downloaded and run interactively as Jupyter notebooks. The entire user guide is also available as a PDF file. * The `sub_id` and `hop_id` modifier arguments can now be compared directly with their friendly string names. For example, this makes it possible to write `sub_id == 'A'` instead of the old `sub_id == lattice['A']` and `hop_id == 'gamma1'` instead of `hop_id == lattice('gamma1')`. * The site state modifier can automatically remove dangling sites which have less than a certain number of neighbors (set using the `min_neighbors` decorator argument). * Added optional `sites` argument for state, position, and onsite energy modifiers. It can be used instead of the `x, y, z, sub_id` arguments and contains a few helper methods. See the modifier API reference for more information. * Fixed a bug where using a single KPM object for multiple calculations could return wrong results. * *Experimental* `hopping_generator` which can be used to add a new hopping family connecting arbitrary sites independent of the main `Lattice` definition. This is useful for creating additional local hoppings, e.g. to model defects. ## v0.7.1 | 2016-02-08 * Added support for double-precision floating point. Single precision is used by default, but it will be switched automatically to double if required by an onsite or hopping modifier. * Added support for the 32-bit version of Python * Tests are now included in the installed package. They can be run with: ```python import pybinding as pb pb.tests() ``` * Available as a binary wheel for 32-bit and 64-bit Windows (Python 3.5 only) and OS X (Python 3.4 and 3.5) ## v0.7.0 | 2016-02-01 Initial release
Markdown
2D
dean0x7d/pybinding
license.md
.md
1,304
25
Copyright (c) 2015 - 2017, Dean Moldovan All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Markdown
2D
dean0x7d/pybinding
support/deploy.sh
.sh
431
13
#!/usr/bin/env bash cd $TRAVIS_BUILD_DIR pip install -U wheel pip install twine if [ "$TRAVIS_OS_NAME" = "linux" ] && [ -d "$TRAVIS_BUILD_DIR/dist" ]; then twine upload -u $PYPI_USER -p $PYPI_PASS --skip-existing dist/*.tar.gz elif [ "$TRAVIS_OS_NAME" = "osx" ]; then PB_NATIVE_SIMD=OFF python setup.py bdist_wheel --plat-name macosx-10.9-x86_64 twine upload -u $PYPI_USER -p $PYPI_PASS --skip-existing dist/*.whl fi
Shell
2D
dean0x7d/pybinding
cppmodule/include/thread.hpp
.hpp
912
44
#pragma once #include <pybind11/pybind11.h> #include "detail/thread.hpp" namespace py = pybind11; namespace cpb { class DeferredBase { public: virtual ~DeferredBase() = default; virtual py::object solver() const = 0; virtual void compute() = 0; virtual py::object result() = 0; }; template<class Result> class Deferred : public DeferredBase { public: Deferred(py::object solver, std::function<Result()> compute) : _solver(std::move(solver)), _compute(std::move(compute)) {} py::object solver() const final { return _solver; } void compute() final { if (is_computed) { return; } _result = _compute(); is_computed = true; } py::object result() final { compute(); return py::cast(_result); } private: py::object _solver; std::function<Result()> _compute; Result _result; bool is_computed = false; }; } // namespace cpb
Unknown
2D
dean0x7d/pybinding
cppmodule/include/resolve.hpp
.hpp
1,041
26
#pragma once /// Syntax sugar for resolving overloaded function pointers: /// - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func) /// - sweet: &Class::func | resolve<Arg0, Arg1, Arg2>() template<class... Args> struct resolve { template<class Return> friend constexpr auto operator|(Return (* pf)(Args...), resolve) noexcept -> decltype(pf) { return pf; } template<class Return, class Class> friend constexpr auto operator|(Return (Class::* pmf)(Args...), resolve) noexcept -> decltype(pmf) { return pmf; } }; /// Resolve const member function /// - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func) /// - sweet: &Class::func | resolve_const<Arg>() template<class... Args> struct resolve_const { template<class Return, class Class> friend constexpr auto operator|(Return (Class::* pmf)(Args...) const, resolve_const) noexcept -> decltype(pmf) { return pmf; } };
Unknown
2D
dean0x7d/pybinding
cppmodule/include/wrappers.hpp
.hpp
659
28
#pragma once #include "detail/config.hpp" #include <pybind11/pybind11.h> #include <pybind11/functional.h> #include <pybind11/stl.h> #include <pybind11/eigen.h> #include "cast.hpp" #include "resolve.hpp" namespace py = pybind11; using namespace py::literals; using release_gil = py::call_guard<py::gil_scoped_release>; void wrap_greens(py::module& m); void wrap_lattice(py::module& m); void wrap_leads(py::module& m); void wrap_model(py::module& m); void wrap_modifiers(py::module& m); void wrap_parallel(py::module& m); void wrap_shape(py::module& m); void wrap_solver(py::module& m); void wrap_system(py::module& m); void wrapper_tests(py::module& m);
Unknown
2D
dean0x7d/pybinding
cppmodule/include/cast.hpp
.hpp
6,133
157
#pragma once #include "numeric/arrayref.hpp" #include "numeric/sparseref.hpp" #include "support/variant.hpp" #include "detail/opaque_alias.hpp" namespace pybind11 { namespace detail { template<> struct visit_helper<cpb::var::variant> { template<class... Args> static auto call(Args&&... args) -> decltype(cpb::var::apply_visitor(std::forward<Args>(args)...)) { return cpb::var::apply_visitor(std::forward<Args>(args)...); } }; template<class... Args> struct type_caster<cpb::var::variant<Args...>> : variant_caster<cpb::var::variant<Args...>> {}; /// Only for statically sized vectors: accepts smaller source arrays and zero-fills the remainder template<class Vector> struct static_vec_caster { using Scalar = typename Vector::Scalar; using Strides = Eigen::InnerStride<>; using Map = Eigen::Map<Eigen::Matrix<Scalar, 1, Eigen::Dynamic> const, 0, Strides>; bool load(handle src, bool) { auto const a = array_t<Scalar>::ensure(src); if (!a) { return false; } auto const ndim = a.ndim(); if (ndim > 1) { return false; } value = Vector::Zero(); if (ndim == 0) { value[0] = a.data()[0]; } else { auto const size = static_cast<int>(a.size()); if (size > Vector::SizeAtCompileTime) { return false; } auto const stride = static_cast<Eigen::Index>(a.strides()[0] / sizeof(Scalar)); value.head(size) = Map(a.data(), size, Strides(stride)); } return true; } static handle cast(Vector const& src, return_value_policy, handle /*parent*/) { return array_t<Scalar>(src.size(), src.data()).release(); } PYBIND11_TYPE_CASTER(Vector, _("numpy.ndarray")); }; template<> struct type_caster<Eigen::Vector3f> : static_vec_caster<Eigen::Vector3f> {}; template<> struct type_caster<Eigen::Vector3i> : static_vec_caster<Eigen::Vector3i> {}; template<bool is_const> struct arrayref_caster { using Type = cpb::num::detail::BasicArrayRef<is_const>; using Shape = std::array<Py_intptr_t, 3>; static constexpr auto writable = !is_const ? npy_api::NPY_ARRAY_WRITEABLE_ : 0; static constexpr auto base_flags = npy_api::NPY_ARRAY_ALIGNED_ | writable; static handle cast(Type const& src, return_value_policy, handle parent) { using cpb::num::Tag; auto data_type = [&] { switch (src.tag) { case Tag::f32: return dtype::of<float>(); case Tag::cf32: return dtype::of<std::complex<float>>(); case Tag::f64: return dtype::of<double>(); case Tag::cf64: return dtype::of<std::complex<double>>(); case Tag::b: return dtype::of<bool>(); case Tag::i8: return dtype::of<int8_t>(); case Tag::i16: return dtype::of<int16_t>(); case Tag::i32: return dtype::of<int32_t>(); case Tag::i64: return dtype::of<int64_t>(); case Tag::u8: return dtype::of<uint8_t>(); case Tag::u16: return dtype::of<uint16_t>(); case Tag::u32: return dtype::of<uint32_t>(); case Tag::u64: return dtype::of<uint64_t>(); default: throw std::runtime_error("ArrayRef: unknown scalar type"); } }(); auto shape = Shape{{src.shape[0], src.shape[1], src.shape[2]}}; auto const flags = base_flags | (src.is_row_major ? npy_api::NPY_ARRAY_C_CONTIGUOUS_ : npy_api::NPY_ARRAY_F_CONTIGUOUS_); auto result = npy_api::get().PyArray_NewFromDescr_( npy_api::get().PyArray_Type_, data_type.release().ptr(), src.ndim, shape.data(), /*strides*/nullptr, const_cast<void*>(src.data), flags, nullptr ); if (!result) { pybind11_fail("ArrayRef: unable to create array"); } if (parent) { detail::keep_alive_impl(result, parent); } return result; } static constexpr auto name = _("numpy.ndarray"); }; template<bool is_const> struct type_caster<cpb::num::detail::BasicArrayRef<is_const>> : arrayref_caster<is_const> {}; template<class T, class... Ts> struct type_caster<cpb::num::VariantArrayConstRef<T, Ts...>> : arrayref_caster<true> {}; template<class T, class... Ts> struct type_caster<cpb::num::VariantArrayRef<T, Ts...>> : arrayref_caster<false> {}; struct csrref_caster { using Type = cpb::num::AnyCsrConstRef; static handle cast(Type const& src, return_value_policy policy, handle parent) { auto const data = pybind11::cast(src.data_ref(), policy, parent); auto const indices = pybind11::cast(src.indices_ref(), policy, parent); auto const indptr = pybind11::cast(src.indptr_ref(), policy, parent); auto result = module::import("scipy.sparse").attr("csr_matrix")( pybind11::make_tuple(data, indices, indptr), pybind11::make_tuple(src.rows, src.cols), /*dtype*/none(), /*copy*/false ); if (parent) { detail::keep_alive_impl(result, parent); } return result.release(); } static constexpr auto name = _("scipy.sparse.csr_matrix"); }; template<> struct type_caster<cpb::num::AnyCsrConstRef> : csrref_caster {}; template<class T, class... Ts> struct type_caster<cpb::num::VariantCsrConstRef<T, Ts...>> : csrref_caster {}; template<class T> struct type_caster<cpb::num::CsrConstRef<T>> : csrref_caster {}; template<class Tag, class T> struct type_caster<cpb::detail::OpaqueIntegerAlias<Tag, T>> { using Type = cpb::detail::OpaqueIntegerAlias<Tag, T>; using Caster = type_caster<T>; bool load(handle src, bool convert) { auto caster = Caster(); if (caster.load(src, convert)) { value = Type(caster.operator T&()); return true; } return false; } static handle cast(Type const& src, return_value_policy policy, handle parent) { return Caster::cast(src.value(), policy, parent); } PYBIND11_TYPE_CASTER(Type, _("int")); }; }} // namespace pybind11::detail
Unknown
2D
dean0x7d/pybinding
cppmodule/src/lattice.cpp
.cpp
5,097
92
#include "Lattice.hpp" #include "wrappers.hpp" using namespace cpb; void wrap_lattice(py::module& m) { using Sub = Lattice::Sublattice; py::class_<Sub>(m, "Sublattice") .def_readonly("position", &Sub::position, "Relative to global lattice offset") .def_readonly("energy", &Sub::energy, "Onsite energy matrix") .def_readonly("unique_id", &Sub::unique_id, "Different for each sublattice") .def_readonly("alias_id", &Sub::alias_id, "May be shared by multiple (e.g. supercells)") .def(py::pickle([](Sub const& s) { return py::dict("position"_a=s.position, "energy"_a=s.energy, "unique_id"_a=s.unique_id, "alias_id"_a=s.alias_id); }, [](py::dict d) { return new Sub{d["position"].cast<decltype(Sub::position)>(), d["energy"].cast<decltype(Sub::energy)>(), d["unique_id"].cast<decltype(Sub::unique_id)>(), d["alias_id"].cast<decltype(Sub::alias_id)>()}; })); using HT = Lattice::HoppingTerm; py::class_<HT>(m, "HoppingTerm") .def_readonly("relative_index", &HT::relative_index, "Relative index between two unit cells - note that it may be [0, 0, 0]") .def_readonly("from_id", &HT::from, "Sublattice ID of the source") .def_readonly("to_id", &HT::to, "Sublattice ID of the destination") .def(py::pickle([](HT const& h) { return py::dict("relative_index"_a=h.relative_index, "from"_a=h.from, "to"_a=h.to); }, [](py::dict d) { return new HT{d["relative_index"].cast<decltype(HT::relative_index)>(), d["from"].cast<decltype(HT::from)>(), d["to"].cast<decltype(HT::to)>()}; })); using HF = Lattice::HoppingFamily; py::class_<HF>(m, "HoppingFamily") .def_readonly("energy", &HF::energy, "Hopping matrix shared by all terms in this family") .def_readonly("family_id", &HF::family_id, "Different for each family") .def_readonly("terms", &HF::terms, "List of :class:`~_pybinding.HoppingTerm`") .def(py::pickle([](HF const& f) { return py::dict("energy"_a=f.energy, "family_id"_a=f.family_id, "terms"_a=f.terms); }, [](py::dict d) { return new HF{d["energy"].cast<decltype(HF::energy)>(), d["family_id"].cast<decltype(HF::family_id)>(), d["terms"].cast<decltype(HF::terms)>()}; })); py::class_<Lattice>(m, "Lattice") .def(py::init<Cartesian, Cartesian, Cartesian>(), "a1"_a, "a2"_a=Cartesian{0, 0, 0}, "a3"_a=Cartesian{0, 0, 0}) .def("add_sublattice", &Lattice::add_sublattice | resolve<string_view, Cartesian, double>()) .def("add_sublattice", &Lattice::add_sublattice | resolve<string_view, Cartesian, VectorXd const&>()) .def("add_sublattice", &Lattice::add_sublattice | resolve<string_view, Cartesian, MatrixXcd const&>()) .def("add_alias", &Lattice::add_alias) .def("register_hopping_energy", &Lattice::register_hopping_energy | resolve<string_view, std::complex<double>>()) .def("register_hopping_energy", &Lattice::register_hopping_energy | resolve<string_view, MatrixXcd const&>()) .def("add_hopping", &Lattice::add_hopping | resolve<Index3D, string_view, string_view, string_view>()) .def("add_hopping", &Lattice::add_hopping | resolve<Index3D, string_view, string_view, std::complex<double>>()) .def("add_hopping", &Lattice::add_hopping | resolve<Index3D, string_view, string_view, MatrixXcd const&>()) .def_property_readonly("ndim", &Lattice::ndim) .def_property_readonly("nsub", &Lattice::nsub) .def_property_readonly("nhop", &Lattice::nhop) .def_property_readonly("vectors", &Lattice::get_vectors) .def_property_readonly("sublattices", &Lattice::get_sublattices) .def_property_readonly("hoppings", &Lattice::get_hoppings) .def_property("offset", &Lattice::get_offset, &Lattice::set_offset) .def_property("min_neighbors", &Lattice::get_min_neighbors, &Lattice::set_min_neighbors) .def(py::pickle([](Lattice const& l) { return py::dict("vectors"_a=l.get_vectors(), "sublattices"_a=l.get_sublattices(), "hoppings"_a=l.get_hoppings(), "offset"_a=l.get_offset(), "min_neighbors"_a=l.get_min_neighbors()); }, [](py::dict d) { auto l = new Lattice(d["vectors"].cast<Lattice::Vectors>(), d["sublattices"].cast<Lattice::Sublattices>(), d["hoppings"].cast<Lattice::Hoppings>()); l->set_offset(d["offset"].cast<Cartesian>()); l->set_min_neighbors(d["min_neighbors"].cast<int>()); return l; })); }
C++
2D
dean0x7d/pybinding
cppmodule/src/model.cpp
.cpp
1,884
41
#include "Model.hpp" #include "wrappers.hpp" using namespace cpb; void wrap_model(py::module& m) { py::class_<Model>(m, "Model") .def(py::init<Lattice const&>()) .def("add", &Model::add | resolve<Primitive>()) .def("add", &Model::add | resolve<Shape const&>()) .def("add", &Model::add | resolve<TranslationalSymmetry const&>()) .def("add", &Model::add | resolve<SiteStateModifier const&>()) .def("add", &Model::add | resolve<PositionModifier const&>()) .def("add", &Model::add | resolve<OnsiteModifier const&>()) .def("add", &Model::add | resolve<HoppingModifier const&>()) .def("add", &Model::add | resolve<SiteGenerator const&>()) .def("add", &Model::add | resolve<HoppingGenerator const&>()) .def("attach_lead", &Model::attach_lead) .def("set_wave_vector", &Model::set_wave_vector, "k"_a, R"( Set the wave vector for periodic models Parameters ---------- k : array_like Wave vector in reciprocal space. )") .def_property_readonly("lattice", &Model::get_lattice) .def_property_readonly("system", &Model::system) .def_property_readonly("raw_hamiltonian", &Model::hamiltonian) .def_property_readonly("hamiltonian", [](Model const& self) { return self.hamiltonian().csrref(); }) .def_property_readonly("leads", &Model::leads) .def("eval", &Model::eval) .def("report", &Model::report, "Return a string with information about the last build") .def_property_readonly("system_build_seconds", &Model::system_build_seconds) .def_property_readonly("hamiltonian_build_seconds", &Model::hamiltonian_build_seconds); py::class_<Hamiltonian>(m, "Hamiltonian") .def_property_readonly("csrref", &Hamiltonian::csrref); }
C++
2D
dean0x7d/pybinding
cppmodule/src/system.cpp
.cpp
6,334
120
#include "system/System.hpp" #include "wrappers.hpp" using namespace cpb; template<class T> void wrap_registry(py::module& m, char const* name) { py::class_<T>(m, name) .def_property_readonly("name_map", &T::name_map) .def(py::pickle([](T const& r) { return py::dict("energies"_a=r.get_energies(), "names"_a=r.get_names()); }, [](py::dict d) { return new T(d["energies"].cast<std::vector<MatrixXcd>>(), d["names"].cast<std::vector<std::string>>()); })); } void wrap_system(py::module& m) { wrap_registry<SiteRegistry>(m, "SiteRegistry"); wrap_registry<HoppingRegistry>(m, "HoppingRegistry"); py::class_<CartesianArray>(m, "CartesianArray") .def_property_readonly("x", [](CartesianArray const& a) { return arrayref(a.x); }) .def_property_readonly("y", [](CartesianArray const& a) { return arrayref(a.y); }) .def_property_readonly("z", [](CartesianArray const& a) { return arrayref(a.z); }) .def(py::pickle([](CartesianArray const& a) { return py::make_tuple(arrayref(a.x), arrayref(a.y), arrayref(a.z)); }, [](py::tuple t) { using T = ArrayXf; return new CartesianArray(t[0].cast<T>(), t[1].cast<T>(), t[2].cast<T>()); })); py::class_<CompressedSublattices>(m, "CompressedSublattices") .def("decompressed", [](CompressedSublattices const& c) { return c.decompressed(); }) .def_property_readonly("alias_ids", &CompressedSublattices::alias_ids) .def_property_readonly("site_counts", &CompressedSublattices::site_counts) .def_property_readonly("orbital_counts", &CompressedSublattices::orbital_counts) .def(py::pickle([](CompressedSublattices const& c) { return py::dict("alias_ids"_a=c.alias_ids(), "site_counts"_a=c.site_counts(), "orbital_counts"_a=c.orbital_counts()); }, [](py::dict d) { return new CompressedSublattices(d["alias_ids"].cast<ArrayXi>(), d["site_counts"].cast<ArrayXi>(), d["orbital_counts"].cast<ArrayXi>()); })); py::class_<HoppingBlocks>(m, "HoppingBlocks") .def_property_readonly("nnz", &HoppingBlocks::nnz) .def("count_neighbors", &HoppingBlocks::count_neighbors) .def("tocsr", [](HoppingBlocks const& hb) { auto type = py::module::import("pybinding.support.alias").attr("AliasCSRMatrix"); return type(hb.tocsr(), "mapping"_a=hb.get_name_map()); }) .def("tocoo", [](py::object self) { return self.attr("tocsr")().attr("tocoo")(); }) .def("__getitem__", [](py::object self, py::object item) { auto const structure = py::module::import("pybinding.support.structure"); return structure.attr("Hoppings")( structure.attr("_slice_csr_matrix")(self.attr("tocsr")(), item) ); }) .def(py::pickle([](HoppingBlocks const& hb) { return py::dict("num_sites"_a=hb.get_num_sites(), "data"_a=hb.get_serialized_blocks(), "name_map"_a=hb.get_name_map()); }, [](py::dict d) { return new HoppingBlocks(d["num_sites"].cast<idx_t>(), d["data"].cast<HoppingBlocks::SerializedBlocks>(), d["name_map"].cast<NameMap>()); })); using Boundary = System::Boundary; py::class_<Boundary>(m, "Boundary") .def_readonly("hoppings", &Boundary::hopping_blocks) .def_readonly("shift", &Boundary::shift) .def("__getitem__", [](py::object self, py::object item) { auto type = py::module::import("pybinding.support.structure").attr("Boundary"); return type(self.attr("shift"), self.attr("hoppings")[item]); }) .def(py::pickle([](Boundary const& b) { return py::make_tuple(b.hopping_blocks, b.shift); }, [](py::tuple t) { return new Boundary{t[0].cast<decltype(Boundary::hopping_blocks)>(), t[1].cast<decltype(Boundary::shift)>()}; })); py::class_<System, std::shared_ptr<System>>(m, "System") .def("find_nearest", &System::find_nearest, "position"_a, "sublattice"_a="") .def("to_hamiltonian_indices", &System::to_hamiltonian_indices) .def_readonly("site_registry", &System::site_registry) .def_readonly("hopping_registry", &System::hopping_registry) .def_readonly("positions", &System::positions) .def_readonly("compressed_sublattices", &System::compressed_sublattices) .def_readonly("hopping_blocks", &System::hopping_blocks) .def_readonly("boundaries", &System::boundaries) .def_property_readonly("hamiltonian_size", &System::hamiltonian_size) .def_property_readonly("expanded_positions", &System::expanded_positions) .def(py::pickle([](System const& s) { return py::dict("site_registry"_a=s.site_registry, "hopping_registry"_a=s.hopping_registry, "positions"_a=s.positions, "compressed_sublattices"_a=s.compressed_sublattices, "hopping_blocks"_a=s.hopping_blocks, "boundaries"_a=s.boundaries); }, [](py::dict d) { auto s = [&]{ if (d.contains("lattice")) { auto const lattice = d["lattice"].cast<Lattice>(); return new System(lattice.site_registry(), lattice.hopping_registry()); } else { return new System(d["site_registry"].cast<SiteRegistry>(), d["hopping_registry"].cast<HoppingRegistry>()); } }(); s->positions = d["positions"].cast<decltype(s->positions)>(); s->compressed_sublattices = d["compressed_sublattices"].cast<decltype(s->compressed_sublattices)>(); s->hopping_blocks = d["hopping_blocks"].cast<decltype(s->hopping_blocks)>(); s->boundaries = d["boundaries"].cast<decltype(s->boundaries)>(); return s; })); }
C++
2D
dean0x7d/pybinding
cppmodule/src/leads.cpp
.cpp
846
25
#include "leads/Leads.hpp" #include "wrappers.hpp" using namespace cpb; void wrap_leads(py::module& m) { py::class_<leads::Spec>(m, "LeadSpec") .def_readonly("axis", &leads::Spec::axis) .def_readonly("sign", &leads::Spec::sign) .def_readonly("shape", &leads::Spec::shape) ; py::class_<Lead>(m, "Lead") .def_property_readonly("spec", &Lead::spec) .def_property_readonly("indices", [](Lead const& l) { return arrayref(l.indices()); }) .def_property_readonly("system", &Lead::system) .def_property_readonly("h0", [](Lead const& l) { return l.h0().csrref(); }) .def_property_readonly("h1", [](Lead const& l) { return l.h1().csrref(); }) ; py::class_<Leads>(m, "Leads") .def("__len__", &Leads::size) .def("__getitem__", &Leads::operator[]) ; }
C++
2D
dean0x7d/pybinding
cppmodule/src/solver.cpp
.cpp
1,651
38
#include "solver/Solver.hpp" #include "solver/FEAST.hpp" #include "wrappers.hpp" using namespace cpb; void wrap_solver(py::module& m) { py::class_<BaseSolver>(m, "Solver") .def("solve", &BaseSolver::solve) .def("clear", &BaseSolver::clear) .def("report", &BaseSolver::report, "shortform"_a=false) .def("calc_dos", &BaseSolver::calc_dos, "energies"_a, "broadening"_a) .def("calc_spatial_ldos", &BaseSolver::calc_spatial_ldos, "energy"_a, "broadening"_a) .def_property("model", &BaseSolver::get_model, &BaseSolver::set_model) .def_property_readonly("system", &BaseSolver::system) .def_property_readonly("eigenvalues", &BaseSolver::eigenvalues) .def_property_readonly("eigenvectors", &BaseSolver::eigenvectors); #ifdef CPB_USE_FEAST auto const feast_defaults = FEASTConfig(); py::class_<Solver<FEAST>, BaseSolver>(m, "FEAST") .def(py::init([](Model const& model, std::pair<float, float> energy, int size_guess, bool recycle, bool verbose) { FEASTConfig config; config.energy_min = energy.first; config.energy_max = energy.second; config.initial_size_guess = size_guess; config.recycle_subspace = recycle; config.is_verbose = verbose; return new Solver<FEAST>(model, config); }, "model"_a, "energy_range"_a, "initial_size_guess"_a, "recycle_subspace"_a=feast_defaults.recycle_subspace, "is_verbose"_a=feast_defaults.is_verbose ); #endif // CPB_USE_FEAST }
C++
2D
dean0x7d/pybinding
cppmodule/src/main.cpp
.cpp
1,383
52
#include "wrappers.hpp" #include "support/simd.hpp" #ifdef CPB_USE_MKL # include <mkl.h> #endif using namespace cpb; PYBIND11_MODULE(_pybinding, m) { wrap_greens(m); wrap_lattice(m); wrap_leads(m); wrap_model(m); wrap_modifiers(m); wrap_parallel(m); wrap_shape(m); wrap_solver(m); wrap_system(m); wrapper_tests(m); m.def("simd_info", []() -> std::string { #if SIMDPP_USE_AVX auto const bits = std::to_string(simd::basic_traits::register_size_bytes * 8); return (SIMDPP_USE_AVX2 ? "AVX2-" : "AVX-") + bits; #elif SIMDPP_USE_SSE3 return "SSE3"; #elif SIMDPP_USE_SSE2 return "SSE2"; #else return "x87"; #endif }); #ifdef CPB_USE_MKL m.def("get_max_threads", MKL_Get_Max_Threads, "Get the maximum number of MKL threads. (<= logical theads)"); m.def("set_num_threads", MKL_Set_Num_Threads, "number"_a, "Set the number of MKL threads."); m.def("get_max_cpu_frequency", MKL_Get_Max_Cpu_Frequency); m.def("get_cpu_frequency", MKL_Get_Cpu_Frequency); // The max threads count may change later but at init time it's usually // equal to the physical core count which is useful information. m.attr("physical_core_count") = MKL_Get_Max_Threads(); #endif #ifdef CPB_VERSION m.attr("__version__") = CPB_VERSION; #else m.attr("__version__") = "dev"; #endif }
C++
2D
dean0x7d/pybinding
cppmodule/src/modifiers.cpp
.cpp
6,010
140
#include "system/StructureModifiers.hpp" #include "hamiltonian/HamiltonianModifiers.hpp" #include "wrappers.hpp" using namespace cpb; namespace { /// Extract an Eigen array from a Python object, but avoid a copy if possible struct ExtractModifierResult { py::object o; template<class EigenType> void operator()(Eigen::Map<EigenType> eigen_map) const { static_assert(EigenType::IsVectorAtCompileTime, ""); using scalar_t = typename EigenType::Scalar; using NumpyType = py::array_t<typename EigenType::Scalar>; if (!py::isinstance<NumpyType>(o)) { std::is_floating_point<scalar_t>() ? throw ComplexOverride() : throw std::runtime_error("Unexpected modifier result size"); } auto const a = py::reinterpret_borrow<NumpyType>(o); if (eigen_map.size() != static_cast<idx_t>(a.size())) { throw std::runtime_error("Unexpected modifier result size"); } if (eigen_map.data() != a.data()) { eigen_map = Eigen::Map<EigenType const>(a.data(), static_cast<idx_t>(a.size())); } } }; template<class EigenType, class T> void extract_modifier_result(T& v, py::object const& o) { ExtractModifierResult{o}(Eigen::Map<EigenType>(v.data(), v.size())); } } // anonymous namespace template<class T> SiteGenerator* init_site_generator(string_view name, T const& energy, py::object make) { auto system_type = py::module::import("pybinding.system").attr("System"); return new SiteGenerator( name, detail::canonical_onsite_energy(energy), [make, system_type](System const& s) { py::gil_scoped_acquire guard{}; auto t = make(system_type(&s)).cast<py::tuple>(); return CartesianArray(t[0].cast<ArrayXf>(), t[1].cast<ArrayXf>(), t[2].cast<ArrayXf>()); } ); }; template<class T> HoppingGenerator* init_hopping_generator(std::string const& name, T const& energy, py::object make) { auto system_type = py::module::import("pybinding.system").attr("System"); return new HoppingGenerator( name, detail::canonical_hopping_energy(energy), [make, system_type](System const& s) { py::gil_scoped_acquire guard{}; auto t = make(system_type(&s)).cast<py::tuple>(); return HoppingGenerator::Result{t[0].cast<ArrayXi>(), t[1].cast<ArrayXi>()}; } ); } void wrap_modifiers(py::module& m) { py::class_<SiteStateModifier>(m, "SiteStateModifier") .def(py::init([](py::object apply, int min_neighbors) { return new SiteStateModifier( [apply](Eigen::Ref<ArrayX<bool>> state, CartesianArrayConstRef p, string_view s) { py::gil_scoped_acquire guard{}; auto result = apply( arrayref(state), arrayref(p.x()), arrayref(p.y()), arrayref(p.z()), s ); extract_modifier_result<ArrayX<bool>>(state, result); }, min_neighbors ); }), "apply"_a, "min_neighbors"_a=0); py::class_<PositionModifier>(m, "PositionModifier") .def(py::init([](py::object apply) { return new PositionModifier([apply](CartesianArrayRef p, string_view sub) { py::gil_scoped_acquire guard{}; auto t = py::tuple(apply(arrayref(p.x()), arrayref(p.y()), arrayref(p.z()), sub)); extract_modifier_result<ArrayXf>(p.x(), t[0]); extract_modifier_result<ArrayXf>(p.y(), t[1]); extract_modifier_result<ArrayXf>(p.z(), t[2]); }); })); py::class_<SiteGenerator>(m, "SiteGenerator") .def(py::init(&init_site_generator<std::complex<double>>)) .def(py::init(&init_site_generator<VectorXd>)) .def(py::init(&init_site_generator<MatrixXcd>)); py::class_<HoppingGenerator>(m, "HoppingGenerator") .def(py::init(&init_hopping_generator<std::complex<double>>)) .def(py::init(&init_hopping_generator<MatrixXcd>)); py::class_<OnsiteModifier>(m, "OnsiteModifier") .def(py::init([](py::object apply, bool is_complex, bool is_double) { return new OnsiteModifier( [apply](ComplexArrayRef energy, CartesianArrayConstRef p, string_view sublattice) { py::gil_scoped_acquire guard{}; auto result = apply( energy, arrayref(p.x()), arrayref(p.y()), arrayref(p.z()), sublattice ); num::match<ArrayX>(energy, ExtractModifierResult{result}); }, is_complex, is_double ); }), "apply"_a, "is_complex"_a=false, "is_double"_a=false) .def_readwrite("is_complex", &OnsiteModifier::is_complex) .def_readwrite("is_double", &OnsiteModifier::is_double); py::class_<HoppingModifier>(m, "HoppingModifier") .def(py::init([](py::object apply, bool is_complex, bool is_double) { return new HoppingModifier( [apply](ComplexArrayRef energy, CartesianArrayConstRef p1, CartesianArrayConstRef p2, string_view hopping_family) { py::gil_scoped_acquire guard{}; auto result = apply( energy, arrayref(p1.x()), arrayref(p1.y()), arrayref(p1.z()), arrayref(p2.x()), arrayref(p2.y()), arrayref(p2.z()), hopping_family ); num::match<ArrayX>(energy, ExtractModifierResult{result}); }, is_complex, is_double ); }), "apply"_a, "is_complex"_a=false, "is_double"_a=false) .def_readwrite("is_complex", &HoppingModifier::is_complex) .def_readwrite("is_double", &HoppingModifier::is_double); }
C++
2D
dean0x7d/pybinding
cppmodule/src/parallel.cpp
.cpp
1,769
47
#include "wrappers.hpp" #include "thread.hpp" #include "numeric/dense.hpp" using namespace cpb; void wrap_parallel(py::module& m) { py::class_<DeferredBase, std::shared_ptr<DeferredBase>>(m, "DeferredBase") .def("compute", &DeferredBase::compute) .def_property_readonly("solver", &DeferredBase::solver) .def_property_readonly("result", &DeferredBase::result); using DeferredXdCM = Deferred<ArrayXXdCM>; py::class_<DeferredXdCM, std::shared_ptr<DeferredXdCM>, DeferredBase>(m, "DeferredXd"); m.def("parallel_for", [](py::object sequence, py::object produce, py::object retire, std::size_t num_threads, std::size_t queue_size) { auto const size = py::len(sequence); py::gil_scoped_release gil_release; struct Job { py::object py; std::shared_ptr<DeferredBase> cpp; }; parallel_for( size, num_threads, queue_size, [&produce, &sequence](size_t id) { py::gil_scoped_acquire gil_acquire; py::object var = sequence[py::cast(id)]; py::object obj = produce(var); return Job{obj, obj.cast<std::shared_ptr<DeferredBase>>()}; }, [](Job& job) { // no GIL lock -> computations run in parallel // but no Python code may be called here job.cpp->compute(); }, [&retire](Job job, size_t id) { py::gil_scoped_acquire gil_acquire; retire(job.py, id); job.py.release().dec_ref(); job.cpp.reset(); } ); }, "sequence"_a, "produce"_a, "retire"_a, "num_threads"_a, "queue_size"_a); }
C++
2D
dean0x7d/pybinding
cppmodule/src/shape.cpp
.cpp
1,901
53
#include "system/Shape.hpp" #include "system/Symmetry.hpp" #include "wrappers.hpp" using namespace cpb; void wrap_shape(py::module& m) { py::class_<Primitive>(m, "Primitive") .def(py::init<int, int, int>()); using RefX = Eigen::Ref<Eigen::ArrayXf const>; py::class_<Shape>(m, "Shape") .def(py::init([](Shape::Vertices const& vertices, py::object f) { auto contains = [f](CartesianArrayConstRef p) { py::gil_scoped_acquire guard; return f(p.x(), p.y(), p.z()).cast<ArrayX<bool>>(); }; return new Shape(vertices, contains); })) .def("contains", [](Shape const& s, RefX x, RefX y, RefX z) { return s.contains({x, y, z}); }, "x"_a, "y"_a, "z"_a, R"( Return ``True`` if the given position is located within the shape Given arrays as input the return type is a boolean array. Parameters ---------- x, y, z : array_like Positions to test against the shape. )") .def_readonly("vertices", &Shape::vertices) .def_readwrite("lattice_offset", &Shape::lattice_offset); py::class_<Line, Shape>(m, "Line") .def(py::init<Cartesian, Cartesian>()); py::class_<Polygon, Shape>(m, "Polygon") .def(py::init<Polygon::Vertices const&>()); py::class_<FreeformShape, Shape>(m, "FreeformShape") .def(py::init([](py::object f, Cartesian width, Cartesian center) { auto contains = [f](CartesianArrayConstRef p) { py::gil_scoped_acquire guard; return f(p.x(), p.y(), p.z()).cast<ArrayX<bool>>(); }; return new FreeformShape(contains, width, center); })); py::class_<TranslationalSymmetry>(m, "TranslationalSymmetry") .def(py::init<float, float, float>()); }
C++
2D
dean0x7d/pybinding
cppmodule/src/kpm.cpp
.cpp
5,615
127
#include "KPM.hpp" #include "wrappers.hpp" #include "thread.hpp" using namespace cpb; namespace { void wrap_kpm_strategy(py::module& m, char const* name) { auto const kpm_defaults = kpm::Config(); m.def( name, [](Model const& model, std::pair<float, float> energy, kpm::Kernel const& kernel, std::string matrix_format, bool optimal_size, bool interleaved, float lanczos, idx_t num_threads, kpm::DefaultCompute::ProgressCallback progress_callback) { kpm::Config config; config.min_energy = energy.first; config.max_energy = energy.second; config.kernel = kernel; config.matrix_format = matrix_format == "ELL" ? kpm::MatrixFormat::ELL : kpm::MatrixFormat::CSR; config.algorithm.optimal_size = optimal_size; config.algorithm.interleaved = interleaved; config.lanczos_precision = lanczos; return KPM(model, kpm::DefaultCompute(num_threads, progress_callback), config); }, "model"_a, "energy_range"_a=py::make_tuple(kpm_defaults.min_energy, kpm_defaults.max_energy), "kernel"_a=kpm_defaults.kernel, "matrix_format"_a="ELL", "optimal_size"_a=true, "interleaved"_a=true, "lanczos_precision"_a=kpm_defaults.lanczos_precision, "num_threads"_a=std::thread::hardware_concurrency(), "progress_callback"_a=py::none() ); } struct ReturnMatrix { template<class T> ComplexCsrConstRef operator()(T) const { throw std::runtime_error("This will never happen"); } template<class scalar_t> ComplexCsrConstRef operator()(SparseMatrixX<scalar_t> const& h2) const { return csrref(h2); } }; } // anonymously namespace void wrap_greens(py::module& m) { py::class_<kpm::Stats>(m, "KPMStats") .def_readonly("num_moments", &kpm::Stats::num_moments) .def_readonly("uses_full_system", &kpm::Stats::uses_full_system) .def_readonly("nnz", &kpm::Stats::nnz) .def_readonly("opt_nnz", &kpm::Stats::opt_nnz) .def_readonly("vec", &kpm::Stats::vec) .def_readonly("opt_vec", &kpm::Stats::opt_vec) .def_readonly("matrix_memory", &kpm::Stats::matrix_memory) .def_readonly("vector_memory", &kpm::Stats::vector_memory) .def_property_readonly("eps", &kpm::Stats::eps) .def_property_readonly("ops", &kpm::Stats::ops) .def_property_readonly("hamiltonian_time", [](kpm::Stats const& s) { return s.hamiltonian_timer.elapsed_seconds(); }) .def_property_readonly("moments_time", [](kpm::Stats const& s) { return s.moments_timer.elapsed_seconds(); }); py::class_<kpm::Kernel>(m, "KPMKernel") .def_readonly("damping_coefficients", &kpm::Kernel::damping_coefficients) .def_readonly("required_num_moments", &kpm::Kernel::required_num_moments); m.def("lorentz_kernel", &kpm::lorentz_kernel); m.def("jackson_kernel", &kpm::jackson_kernel); m.def("dirichlet_kernel", &kpm::dirichlet_kernel); py::class_<KPM>(m, "KPM") .def("moments", &KPM::moments) .def("calc_greens", &KPM::calc_greens, release_gil()) .def("calc_greens", &KPM::calc_greens_vector, release_gil()) .def("calc_dos", &KPM::calc_dos, release_gil()) .def("calc_conductivity", &KPM::calc_conductivity, release_gil()) .def("calc_ldos", &KPM::calc_ldos, release_gil()) .def("calc_spatial_ldos", &KPM::calc_spatial_ldos, release_gil()) .def("deferred_ldos", [](py::object self, ArrayXd energy, double broadening, Cartesian position, std::string sublattice) { auto& kpm = self.cast<KPM&>(); kpm.get_model().eval(); return Deferred<ArrayXXdCM>{ self, [=, &kpm] { return kpm.calc_ldos(energy, broadening, position, sublattice); } }; }) .def("report", &KPM::report, "shortform"_a=false) .def_property("model", &KPM::get_model, &KPM::set_model) .def_property_readonly("system", [](KPM const& kpm) { return kpm.get_model().system(); }) .def_property_readonly("scaling_factors", [](KPM& kpm) { auto const s = kpm.get_core().scaling_factors(); return py::make_tuple(s.a, s.b); }) .def_property_readonly("kernel", [](KPM& kpm) { return kpm.get_core().get_config().kernel; }) .def_property_readonly("stats", [](KPM& kpm) { return kpm.get_core().get_stats(); }); wrap_kpm_strategy(m, "kpm"); py::class_<kpm::OptimizedHamiltonian>(m, "OptimizedHamiltonian") .def(py::init([](Hamiltonian const& h, int index) { auto self = new kpm::OptimizedHamiltonian(h, kpm::MatrixFormat::CSR, true); auto indices = std::vector<idx_t>(h.rows()); std::iota(indices.begin(), indices.end(), 0); auto bounds = kpm::Bounds(h, kpm::Config{}.lanczos_precision); self->optimize_for({index, indices}, bounds.scaling_factors()); return self; })) .def_property_readonly("matrix", [](kpm::OptimizedHamiltonian const& self) { return var::apply_visitor(ReturnMatrix{}, self.matrix()); }) .def_property_readonly("sizes", [](kpm::OptimizedHamiltonian const& self) { return self.map().get_data(); }) .def_property_readonly("indices", [](kpm::OptimizedHamiltonian const& self) { return self.idx().dest; }); }
C++
2D
dean0x7d/pybinding
cppmodule/src/wrapper_tests.cpp
.cpp
714
27
#include "wrappers.hpp" namespace { struct TestArrayRef { Eigen::ArrayXi a = Eigen::ArrayXi::LinSpaced(12, 0, 12); }; } void wrapper_tests(py::module& pm) { auto m = pm.def_submodule("wrapper_tests"); m.def("variant_load", [](cpb::var::variant<int, std::string> v) { return v.is<int>() ? "int" : "std::string"; }); m.def("variant_cast", []() { using V = cpb::var::variant<int, std::string>; return py::make_tuple(V(5), V("Hello")); }); py::class_<TestArrayRef>(m, "TestArrayRef") .def(py::init<>()) .def_property_readonly("a", [](TestArrayRef const& r) { return cpb::num::arrayref(r.a.data(), 2, 2, 3); }); }
C++
2D
dean0x7d/pybinding
cppcore/include/Lattice.hpp
.hpp
8,080
192
#pragma once #include "system/Registry.hpp" #include <vector> namespace cpb { class OptimizedUnitCell; /** Crystal lattice specification */ class Lattice { public: struct Sublattice { Cartesian position; ///< relative to lattice origin MatrixXcd energy; ///< onsite energy term SubID unique_id; ///< different for each entry SubAliasID alias_id; ///< may be shared by multiple entries, e.g. for creating supercells }; struct HoppingTerm { Index3D relative_index; ///< relative index between two unit cells - may be (0, 0, 0) SubID from; ///< source sublattice unique ID SubID to; ///< destination sublattice unique ID friend bool operator==(HoppingTerm const& a, HoppingTerm const& b) { auto const left = std::tie(a.relative_index, a.from, a.to); auto const right = std::tie(b.relative_index, b.from, b.to); auto const right_conjugate = std::make_tuple(-b.relative_index, b.to, b.from); return left == right || left == right_conjugate; } friend bool operator!=(HoppingTerm const& a, HoppingTerm const& b) { return !(a == b); } }; struct HoppingFamily { MatrixXcd energy; ///< base hopping energy which is shared by all terms in this family HopID family_id; ///< different for each family std::vector<HoppingTerm> terms; ///< site connections }; using Vectors = std::vector<Cartesian>; using Sublattices = std::unordered_map<std::string, Sublattice>; using Hoppings = std::unordered_map<std::string, HoppingFamily>; public: Lattice(Cartesian a1, Cartesian a2 = {0, 0, 0}, Cartesian a3 = {0, 0, 0}); Lattice(Vectors v, Sublattices s, Hoppings h) : vectors(std::move(v)), sublattices(std::move(s)), hoppings(std::move(h)) {} /// Create a new sublattice void add_sublattice(string_view name, Cartesian position, double onsite_energy = .0); void add_sublattice(string_view name, Cartesian position, VectorXd const& onsite_energy); void add_sublattice(string_view name, Cartesian position, MatrixXcd const& onsite_energy); /// Create a sublattice which an alias for an existing lattice at a different position void add_alias(string_view alias_name, string_view original_name, Cartesian position); /// Associate a name with a hopping energy, but don't connect any sites void register_hopping_energy(string_view name, std::complex<double> energy); void register_hopping_energy(string_view name, MatrixXcd const& energy); /// Connect sites with an already registered hopping name/energy void add_hopping(Index3D relative_index, string_view from_sub, string_view to_sub, string_view hopping_family_name); /// Connect sites with an anonymous hopping energy void add_hopping(Index3D relative_index, string_view from_sub, string_view to_sub, std::complex<double> energy); void add_hopping(Index3D relative_index, string_view from_sub, string_view to_sub, MatrixXcd const& energy); public: // getters and setters /// The primitive vectors that define the lattice Vectors const& get_vectors() const { return vectors; } /// All the sites that belong to the primitive cell Sublattices const& get_sublattices() const { return sublattices; } /// Connections inside the unit cell or to a neighboring cell Hoppings const& get_hoppings() const { return hoppings; } /// The lattice offset value is added to the positions of all the sublattices Cartesian get_offset() const { return offset; } /// Set the lattice offset -- it must be within half the length of a primitive vector void set_offset(Cartesian position); /// Return a copy of this lattice with a different offset Lattice with_offset(Cartesian position) const; /// Any site which has less neighbors than this minimum will be considered as "dangling" int get_min_neighbors() const { return min_neighbors; } /// Set the minimum number of neighbors for any site void set_min_neighbors(int n) { min_neighbors = n; } /// Return a copy of this lattice with a different minimum neighbor count Lattice with_min_neighbors(int number) const; public: // properties /// The dimensionality of the lattice int ndim() const { return static_cast<int>(vectors.size()); } /// Number of sublattices int nsub() const { return static_cast<int>(sublattices.size()); } /// Number of hopping families int nhop() const { return static_cast<int>(hoppings.size()); } /// Get a single vector -- Expects: index < lattice.ndim() Cartesian vector(size_t index) const { return vectors[index]; } /// Get the maximum possible number of hoppings from any site of this lattice int max_hoppings() const; /// Does at least one sublattice have non-zero onsite energy on the main diagonal? bool has_diagonal_terms() const; /// Does at least one sublattice have non-zero onsite energy (including off-diagonal terms)? bool has_onsite_energy() const; public: // optimized access /// Return the optimized version of the lattice structure -- see `OptimizedLatticeStructure` OptimizedUnitCell optimized_unit_cell() const; /// Site information for the system builder SiteRegistry site_registry() const; /// Hopping information for the system builder HoppingRegistry hopping_registry() const; public: // utilities /// Calculate the spatial position of a unit cell or a sublattice site if specified Cartesian calc_position(Index3D index, string_view sublattice_name = "") const; /** Translate Cartesian `position` into lattice vector coordinates Return vector {n1, n2, n3} which satisfies `position = n1*a1 + n2*a2 + n3*a3`, where a1, a2 and a3 are lattice vectors. Note that the return vector is `float`. */ Vector3f translate_coordinates(Cartesian position) const; private: /// Access sublattice information by name or ID Sublattice const& sublattice(string_view name) const; Sublattice const& sublattice(SubID id) const; /// Assess hopping family information by name or ID HoppingFamily const& hopping_family(string_view name) const; HoppingFamily const& hopping_family(HopID id) const; SubID make_unique_sublattice_id(string_view name); private: Vectors vectors; ///< primitive vectors that define the lattice Sublattices sublattices; ///< i.e the sites that belong to the primitive cell Hoppings hoppings; ///< connections inside the unit cell or to a neighboring cell Cartesian offset = {0, 0, 0}; ///< global offset: sublattices are defined relative to this int min_neighbors = 1; ///< minimum number of neighbours required at each lattice site }; /** Unit cell data for a `Lattice` (all sites and hopping connections) The data layout is optimized for traversal over sites. In addition, the sites are sorted by the size of the onsite energy matrix and the alias ID. */ class OptimizedUnitCell { public: /// Similar to Lattice::HoppingTerm but `from_sublattice` is implicit struct Hopping { Index3D relative_index; storage_idx_t to_sub_idx; ///< destination sublattice index in `sites` (not `unique_id`) HopID family_id; bool is_conjugate; ///< true if this is an automatically added complex conjugate term }; /// Similar to Lattice::Sublattice but each site lists hopping from itself struct Site { Cartesian position; storage_idx_t norb; ///< number of orbitals on this site SubID unique_id; SubAliasID alias_id; std::vector<Hopping> hoppings; }; using Sites = std::vector<Site>; public: explicit OptimizedUnitCell(Lattice const& lattice); Site const& operator[](size_t n) const { return sites[n]; } Sites::const_iterator begin() const { return sites.begin(); } Sites::const_iterator end() const { return sites.end(); } private: Sites sites; }; } // namespace cpb
Unknown
2D
dean0x7d/pybinding
cppcore/include/KPM.hpp
.hpp
2,178
52
#pragma once #include "kpm/default/Compute.hpp" namespace cpb { /** Kernel Polynomial Method calculation interface */ class KPM { public: KPM(Model const& model, kpm::Compute const& compute = kpm::DefaultCompute{}, kpm::Config const& config = {}); void set_model(Model const&); Model const& get_model() const { return model; } kpm::Core& get_core() { return core; } /// Get some information about what happened during the last calculation std::string report(bool shortform) const; ArrayXcd moments(idx_t num_moments, VectorXcd const& alpha, VectorXcd const& beta = {}, SparseMatrixXcd const& op = {}) const; /// LDOS at the given position and sublattice for the energy range and broadening ArrayXXdCM calc_ldos(ArrayXd const& energy, double broadening, Cartesian position, string_view sublattice = "", bool reduce = true) const; /// LDOS for multiple positions determined by the given shape ArrayXXdCM calc_spatial_ldos(ArrayXd const& energy, double broadening, Shape const& shape, string_view sublattice = "") const; /// DOS for the given energy range and broadening ArrayXd calc_dos(ArrayXd const& energy, double broadening, idx_t num_random) const; /// Green's function matrix element (row, col) for the given energy range ArrayXcd calc_greens(idx_t row, idx_t col, ArrayXd const& energy, double broadening) const; /// Multiple Green's matrix elements for a single `row` and multiple `cols` std::vector<ArrayXcd> calc_greens_vector(idx_t row, std::vector<idx_t> const& cols, ArrayXd const& energy, double broadening) const; /// Kubo-Bastin conductivity in `direction` ("xx", "xy", etc.) ArrayXd calc_conductivity(ArrayXd const& chemical_potential, double broadening, double temperature, string_view direction, idx_t num_random, idx_t num_points) const; private: Model model; mutable kpm::Core core; mutable Chrono calculation_timer; ///< last calculation time }; } // namespace cpb
Unknown