20 "git.arvados.org/arvados.git/sdk/go/arvados"
21 "github.com/arvados/lightning/hgvs"
22 log "github.com/sirupsen/logrus"
25 type annotatecmd struct {
28 tag2tagid map[string]tagID
31 func (cmd *annotatecmd) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
35 fmt.Fprintf(stderr, "%s\n", err)
38 flags := flag.NewFlagSet("", flag.ContinueOnError)
39 flags.SetOutput(stderr)
40 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
41 runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
42 projectUUID := flags.String("project", "", "project `UUID` for output data")
43 priority := flags.Int("priority", 500, "container request priority")
44 inputFilename := flags.String("i", "-", "input `file` (library)")
45 outputFilename := flags.String("o", "-", "output `file`")
46 flags.BoolVar(&cmd.variantHash, "variant-hash", false, "output variant hash instead of index")
47 flags.IntVar(&cmd.maxTileSize, "max-tile-size", 50000, "don't try to make annotations for tiles bigger than given `size`")
48 err = flags.Parse(args)
49 if err == flag.ErrHelp {
52 } else if err != nil {
58 log.Println(http.ListenAndServe(*pprof, nil))
62 if *outputFilename != "-" {
63 err = errors.New("cannot specify output file in container mode: not implemented")
66 runner := arvadosContainerRunner{
67 Name: "lightning annotate",
68 Client: arvados.NewClientFromEnv(),
69 ProjectUUID: *projectUUID,
74 err = runner.TranslatePaths(inputFilename)
78 runner.Args = []string{"annotate", "-local=true", fmt.Sprintf("-variant-hash=%v", cmd.variantHash), "-max-tile-size", strconv.Itoa(cmd.maxTileSize), "-i", *inputFilename, "-o", "/mnt/output/tilevariants.csv"}
80 output, err = runner.Run()
84 fmt.Fprintln(stdout, output+"/tilevariants.csv")
88 var input io.ReadCloser
89 if *inputFilename == "-" {
90 input = ioutil.NopCloser(stdin)
92 input, err = os.Open(*inputFilename)
99 var output io.WriteCloser
100 if *outputFilename == "-" {
101 output = nopCloser{stdout}
103 output, err = os.OpenFile(*outputFilename, os.O_CREATE|os.O_WRONLY, 0666)
109 bufw := bufio.NewWriterSize(output, 4*1024*1024)
111 tilelib := &tileLibrary{
113 retainTileSequences: true,
115 err = tilelib.LoadGob(context.Background(), input, strings.HasSuffix(*inputFilename, ".gz"), nil)
119 err = cmd.exportTileDiffs(bufw, tilelib)
138 func (cmd *annotatecmd) exportTileDiffs(outw io.Writer, tilelib *tileLibrary) error {
139 tagset := tilelib.taglib.Tags()
140 if len(tagset) == 0 {
141 return errors.New("cannot annotate library without tags")
143 taglen := len(tagset[0])
145 for name := range tilelib.refseqs {
146 refs = append(refs, name)
148 cmd.tag2tagid = make(map[string]tagID, len(tagset))
149 for tagid, tagseq := range tagset {
150 cmd.tag2tagid[string(tagseq)] = tagID(tagid)
153 log.Infof("len(refs) %d", len(refs))
155 outch := make(chan string, runtime.NumCPU()*2)
156 var outwg sync.WaitGroup
161 for s := range outch {
162 io.WriteString(outw, s)
168 for _, refcs := range tilelib.refseqs {
172 throttle := &throttle{Max: runtime.NumCPU()*2 + nseqs*2 + 1}
173 defer throttle.Wait()
175 for _, refname := range refs {
177 refcs := tilelib.refseqs[refname]
178 var seqnames []string
179 for seqname := range refcs {
180 seqnames = append(seqnames, seqname)
182 sort.Strings(seqnames)
183 for _, seqname := range seqnames {
187 defer throttle.Release()
188 throttle.Report(cmd.annotateSequence(throttle, outch, tilelib, taglen, refname, seqname, refcs[seqname], len(refs) > 1))
193 return throttle.Err()
196 func (cmd *annotatecmd) annotateSequence(throttle *throttle, outch chan<- string, tilelib *tileLibrary, taglen int, refname, seqname string, reftiles []tileLibRef, refnamecol bool) error {
198 // tilestart[123] is the index into refseq
199 // where the tile for tag 123 was placed.
200 tilestart := map[tagID]int{}
201 tileend := map[tagID]int{}
202 for _, libref := range reftiles {
203 if libref.Variant < 1 {
204 return fmt.Errorf("reference %q seq %q uses variant zero at tag %d", refname, seqname, libref.Tag)
206 seq := tilelib.TileVariantSequence(libref)
207 if len(seq) < taglen {
208 return fmt.Errorf("reference %q seq %q uses tile %d variant %d with sequence len %d < taglen %d", refname, seqname, libref.Tag, libref.Variant, len(seq), taglen)
211 if len(refseq) == 0 {
214 tilestart[libref.Tag] = len(refseq) - overlap
215 refseq = append(refseq, seq[overlap:]...)
216 tileend[libref.Tag] = len(refseq)
218 log.Infof("seq %s len(refseq) %d len(tilestart) %d", seqname, len(refseq), len(tilestart))
219 for tag, tvs := range tilelib.variant {
221 refstart, ok := tilestart[tag]
223 // Tag didn't place on this
224 // reference sequence. (It
225 // might place on the same
226 // chromosome in a genome
227 // anyway, but we don't output
228 // the annotations that would
232 for variant := 1; variant <= len(tvs); variant++ {
233 variant, hash := tileVariantID(variant), tvs[variant-1]
234 tileseq := tilelib.TileVariantSequence(tileLibRef{Tag: tag, Variant: variant})
235 if len(tileseq) == 0 {
237 } else if len(tileseq) < taglen {
238 return fmt.Errorf("tilevar %d,%d has sequence len %d < taglen %d", tag, variant, len(tileseq), taglen)
241 endtag := string(tileseq[len(tileseq)-taglen:])
242 if endtagid, ok := cmd.tag2tagid[endtag]; !ok {
243 // Tile variant doesn't end on a tag, so it can only place at the end of a chromosome.
244 refpart = refseq[refstart:]
245 log.Warnf("%x tilevar %d,%d endtag not in ref: %s", hash[:13], tag, variant, endtag)
246 } else if refendtagstart, ok := tilestart[endtagid]; !ok {
247 // Ref ends a chromsome with a (possibly very large) variant of this tile, but genomes with this tile don't.
248 // Give up. (TODO: something smarter)
249 log.Debugf("%x not annotating tilevar %d,%d because end tag %d is not in ref", hash[:13], tag, variant, endtagid)
252 // Non-terminal tile vs. non-terminal reference.
253 refpart = refseq[refstart : refendtagstart+taglen]
254 log.Tracef("\n%x tilevar %d,%d endtag %s endtagid %d refendtagstart %d", hash[:13], tag, variant, endtag, endtagid, refendtagstart)
256 if len(refpart) > cmd.maxTileSize {
257 log.Warnf("%x tilevar %d,%d skipping long diff, ref %s seq %s pos %d ref len %d", hash[:13], tag, variant, refname, seqname, refstart, len(refpart))
260 if len(tileseq) > cmd.maxTileSize {
261 log.Warnf("%x tilevar %d,%d skipping long diff, ref %s seq %s variant len %d", hash[:13], tag, variant, refname, seqname, len(tileseq))
264 // log.Printf("\n%x @ refstart %d \n< %s\n> %s\n", tv.Blake2b, refstart, refpart, tileseq)
268 defer throttle.Release()
269 diffs, _ := hgvs.Diff(strings.ToUpper(string(refpart)), strings.ToUpper(string(tileseq)), 0)
270 for _, diff := range diffs {
271 diff.Position += refstart
274 varid = fmt.Sprintf("%x", hash)[:13]
276 varid = fmt.Sprintf("%d", variant)
280 refnamefield = "," + trimFilenameForLabel(refname)
282 outch <- fmt.Sprintf("%d,%s%s,%s:g.%s\n", tag, varid, refnamefield, seqname, diff.String())