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 == "" {
59 return errors.New("must provide -case-control-file")
61 if *caseControlColumn == "" {
62 return errors.New("must provide -case-control-column")
67 log.Println(http.ListenAndServe(*pprof, nil))
72 runner := arvadosContainerRunner{
73 Name: "lightning choose-samples",
74 Client: arvados.NewClientFromEnv(),
75 ProjectUUID: *projectUUID,
82 err = runner.TranslatePaths(inputDir, caseControlFilename)
86 runner.Args = []string{"choose-samples", "-local=true",
88 "-input-dir=" + *inputDir,
89 "-output-dir=/mnt/output",
90 "-case-control-file=" + *caseControlFilename,
91 "-case-control-column=" + *caseControlColumn,
92 "-training-set-size=" + fmt.Sprintf("%f", *trainingSetSize),
93 "-random-seed=" + fmt.Sprintf("%d", *randSeed),
95 runner.Args = append(runner.Args, cmd.filter.Args()...)
97 output, err = runner.Run()
101 fmt.Fprintln(stdout, output)
105 infiles, err := allFiles(*inputDir, matchGobFile)
109 if len(infiles) == 0 {
110 err = fmt.Errorf("no input files found in %s", *inputDir)
113 sort.Strings(infiles)
115 in0, err := open(infiles[0])
120 matchGenome, err := regexp.Compile(cmd.filter.MatchGenome)
122 err = fmt.Errorf("-match-genome: invalid regexp: %q", cmd.filter.MatchGenome)
126 var sampleIDs []string
127 err = DecodeLibrary(in0, strings.HasSuffix(infiles[0], ".gz"), func(ent *LibraryEntry) error {
128 for _, cg := range ent.CompactGenomes {
129 if matchGenome.MatchString(cg.Name) {
130 sampleIDs = append(sampleIDs, cg.Name)
140 if len(sampleIDs) == 0 {
141 err = fmt.Errorf("no genomes found matching regexp %q", cmd.filter.MatchGenome)
144 sort.Strings(sampleIDs)
145 caseControl, err := cmd.loadCaseControlFiles(*caseControlFilename, *caseControlColumn, sampleIDs)
149 if len(caseControl) == 0 {
150 err = fmt.Errorf("fatal: 0 cases, 0 controls, nothing to do")
154 var trainingSet, validationSet []int
155 for i := range caseControl {
156 trainingSet = append(trainingSet, i)
158 sort.Ints(trainingSet)
159 wantlen := int(*trainingSetSize)
160 if *trainingSetSize <= 1 {
161 wantlen = int(*trainingSetSize * float64(len(trainingSet)))
163 randsrc := rand.NewSource(*randSeed)
164 for tslen := len(trainingSet); tslen > wantlen; {
165 i := int(randsrc.Int63()) % tslen
166 validationSet = append(validationSet, trainingSet[i])
168 trainingSet[i] = trainingSet[tslen]
169 trainingSet = trainingSet[:tslen]
171 sort.Ints(trainingSet)
172 sort.Ints(validationSet)
174 samplesFilename := *outputDir + "/samples.csv"
175 log.Infof("writing sample metadata to %s", samplesFilename)
177 f, err = os.Create(samplesFilename)
182 _, err = fmt.Fprint(f, "Index,SampleID,CaseControl,TrainingValidation\n")
186 tsi := 0 // next idx in training set
187 vsi := 0 // next idx in validation set
188 for i, name := range sampleIDs {
190 if len(trainingSet) > tsi && trainingSet[tsi] == i {
198 } else if len(validationSet) > vsi && validationSet[vsi] == i {
207 _, err = fmt.Fprintf(f, "%d,%s,%s,%s\n", i, trimFilenameForLabel(name), cc, tv)
209 err = fmt.Errorf("write %s: %w", samplesFilename, err)
215 err = fmt.Errorf("close %s: %w", samplesFilename, err)
221 // Read case/control file(s). Returned map m has m[i]==true if
222 // sampleIDs[i] is case, m[i]==false if sampleIDs[i] is control.
223 func (cmd *chooseSamples) loadCaseControlFiles(path, colname string, sampleIDs []string) (map[int]bool, error) {
224 infiles, err := allFiles(path, nil)
228 // index in sampleIDs => case(true) / control(false)
230 // index in sampleIDs => true if matched by multiple patterns in case/control files
231 dup := map[int]bool{}
232 for _, infile := range infiles {
233 f, err := open(infile)
237 buf, err := io.ReadAll(f)
243 for _, tsv := range bytes.Split(buf, []byte{'\n'}) {
247 split := strings.Split(string(tsv), "\t")
250 for col, name := range split {
257 return nil, fmt.Errorf("%s: no column named %q in header row %q", infile, colname, tsv)
261 if len(split) <= ccCol {
266 for i, name := range sampleIDs {
267 if strings.Contains(name, pattern) {
269 log.Warnf("pattern %q in %s matches multiple sample IDs (%q, %q)", pattern, infile, sampleIDs[found], name)
273 } else if _, ok := cc[i]; ok {
274 log.Warnf("multiple patterns match sample ID %q, omitting from cases/controls", name)
280 if split[ccCol] == "0" {
283 if split[ccCol] == "1" {
289 log.Warnf("pattern %q in %s does not match any genome IDs", pattern, infile)