18 "git.arvados.org/arvados.git/sdk/go/arvados"
19 "github.com/kshedden/gonpy"
20 "github.com/sirupsen/logrus"
21 log "github.com/sirupsen/logrus"
24 type exportNumpy struct {
28 func (cmd *exportNumpy) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
32 fmt.Fprintf(stderr, "%s\n", err)
35 flags := flag.NewFlagSet("", flag.ContinueOnError)
36 flags.SetOutput(stderr)
37 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
38 runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
39 projectUUID := flags.String("project", "", "project `UUID` for output data")
40 priority := flags.Int("priority", 500, "container request priority")
41 inputFilename := flags.String("i", "-", "input `file`")
42 outputFilename := flags.String("o", "-", "output `file`")
43 annotationsFilename := flags.String("output-annotations", "", "output `file` for tile variant annotations csv")
44 librefsFilename := flags.String("output-onehot2tilevar", "", "when using -one-hot, create csv `file` mapping column# to tag# and variant#")
45 labelsFilename := flags.String("output-labels", "", "output `file` for genome labels csv")
46 onehot := flags.Bool("one-hot", false, "recode tile variants as one-hot")
47 cmd.filter.Flags(flags)
48 err = flags.Parse(args)
49 if err == flag.ErrHelp {
52 } else if err != nil {
58 log.Println(http.ListenAndServe(*pprof, nil))
63 if *outputFilename != "-" {
64 err = errors.New("cannot specify output file in container mode: not implemented")
67 runner := arvadosContainerRunner{
68 Name: "lightning export-numpy",
69 Client: arvados.NewClientFromEnv(),
70 ProjectUUID: *projectUUID,
77 err = runner.TranslatePaths(inputFilename)
81 runner.Args = []string{"export-numpy", "-local=true",
82 fmt.Sprintf("-one-hot=%v", *onehot),
84 "-o", "/mnt/output/matrix.npy",
85 "-output-annotations", "/mnt/output/annotations.csv",
86 "-output-onehot2tilevar", "/mnt/output/onehot2tilevar.csv",
87 "-output-labels", "/mnt/output/labels.csv",
88 "-max-variants", fmt.Sprintf("%d", cmd.filter.MaxVariants),
89 "-min-coverage", fmt.Sprintf("%f", cmd.filter.MinCoverage),
90 "-max-tag", fmt.Sprintf("%d", cmd.filter.MaxTag),
93 output, err = runner.Run()
97 fmt.Fprintln(stdout, output+"/matrix.npy")
101 var input io.ReadCloser
102 if *inputFilename == "-" {
103 input = ioutil.NopCloser(stdin)
105 input, err = open(*inputFilename)
111 input = ioutil.NopCloser(bufio.NewReaderSize(input, 8*1024*1024))
112 tilelib := &tileLibrary{
114 retainTileSequences: true,
115 compactGenomes: map[string][]tileVariantID{},
117 err = tilelib.LoadGob(context.Background(), input, strings.HasSuffix(*inputFilename, ".gz"), nil)
126 log.Info("filtering")
127 cmd.filter.Apply(tilelib)
131 if *annotationsFilename != "" {
132 log.Infof("writing annotations")
133 var annow io.WriteCloser
134 annow, err = os.OpenFile(*annotationsFilename, os.O_CREATE|os.O_WRONLY, 0666)
139 err = (&annotatecmd{maxTileSize: 5000}).exportTileDiffs(annow, tilelib)
149 log.Info("building numpy array")
150 out, rows, cols, names := cgs2array(tilelib)
152 if *labelsFilename != "" {
153 log.Infof("writing labels to %s", *labelsFilename)
155 f, err = os.OpenFile(*labelsFilename, os.O_CREATE|os.O_WRONLY, 0777)
160 _, outBasename := path.Split(*outputFilename)
161 for i, name := range names {
162 _, err = fmt.Fprintf(f, "%d,%q,%q\n", i, trimFilenameForLabel(name), outBasename)
164 err = fmt.Errorf("write %s: %w", *labelsFilename, err)
170 err = fmt.Errorf("close %s: %w", *labelsFilename, err)
175 log.Info("writing numpy file")
176 var output io.WriteCloser
177 if *outputFilename == "-" {
178 output = nopCloser{stdout}
180 output, err = os.OpenFile(*outputFilename, os.O_CREATE|os.O_WRONLY, 0777)
186 bufw := bufio.NewWriter(output)
187 npw, err := gonpy.NewWriter(nopCloser{bufw})
192 log.Info("recoding to onehot")
193 recoded, librefs, recodedcols := recodeOnehot(out, cols)
194 out, cols = recoded, recodedcols
195 if *librefsFilename != "" {
196 log.Infof("writing onehot column mapping")
197 err = cmd.writeLibRefs(*librefsFilename, tilelib, librefs)
203 log.WithFields(logrus.Fields{
206 }).Info("writing numpy")
207 npw.Shape = []int{rows, cols}
220 func (*exportNumpy) writeLibRefs(fnm string, tilelib *tileLibrary, librefs []tileLibRef) error {
221 f, err := os.OpenFile(fnm, os.O_CREATE|os.O_WRONLY, 0666)
226 for i, libref := range librefs {
227 _, err = fmt.Fprintf(f, "%d,%d,%d\n", i, libref.Tag, libref.Variant)
235 func cgs2array(tilelib *tileLibrary) (data []int16, rows, cols int, cgnames []string) {
236 for name := range tilelib.compactGenomes {
237 cgnames = append(cgnames, name)
239 sort.Slice(cgnames, func(i, j int) bool {
240 return trimFilenameForLabel(cgnames[i]) < trimFilenameForLabel(cgnames[j])
243 rows = len(tilelib.compactGenomes)
244 for _, cg := range tilelib.compactGenomes {
250 // flag low-quality tile variants so we can change to -1 below
251 lowqual := make([]map[tileVariantID]bool, cols/2)
252 for tag, variants := range tilelib.variant {
254 for varidx, hash := range variants {
255 if len(tilelib.seq[hash]) == 0 {
257 lq = map[tileVariantID]bool{}
260 lq[tileVariantID(varidx+1)] = true
265 data = make([]int16, rows*cols)
266 for row, name := range cgnames {
267 for i, v := range tilelib.compactGenomes[name] {
268 if v > 0 && lowqual[i/2][v] {
269 data[row*cols+i] = -1
271 data[row*cols+i] = int16(v)
279 func recodeOnehot(in []int16, incols int) (out []int16, librefs []tileLibRef, outcols int) {
280 rows := len(in) / incols
281 maxvalue := make([]int16, incols)
282 for row := 0; row < rows; row++ {
283 for col := 0; col < incols; col++ {
284 if v := in[row*incols+col]; maxvalue[col] < v {
289 outcol := make([]int, incols)
291 for incol, maxv := range maxvalue {
292 outcol[incol] = outcols
296 for v := 1; v <= int(maxv); v++ {
297 librefs = append(librefs, tileLibRef{Tag: tagID(incol), Variant: tileVariantID(v)})
301 log.Printf("recodeOnehot: dropped %d input cols with zero maxvalue", dropped)
303 out = make([]int16, rows*outcols)
304 for inidx, row := 0, 0; row < rows; row++ {
305 outrow := out[row*outcols:]
306 for col := 0; col < incols; col++ {
307 if v := in[inidx]; v > 0 {
308 outrow[outcol[col]+int(v)-1] = 1
316 type nopCloser struct {
320 func (nopCloser) Close() error { return nil }
322 func trimFilenameForLabel(s string) string {
323 if i := strings.LastIndex(s, "/"); i >= 0 {
326 s = strings.TrimSuffix(s, ".gz")
327 s = strings.TrimSuffix(s, ".fa")
328 s = strings.TrimSuffix(s, ".fasta")
329 s = strings.TrimSuffix(s, ".1")
330 s = strings.TrimSuffix(s, ".2")
331 s = strings.TrimSuffix(s, ".gz")
332 s = strings.TrimSuffix(s, ".vcf")