1 // Copyright (C) The Lightning Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
23 "git.arvados.org/arvados.git/sdk/go/arvados"
24 "github.com/klauspost/pgzip"
25 log "github.com/sirupsen/logrus"
28 type slicecmd struct{}
30 func (cmd *slicecmd) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
34 fmt.Fprintf(stderr, "%s\n", err)
37 flags := flag.NewFlagSet("", flag.ContinueOnError)
38 flags.SetOutput(stderr)
39 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
40 runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
41 projectUUID := flags.String("project", "", "project `UUID` for output data")
42 priority := flags.Int("priority", 500, "container request priority")
43 preemptible := flags.Bool("preemptible", true, "request preemptible instance")
44 outputDir := flags.String("output-dir", "./out", "output `directory`")
45 tagsPerFile := flags.Int("tags-per-file", 50000, "tags per file (nfiles will be ~10M÷x)")
46 err = flags.Parse(args)
47 if err == flag.ErrHelp {
50 } else if err != nil {
53 inputDirs := flags.Args()
54 if len(inputDirs) == 0 {
55 err = errors.New("no input dirs specified")
61 log.Println(http.ListenAndServe(*pprof, nil))
66 runner := arvadosContainerRunner{
67 Name: "lightning slice",
68 Client: arvados.NewClientFromEnv(),
69 ProjectUUID: *projectUUID,
75 Preemptible: *preemptible,
77 for i := range inputDirs {
78 err = runner.TranslatePaths(&inputDirs[i])
83 runner.Args = append([]string{"slice", "-local=true",
85 "-output-dir", "/mnt/output",
88 output, err = runner.Run()
92 fmt.Fprintln(stdout, output)
96 err = Slice(*tagsPerFile, *outputDir, inputDirs)
103 // Read tags+tiles+genomes from srcdir, write to dstdir with (up to)
104 // the specified number of tags per file.
105 func Slice(tagsPerFile int, dstdir string, srcdirs []string) error {
107 for _, srcdir := range srcdirs {
108 files, err := allFiles(srcdir, matchGobFile)
112 infiles = append(infiles, files...)
114 // dirNamespace[dir] is an int in [0,len(dirNamespace)), used below to
115 // namespace variant numbers from different dirs.
116 dirNamespace := map[string]tileVariantID{}
117 for _, path := range infiles {
118 dir, _ := filepath.Split(path)
119 if _, ok := dirNamespace[dir]; !ok {
120 dirNamespace[dir] = tileVariantID(len(dirNamespace))
123 namespaces := tileVariantID(len(dirNamespace))
129 bufws []*bufio.Writer
133 countTileVariants int64
135 countReferences int64
138 throttle := throttle{Max: runtime.GOMAXPROCS(0)}
139 for _, infile := range infiles {
141 throttle.Go(func() error {
142 f, err := open(infile)
147 dir, _ := filepath.Split(infile)
148 namespace := dirNamespace[dir]
149 log.Printf("reading %s (namespace %d)", infile, namespace)
150 return DecodeLibrary(f, strings.HasSuffix(infile, ".gz"), func(ent *LibraryEntry) error {
151 if err := throttle.Err(); err != nil {
154 if len(ent.TagSet) > 0 {
155 tagsetOnce.Do(func() {
158 fs, bufws, gzws, encs, err = openOutFiles(dstdir, len(ent.TagSet), tagsPerFile)
163 for _, enc := range encs {
164 err = enc.Encode(LibraryEntry{TagSet: tagset})
172 if err := throttle.Err(); err != nil {
175 atomic.AddInt64(&countTileVariants, int64(len(ent.TileVariants)))
176 for _, tv := range ent.TileVariants {
177 tv.Variant = tv.Variant*namespaces + namespace
180 fileno = int(tv.Tag) / tagsPerFile
182 err := encs[fileno].Encode(LibraryEntry{
183 TileVariants: []TileVariant{tv},
189 // Here, each output file gets a
190 // CompactGenome entry for each
191 // genome, even if there are no
192 // variants in the relevant range.
193 // Easier for downstream code.
194 atomic.AddInt64(&countGenomes, int64(len(ent.CompactGenomes)))
195 for _, cg := range ent.CompactGenomes {
196 for i, v := range cg.Variants {
198 cg.Variants[i] = v*namespaces + namespace
201 for i, enc := range encs {
202 start := i * tagsPerFile
203 end := start + tagsPerFile
204 if max := len(cg.Variants)/2 + int(cg.StartTag); end > max {
207 if start < int(cg.StartTag) {
208 start = int(cg.StartTag)
210 var variants []tileVariantID
212 variants = cg.Variants[(start-int(cg.StartTag))*2 : (end-int(cg.StartTag))*2]
214 err := enc.Encode(LibraryEntry{CompactGenomes: []CompactGenome{{
217 StartTag: tagID(start),
218 EndTag: tagID(start + tagsPerFile),
225 // Write all ref seqs to the first
226 // slice. Easier for downstream code.
227 atomic.AddInt64(&countReferences, int64(len(ent.CompactSequences)))
228 if len(ent.CompactSequences) > 0 {
229 for _, cs := range ent.CompactSequences {
230 for _, tseq := range cs.TileSequences {
231 for i, libref := range tseq {
232 tseq[i].Variant = libref.Variant*namespaces + namespace
236 err := encs[0].Encode(LibraryEntry{CompactSequences: ent.CompactSequences})
246 if throttle.Err() != nil {
247 closeOutFiles(fs, bufws, gzws, encs)
248 return throttle.Err()
250 defer log.Printf("Total %d tile variants, %d genomes, %d reference sequences", countTileVariants, countGenomes, countReferences)
251 return closeOutFiles(fs, bufws, gzws, encs)
254 func openOutFiles(dstdir string, tags, tagsPerFile int) (fs []*os.File, bufws []*bufio.Writer, gzws []*pgzip.Writer, encs []*gob.Encoder, err error) {
255 nfiles := (tags + tagsPerFile - 1) / tagsPerFile
256 fs = make([]*os.File, nfiles)
257 bufws = make([]*bufio.Writer, nfiles)
258 gzws = make([]*pgzip.Writer, nfiles)
259 encs = make([]*gob.Encoder, nfiles)
260 for i := 0; i*tagsPerFile < tags; i++ {
261 fs[i], err = os.Create(dstdir + fmt.Sprintf("/library%04d.gob.gz", i))
265 bufws[i] = bufio.NewWriterSize(fs[i], 1<<26)
266 gzws[i] = pgzip.NewWriter(bufws[i])
267 encs[i] = gob.NewEncoder(gzws[i])
272 func closeOutFiles(fs []*os.File, bufws []*bufio.Writer, gzws []*pgzip.Writer, encs []*gob.Encoder) error {
274 for _, gzw := range gzws {
277 if err != nil && firstErr == nil {
282 for _, bufw := range bufws {
285 if err != nil && firstErr == nil {
290 for _, f := range fs {
293 if err != nil && firstErr == nil {