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 {
29 tag2tagid map[string]tagID
30 reportAnnotation func(tag tagID, outcol int, variant tileVariantID, refname string, seqname string, pdi hgvs.Variant)
33 func (cmd *annotatecmd) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
37 fmt.Fprintf(stderr, "%s\n", err)
40 flags := flag.NewFlagSet("", flag.ContinueOnError)
41 flags.SetOutput(stderr)
42 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
43 runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
44 projectUUID := flags.String("project", "", "project `UUID` for output data")
45 priority := flags.Int("priority", 500, "container request priority")
46 inputFilename := flags.String("i", "-", "input `file` (library)")
47 outputFilename := flags.String("o", "-", "output `file`")
48 flags.BoolVar(&cmd.variantHash, "variant-hash", false, "output variant hash instead of index")
49 flags.IntVar(&cmd.maxTileSize, "max-tile-size", 50000, "don't try to make annotations for tiles bigger than given `size`")
50 err = flags.Parse(args)
51 if err == flag.ErrHelp {
54 } else if err != nil {
60 log.Println(http.ListenAndServe(*pprof, nil))
64 if *outputFilename != "-" {
65 err = errors.New("cannot specify output file in container mode: not implemented")
68 runner := arvadosContainerRunner{
69 Name: "lightning annotate",
70 Client: arvados.NewClientFromEnv(),
71 ProjectUUID: *projectUUID,
76 err = runner.TranslatePaths(inputFilename)
80 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"}
82 output, err = runner.Run()
86 fmt.Fprintln(stdout, output+"/tilevariants.csv")
90 var input io.ReadCloser
91 if *inputFilename == "-" {
92 input = ioutil.NopCloser(stdin)
94 input, err = os.Open(*inputFilename)
101 var output io.WriteCloser
102 if *outputFilename == "-" {
103 output = nopCloser{stdout}
105 output, err = os.OpenFile(*outputFilename, os.O_CREATE|os.O_WRONLY, 0666)
111 bufw := bufio.NewWriterSize(output, 4*1024*1024)
113 tilelib := &tileLibrary{
115 retainTileSequences: true,
117 err = tilelib.LoadGob(context.Background(), input, strings.HasSuffix(*inputFilename, ".gz"), nil)
121 err = cmd.exportTileDiffs(bufw, tilelib)
140 func (cmd *annotatecmd) exportTileDiffs(outw io.Writer, tilelib *tileLibrary) error {
141 tagset := tilelib.taglib.Tags()
142 if len(tagset) == 0 {
143 return errors.New("cannot annotate library without tags")
145 taglen := len(tagset[0])
147 for name := range tilelib.refseqs {
148 refs = append(refs, name)
150 cmd.tag2tagid = make(map[string]tagID, len(tagset))
151 for tagid, tagseq := range tagset {
152 cmd.tag2tagid[string(tagseq)] = tagID(tagid)
155 log.Infof("len(refs) %d", len(refs))
157 outch := make(chan string, runtime.NumCPU()*2)
158 var outwg sync.WaitGroup
163 for s := range outch {
164 io.WriteString(outw, s)
170 for _, refcs := range tilelib.refseqs {
174 throttle := &throttle{Max: runtime.NumCPU()*2 + nseqs*2 + 1}
175 defer throttle.Wait()
177 for _, refname := range refs {
179 refcs := tilelib.refseqs[refname]
180 var seqnames []string
181 for seqname := range refcs {
182 seqnames = append(seqnames, seqname)
184 sort.Strings(seqnames)
185 for _, seqname := range seqnames {
188 if throttle.Err() != nil {
192 defer throttle.Release()
193 throttle.Report(cmd.annotateSequence(throttle, outch, tilelib, taglen, refname, seqname, refcs[seqname], len(refs) > 1))
198 return throttle.Err()
201 func (cmd *annotatecmd) annotateSequence(throttle *throttle, outch chan<- string, tilelib *tileLibrary, taglen int, refname, seqname string, reftiles []tileLibRef, refnamecol bool) error {
204 refnamefield = "," + trimFilenameForLabel(refname)
207 // tilestart[123] is the index into refseq
208 // where the tile for tag 123 was placed.
209 tilestart := map[tagID]int{}
210 tileend := map[tagID]int{}
211 for _, libref := range reftiles {
212 if libref.Variant < 1 {
213 return fmt.Errorf("reference %q seq %q uses variant zero at tag %d", refname, seqname, libref.Tag)
215 seq := tilelib.TileVariantSequence(libref)
216 if len(seq) < taglen {
217 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)
220 if len(refseq) == 0 {
223 tilestart[libref.Tag] = len(refseq) - overlap
224 refseq = append(refseq, seq[overlap:]...)
225 tileend[libref.Tag] = len(refseq)
227 log.Infof("seq %s len(refseq) %d len(tilestart) %d", seqname, len(refseq), len(tilestart))
228 // outtag is tag's index in the subset of tags that aren't
229 // dropped. If there are 10M tags and half are dropped by
230 // dropTiles, tag ranges from 0 to 10M-1 and outtag ranges
233 // IOW, in the matrix built by cgs2array(), {tag} is
234 // represented by columns {outtag}*2 and {outtag}*2+1.
236 for tag, tvs := range tilelib.variant {
237 if len(cmd.dropTiles) > tag && cmd.dropTiles[tag] {
242 // Must shadow outcol var to use safely in goroutine below.
244 refstart, ok := tilestart[tag]
246 // Tag didn't place on this reference
247 // sequence. (It might place on the same
248 // chromosome in a genome anyway, but we don't
249 // output the annotations that would result.)
250 // outch <- fmt.Sprintf("%d,%d,-1%s\n", tag, outcol, refnamefield)
253 for variant := 1; variant <= len(tvs); variant++ {
254 variant, hash := tileVariantID(variant), tvs[variant-1]
255 tileseq := tilelib.TileVariantSequence(tileLibRef{Tag: tag, Variant: variant})
256 if len(tileseq) == 0 {
258 } else if len(tileseq) < taglen {
259 return fmt.Errorf("tilevar %d,%d has sequence len %d < taglen %d", tag, variant, len(tileseq), taglen)
262 endtag := string(tileseq[len(tileseq)-taglen:])
263 if endtagid, ok := cmd.tag2tagid[endtag]; !ok {
264 // Tile variant doesn't end on a tag, so it can only place at the end of a chromosome.
265 refpart = refseq[refstart:]
266 log.Warnf("%x tilevar %d,%d endtag not in ref: %s", hash[:13], tag, variant, endtag)
267 } else if refendtagstart, ok := tilestart[endtagid]; !ok {
268 // Ref ends a chromsome with a (possibly very large) variant of this tile, but genomes with this tile don't.
269 // Give up. (TODO: something smarter)
270 log.Debugf("%x not annotating tilevar %d,%d because end tag %d is not in ref", hash[:13], tag, variant, endtagid)
273 // Non-terminal tile vs. non-terminal reference.
274 refpart = refseq[refstart : refendtagstart+taglen]
275 log.Tracef("\n%x tilevar %d,%d endtag %s endtagid %d refendtagstart %d", hash[:13], tag, variant, endtag, endtagid, refendtagstart)
277 if len(refpart) > cmd.maxTileSize {
278 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))
281 if len(tileseq) > cmd.maxTileSize {
282 log.Warnf("%x tilevar %d,%d skipping long diff, ref %s seq %s variant len %d", hash[:13], tag, variant, refname, seqname, len(tileseq))
285 // log.Printf("\n%x @ refstart %d \n< %s\n> %s\n", tv.Blake2b, refstart, refpart, tileseq)
289 defer throttle.Release()
290 diffs, _ := hgvs.Diff(strings.ToUpper(string(refpart)), strings.ToUpper(string(tileseq)), 0)
291 for _, diff := range diffs {
292 diff.Position += refstart
295 varid = fmt.Sprintf("%x", hash)[:13]
297 varid = fmt.Sprintf("%d", variant)
299 outch <- fmt.Sprintf("%d,%d,%s%s,%s:g.%s\n", tag, outcol, varid, refnamefield, seqname, diff.String())
300 if cmd.reportAnnotation != nil {
301 cmd.reportAnnotation(tag, outcol, variant, refname, seqname, diff)