17 "git.arvados.org/arvados.git/sdk/go/arvados"
18 "github.com/kshedden/gonpy"
19 log "github.com/sirupsen/logrus"
22 type exportNumpy struct {
26 func (cmd *exportNumpy) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
30 fmt.Fprintf(stderr, "%s\n", err)
33 flags := flag.NewFlagSet("", flag.ContinueOnError)
34 flags.SetOutput(stderr)
35 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
36 runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
37 projectUUID := flags.String("project", "", "project `UUID` for output data")
38 priority := flags.Int("priority", 500, "container request priority")
39 inputFilename := flags.String("i", "-", "input `file`")
40 outputFilename := flags.String("o", "-", "output `file`")
41 annotationsFilename := flags.String("output-annotations", "", "output `file` for tile variant annotations tsv")
42 librefsFilename := flags.String("output-onehot2tilevar", "", "when using -one-hot, create tsv `file` mapping column# to tag# and variant#")
43 onehot := flags.Bool("one-hot", false, "recode tile variants as one-hot")
44 cmd.filter.Flags(flags)
45 err = flags.Parse(args)
46 if err == flag.ErrHelp {
49 } else if err != nil {
55 log.Println(http.ListenAndServe(*pprof, nil))
60 if *outputFilename != "-" {
61 err = errors.New("cannot specify output file in container mode: not implemented")
64 runner := arvadosContainerRunner{
65 Name: "lightning export-numpy",
66 Client: arvados.NewClientFromEnv(),
67 ProjectUUID: *projectUUID,
72 err = runner.TranslatePaths(inputFilename)
76 runner.Args = []string{"export-numpy", "-local=true",
77 fmt.Sprintf("-one-hot=%v", *onehot),
79 "-o", "/mnt/output/matrix.npy",
80 "-output-annotations", "/mnt/output/annotations.tsv",
81 "-output-onehot2tilevar", "/mnt/output/onehot2tilevar.tsv",
82 "-max-variants", fmt.Sprintf("%d", cmd.filter.MaxVariants),
83 "-min-coverage", fmt.Sprintf("%f", cmd.filter.MinCoverage),
84 "-max-tag", fmt.Sprintf("%d", cmd.filter.MaxTag),
87 output, err = runner.Run()
91 fmt.Fprintln(stdout, output+"/matrix.npy")
95 var input io.ReadCloser
96 if *inputFilename == "-" {
97 input = ioutil.NopCloser(stdin)
99 input, err = os.Open(*inputFilename)
105 tilelib := &tileLibrary{
107 retainTileSequences: true,
108 compactGenomes: map[string][]tileVariantID{},
110 err = tilelib.LoadGob(context.Background(), input, strings.HasSuffix(*inputFilename, ".gz"), nil)
119 log.Info("filtering")
120 cmd.filter.Apply(tilelib)
124 if *annotationsFilename != "" {
125 log.Infof("writing annotations")
126 var annow io.WriteCloser
127 annow, err = os.OpenFile(*annotationsFilename, os.O_CREATE|os.O_WRONLY, 0666)
132 err = (&annotatecmd{maxTileSize: 5000}).exportTileDiffs(annow, tilelib)
142 log.Info("building numpy array")
143 out, rows, cols := cgs2array(tilelib.compactGenomes)
144 var output io.WriteCloser
145 if *outputFilename == "-" {
146 output = nopCloser{stdout}
148 output, err = os.OpenFile(*outputFilename, os.O_CREATE|os.O_WRONLY, 0777)
154 bufw := bufio.NewWriter(output)
155 npw, err := gonpy.NewWriter(nopCloser{bufw})
160 log.Info("recoding to onehot")
161 recoded, librefs, recodedcols := recodeOnehot(out, cols)
162 out, cols = recoded, recodedcols
163 if *librefsFilename != "" {
164 log.Infof("writing onehot column mapping")
165 err = cmd.writeLibRefs(*librefsFilename, tilelib, librefs)
171 log.Info("writing numpy")
172 npw.Shape = []int{rows, cols}
185 func (*exportNumpy) writeLibRefs(fnm string, tilelib *tileLibrary, librefs []tileLibRef) error {
186 f, err := os.OpenFile(fnm, os.O_CREATE|os.O_WRONLY, 0666)
191 for i, libref := range librefs {
192 _, err = fmt.Fprintf(f, "%d\t%d\t%d\n", i, libref.Tag, libref.Variant)
200 func cgs2array(cgs map[string][]tileVariantID) (data []uint16, rows, cols int) {
202 for name := range cgs {
203 cgnames = append(cgnames, name)
205 sort.Strings(cgnames)
208 for _, cg := range cgs {
213 data = make([]uint16, rows*cols)
214 for row, name := range cgnames {
215 for i, v := range cgs[name] {
216 data[row*cols+i] = uint16(v)
222 func recodeOnehot(in []uint16, incols int) (out []uint16, librefs []tileLibRef, outcols int) {
223 rows := len(in) / incols
224 maxvalue := make([]uint16, incols)
225 for row := 0; row < rows; row++ {
226 for col := 0; col < incols; col++ {
227 if v := in[row*incols+col]; maxvalue[col] < v {
232 outcol := make([]int, incols)
234 for incol, maxv := range maxvalue {
235 outcol[incol] = outcols
239 for v := 1; v <= int(maxv); v++ {
240 librefs = append(librefs, tileLibRef{Tag: tagID(incol), Variant: tileVariantID(v)})
244 log.Printf("recodeOnehot: dropped %d input cols with zero maxvalue", dropped)
246 out = make([]uint16, rows*outcols)
247 for inidx, row := 0, 0; row < rows; row++ {
248 outrow := out[row*outcols:]
249 for col := 0; col < incols; col++ {
250 if v := in[inidx]; v > 0 {
251 outrow[outcol[col]+int(v)-1] = 1
259 type nopCloser struct {
263 func (nopCloser) Close() error { return nil }