More memory for pca.
[lightning.git] / exportnumpy.go
1 package main
2
3 import (
4         "bufio"
5         "errors"
6         "flag"
7         "fmt"
8         "io"
9         "io/ioutil"
10         "net/http"
11         _ "net/http/pprof"
12         "os"
13         "sort"
14
15         "git.arvados.org/arvados.git/sdk/go/arvados"
16         "github.com/kshedden/gonpy"
17         log "github.com/sirupsen/logrus"
18 )
19
20 type exportNumpy struct{}
21
22 func (cmd *exportNumpy) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
23         var err error
24         defer func() {
25                 if err != nil {
26                         fmt.Fprintf(stderr, "%s\n", err)
27                 }
28         }()
29         flags := flag.NewFlagSet("", flag.ContinueOnError)
30         flags.SetOutput(stderr)
31         pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
32         runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
33         projectUUID := flags.String("project", "", "project `UUID` for output data")
34         priority := flags.Int("priority", 500, "container request priority")
35         inputFilename := flags.String("i", "-", "input `file`")
36         outputFilename := flags.String("o", "-", "output `file`")
37         onehot := flags.Bool("one-hot", false, "recode tile variants as one-hot")
38         err = flags.Parse(args)
39         if err == flag.ErrHelp {
40                 err = nil
41                 return 0
42         } else if err != nil {
43                 return 2
44         }
45
46         if *pprof != "" {
47                 go func() {
48                         log.Println(http.ListenAndServe(*pprof, nil))
49                 }()
50         }
51
52         if !*runlocal {
53                 if *outputFilename != "-" {
54                         err = errors.New("cannot specify output file in container mode: not implemented")
55                         return 1
56                 }
57                 runner := arvadosContainerRunner{
58                         Name:        "lightning export-numpy",
59                         Client:      arvados.NewClientFromEnv(),
60                         ProjectUUID: *projectUUID,
61                         RAM:         64000000000,
62                         VCPUs:       2,
63                         Priority:    *priority,
64                 }
65                 err = runner.TranslatePaths(inputFilename)
66                 if err != nil {
67                         return 1
68                 }
69                 runner.Args = []string{"export-numpy", "-local=true", fmt.Sprintf("-one-hot=%v", *onehot), "-i", *inputFilename, "-o", "/mnt/output/library.npy"}
70                 var output string
71                 output, err = runner.Run()
72                 if err != nil {
73                         return 1
74                 }
75                 fmt.Fprintln(stdout, output+"/library.npy")
76                 return 0
77         }
78
79         var input io.ReadCloser
80         if *inputFilename == "-" {
81                 input = ioutil.NopCloser(stdin)
82         } else {
83                 input, err = os.Open(*inputFilename)
84                 if err != nil {
85                         return 1
86                 }
87                 defer input.Close()
88         }
89         cgs, err := ReadCompactGenomes(input)
90         if err != nil {
91                 return 1
92         }
93         err = input.Close()
94         if err != nil {
95                 return 1
96         }
97         sort.Slice(cgs, func(i, j int) bool { return cgs[i].Name < cgs[j].Name })
98         cols := 0
99         for _, cg := range cgs {
100                 if cols < len(cg.Variants) {
101                         cols = len(cg.Variants)
102                 }
103         }
104         rows := len(cgs)
105         out := make([]uint16, rows*cols)
106         for row, cg := range cgs {
107                 for i, v := range cg.Variants {
108                         out[row*cols+i] = uint16(v)
109                 }
110         }
111
112         var output io.WriteCloser
113         if *outputFilename == "-" {
114                 output = nopCloser{stdout}
115         } else {
116                 output, err = os.OpenFile(*outputFilename, os.O_CREATE|os.O_WRONLY, 0777)
117                 if err != nil {
118                         return 1
119                 }
120                 defer output.Close()
121         }
122         bufw := bufio.NewWriter(output)
123         npw, err := gonpy.NewWriter(nopCloser{bufw})
124         if err != nil {
125                 return 1
126         }
127         if *onehot {
128                 out, cols := recodeOnehot(out, cols)
129                 npw.Shape = []int{rows, cols}
130                 npw.WriteUint8(out)
131         } else {
132                 npw.Shape = []int{rows, cols}
133                 npw.WriteUint16(out)
134         }
135         err = bufw.Flush()
136         if err != nil {
137                 return 1
138         }
139         err = output.Close()
140         if err != nil {
141                 return 1
142         }
143         return 0
144 }
145
146 func recodeOnehot(in []uint16, incols int) ([]uint8, int) {
147         rows := len(in) / incols
148         maxvalue := make([]uint16, incols)
149         for row := 0; row < rows; row++ {
150                 for col := 0; col < incols; col++ {
151                         if v := in[row*incols+col]; maxvalue[col] < v {
152                                 maxvalue[col] = v
153                         }
154                 }
155         }
156         outcol := make([]int, incols)
157         outcols := 0
158         for incol, v := range maxvalue {
159                 outcol[incol] = outcols
160                 outcols += int(v)
161         }
162         out := make([]uint8, rows*outcols)
163         for row := 0; row < rows; row++ {
164                 for col := 0; col < incols; col++ {
165                         if v := in[row*incols+col]; v > 0 {
166                                 out[row*outcols+outcol[col]+int(v)-1] = 1
167                         }
168                 }
169         }
170         return out, outcols
171 }
172
173 type nopCloser struct {
174         io.Writer
175 }
176
177 func (nopCloser) Close() error { return nil }