1 // Copyright (C) The Lightning Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
21 "git.arvados.org/arvados.git/sdk/go/arvados"
22 log "github.com/sirupsen/logrus"
25 type chooseSamples struct {
29 func (cmd *chooseSamples) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
30 err := cmd.run(prog, args, stdin, stdout, stderr)
32 fmt.Fprintf(stderr, "%s\n", err)
38 func (cmd *chooseSamples) run(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) error {
39 flags := flag.NewFlagSet("", flag.ContinueOnError)
40 flags.SetOutput(stderr)
41 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
42 runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
43 projectUUID := flags.String("project", "", "project `UUID` for output data")
44 priority := flags.Int("priority", 500, "container request priority")
45 inputDir := flags.String("input-dir", "./in", "input `directory`")
46 outputDir := flags.String("output-dir", "./out", "output `directory`")
47 trainingSetSize := flags.Float64("training-set-size", 0.8, "number (or proportion, if <=1) of eligible samples to assign to the training set")
48 caseControlFilename := flags.String("case-control-file", "", "tsv file or directory indicating cases and controls (if directory, all .tsv files will be read)")
49 caseControlColumn := flags.String("case-control-column", "", "name of case/control column in case-control files (value must be 0 for control, 1 for case)")
50 randSeed := flags.Int64("random-seed", 0, "PRNG seed")
51 cmd.filter.Flags(flags)
52 err := flags.Parse(args)
53 if err == flag.ErrHelp {
55 } else if err != nil {
58 if (*caseControlFilename == "") != (*caseControlColumn == "") {
59 return errors.New("must provide both -case-control-file and -case-control-column, or neither")
64 log.Println(http.ListenAndServe(*pprof, nil))
69 runner := arvadosContainerRunner{
70 Name: "lightning choose-samples",
71 Client: arvados.NewClientFromEnv(),
72 ProjectUUID: *projectUUID,
79 err = runner.TranslatePaths(inputDir, caseControlFilename)
83 runner.Args = []string{"choose-samples", "-local=true",
85 "-input-dir=" + *inputDir,
86 "-output-dir=/mnt/output",
87 "-case-control-file=" + *caseControlFilename,
88 "-case-control-column=" + *caseControlColumn,
89 "-training-set-size=" + fmt.Sprintf("%f", *trainingSetSize),
90 "-random-seed=" + fmt.Sprintf("%d", *randSeed),
92 runner.Args = append(runner.Args, cmd.filter.Args()...)
94 output, err = runner.Run()
98 fmt.Fprintln(stdout, output)
102 infiles, err := allFiles(*inputDir, matchGobFile)
106 if len(infiles) == 0 {
107 err = fmt.Errorf("no input files found in %s", *inputDir)
110 sort.Strings(infiles)
112 in0, err := open(infiles[0])
117 matchGenome, err := regexp.Compile(cmd.filter.MatchGenome)
119 err = fmt.Errorf("-match-genome: invalid regexp: %q", cmd.filter.MatchGenome)
123 var sampleIDs []string
124 err = DecodeLibrary(in0, strings.HasSuffix(infiles[0], ".gz"), func(ent *LibraryEntry) error {
125 for _, cg := range ent.CompactGenomes {
126 if matchGenome.MatchString(cg.Name) {
127 sampleIDs = append(sampleIDs, cg.Name)
137 if len(sampleIDs) == 0 {
138 err = fmt.Errorf("no genomes found matching regexp %q", cmd.filter.MatchGenome)
141 sort.Strings(sampleIDs)
142 caseControl, err := cmd.loadCaseControlFiles(*caseControlFilename, *caseControlColumn, sampleIDs)
146 if len(caseControl) == 0 {
147 err = fmt.Errorf("fatal: 0 cases, 0 controls, nothing to do")
151 var trainingSet, validationSet []int
152 for i := range caseControl {
153 trainingSet = append(trainingSet, i)
155 sort.Ints(trainingSet)
156 wantlen := int(*trainingSetSize)
157 if *trainingSetSize <= 1 {
158 wantlen = int(*trainingSetSize * float64(len(trainingSet)))
160 randsrc := rand.NewSource(*randSeed)
161 for tslen := len(trainingSet); tslen > wantlen; {
162 i := int(randsrc.Int63()) % tslen
163 validationSet = append(validationSet, trainingSet[i])
165 trainingSet[i] = trainingSet[tslen]
166 trainingSet = trainingSet[:tslen]
168 sort.Ints(trainingSet)
169 sort.Ints(validationSet)
171 samplesFilename := *outputDir + "/samples.csv"
172 log.Infof("writing sample metadata to %s", samplesFilename)
174 f, err = os.Create(samplesFilename)
179 _, err = fmt.Fprint(f, "Index,SampleID,CaseControl,TrainingValidation\n")
183 tsi := 0 // next idx in training set
184 vsi := 0 // next idx in validation set
185 for i, name := range sampleIDs {
187 if len(trainingSet) > tsi && trainingSet[tsi] == i {
195 } else if len(validationSet) > vsi && validationSet[vsi] == i {
204 _, err = fmt.Fprintf(f, "%d,%s,%s,%s\n", i, trimFilenameForLabel(name), cc, tv)
206 err = fmt.Errorf("write %s: %w", samplesFilename, err)
212 err = fmt.Errorf("close %s: %w", samplesFilename, err)
218 // Read case/control file(s). Returned map m has m[i]==true if
219 // sampleIDs[i] is case, m[i]==false if sampleIDs[i] is control.
220 func (cmd *chooseSamples) loadCaseControlFiles(path, colname string, sampleIDs []string) (map[int]bool, error) {
222 // all samples are control group
223 cc := make(map[int]bool, len(sampleIDs))
224 for i := range sampleIDs {
229 infiles, err := allFiles(path, nil)
233 // index in sampleIDs => case(true) / control(false)
235 // index in sampleIDs => true if matched by multiple patterns in case/control files
236 dup := map[int]bool{}
237 for _, infile := range infiles {
238 f, err := open(infile)
242 buf, err := io.ReadAll(f)
248 for _, tsv := range bytes.Split(buf, []byte{'\n'}) {
252 split := strings.Split(string(tsv), "\t")
255 for col, name := range split {
262 return nil, fmt.Errorf("%s: no column named %q in header row %q", infile, colname, tsv)
266 if len(split) <= ccCol {
271 for i, name := range sampleIDs {
272 if strings.Contains(name, pattern) {
274 log.Warnf("pattern %q in %s matches multiple sample IDs (%q, %q)", pattern, infile, sampleIDs[found], name)
278 } else if _, ok := cc[i]; ok {
279 log.Warnf("multiple patterns match sample ID %q, omitting from cases/controls", name)
285 if split[ccCol] == "0" {
288 if split[ccCol] == "1" {
294 log.Warnf("pattern %q in %s does not match any genome IDs", pattern, infile)