-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
295 lines (271 loc) · 8.55 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package main
import (
"encoding/csv"
"fmt"
"io"
"math"
"os"
"path"
"sort"
"strconv"
"strings"
"github.com/rhagenson/swsc/internal/metrics"
"github.com/rhagenson/swsc/internal/nexus"
"github.com/rhagenson/swsc/internal/pfinder"
"github.com/rhagenson/swsc/internal/uce"
"github.com/rhagenson/swsc/internal/ui"
"github.com/rhagenson/swsc/internal/utils"
"github.com/rhagenson/swsc/internal/windows"
"github.com/rhagenson/swsc/internal/writers"
"github.com/shenwei356/bio/seq"
"github.com/shenwei356/bio/seqio/fastx"
"github.com/spf13/pflag"
pb "gopkg.in/cheggaaa/pb.v1"
)
// Required flags
var (
fNex = pflag.String("nexus", "", "Nexus file to process (.nex)")
fFasta = pflag.String("fasta", "", "Multi-FASTA file to process (.fna/fasta)")
fUces = pflag.String("uces", "", "CSV file with UCE ranges, format: Name,Start,Stop (inclusive)")
fOutput = pflag.String("output", "", "Partition file to write (.csv)")
fCfg = pflag.String("cfg", "", "Config file for PartionFinder2 (.cfg)")
)
// General use flags
var (
fMinWin = pflag.Uint("minWin", 50, "Minimum window size")
fLargeCore = pflag.Bool("largeCore", false, "When a small and large core have equivalent metrics, choose the large core")
fNCandidates = pflag.Uint("candidates", 3, "Number of best candidates to search with")
fHelp = pflag.Bool("help", false, "Print help and exit")
)
// Metric flags
var (
fEntropy = pflag.Bool("entropy", false, "Calculate Shannon's entropy metric")
fGc = pflag.Bool("gc", false, "Calculate GC content metric")
// multi = pflag.Bool("multi", false, "Calculate multinomial distribution metric")
)
func setup() {
pflag.Parse()
if *fHelp {
pflag.Usage()
os.Exit(1)
}
// Failure states
switch {
case (*fNex == "") != (*fFasta == "" && *fUces == ""): // != used as XOR
pflag.Usage()
ui.Errorf("Must provide either nexus, or fasta and uces\n")
case *fOutput == "":
pflag.Usage()
ui.Errorf("Must provide output\n")
case *fNex != "" && !strings.HasSuffix(*fNex, ".nex"):
ui.Errorf("Input expected to end in .nex, got %s\n", path.Ext(*fNex))
case *fFasta != "" && !(strings.HasSuffix(*fFasta, ".fna") || strings.HasSuffix(*fFasta, ".fasta")):
ui.Errorf("FASTA expected to end in .fna, got %s\n", path.Ext(*fFasta))
case *fUces != "" && !strings.HasSuffix(*fUces, ".csv"):
ui.Errorf("UCEs expected to end in .csv, got %s\n", path.Ext(*fUces))
case *fOutput != "" && !strings.HasSuffix(*fOutput, ".csv"):
ui.Errorf("Output expected to end in .csv, got %s\n", path.Ext(*fOutput))
case *fCfg != "" && !strings.HasSuffix(*fCfg, ".cfg"):
ui.Errorf("Config expected to end in .cfg, got %s\n", path.Ext(*fCfg))
case *fEntropy == *fGc && (*fEntropy || *fGc):
ui.Errorf("Only one metric is allowed\n")
case !(*fEntropy || *fGc):
ui.Errorf("At least one metric is needed\n")
}
}
func main() {
// Parse CLI arguments
setup()
var (
aln = new(nexus.Alignment) // Sequence alignment
uces = make(map[string][]nexus.Pair, 0) // UCE set
letters []byte // Valid letters in Alignment
)
switch {
case *fNex != "": // Nexus input, all in one input
in, err := os.Open(*fNex)
defer in.Close()
if err != nil {
ui.Errorf("Could not read input file: %s", err)
}
// Read in the input Nexus file
nex := nexus.Read(in)
*aln = nex.Alignment()
uces = nex.Charsets()
letters = nex.Letters()
case *fFasta != "" && *fUces != "": // FASTA and UCE input,
fna, err := fastx.NewDefaultReader(*fFasta)
defer fna.Close()
if err != nil {
ui.Errorf("Could not read input file: %s", err)
}
seqs := make([]string, 0)
for {
record, err := fna.Read()
if err != nil {
if err == io.EOF {
break
}
ui.Errorf("Failed parsing FASTA: %v", err)
}
seqs = append(seqs, record.Seq.String())
}
*aln = nexus.Alignment(seqs)
letters = seq.DNA.Letters()
inUce, err := os.Open(*fUces)
defer inUce.Close()
if err != nil {
ui.Errorf("Could not read input file: %s", err)
}
uceCsv := csv.NewReader(inUce)
colMap := make(map[string]int, 3)
header, err := uceCsv.Read()
for i, col := range header {
switch col {
case "Name":
colMap["Name"] = i
case "Start":
colMap["Start"] = i
case "Stop":
colMap["Stop"] = i
default:
ui.Errorf("Did not understand column %q", col)
}
}
rows, err := uceCsv.ReadAll()
for _, row := range rows {
start, err := strconv.Atoi(row[colMap["Start"]])
if err != nil {
ui.Errorf("Failed to read Start in UCE row: %q", row)
}
stop, err := strconv.Atoi(row[colMap["Stop"]])
if err != nil {
ui.Errorf("Failed to read Stop in UCE row: %q", row)
}
uces[row[colMap["Name"]]] = append(uces[row[colMap["Name"]]],
nexus.NewPair(
start,
stop+1, // Inclusive range in file, while exclusive range used internally
),
)
}
default:
ui.Errorf("Did not understand how to read input")
}
out, err := os.Create(*fOutput)
defer out.Close()
if err != nil {
ui.Errorf("Could not create output file: %s", err)
}
writers.WriteOutputHeader(out)
var (
bar = pb.StartNew(len(uces)) // Progress bar
metVals = make(map[metrics.Metric][]float64, 3)
)
// Early panic if minWin has been set too large to create flanks and core of that length
if err := utils.ValidateMinWin(aln.Len(), int(*fMinWin)); err != nil {
ui.Errorf("Failed due to: %v", err)
}
if *fEntropy {
metVals[metrics.Entropy] = metrics.SitewiseEntropy(aln, letters)
}
if *fGc {
metVals[metrics.GC] = metrics.SitewiseGc(aln)
}
// Sort UCEs
// Create reverse lookup to maintain order
revUCEs := make(map[int]string, len(uces))
keys := make([]int, 0, len(uces))
for name, sites := range uces {
var (
start = math.MaxInt64 // Minimum position in UCE
)
// Get the inclusive window for the UCE if multiple windows exist (which they should not, but can in the Nexus format)
for _, pair := range sites {
if pair.First() < start {
start = pair.First()
}
}
revUCEs[start] = name
keys = append(keys, start)
}
sort.Ints(keys) // Sort done in place
// Process each UCE in turn
pFinderConfigBlocks := make([]string, len(uces))
outputFrames := make([][][]string, len(uces))
sem := make(chan struct{}, len(uces))
uceNum := 0
for _, key := range keys {
go func(key, uceNum int) {
name := revUCEs[key]
sites := uces[name]
var (
start = sites[0].First() // Minimum position in UCE
stop = sites[0].Second() // Maximum position in UCE
)
// Get the inclusive window for the UCE if multiple windows exist (which they should not, but can in the Nexus format)
for _, pair := range sites {
if pair.First() < start {
start = pair.First()
}
if stop < pair.Second() {
stop = pair.Second()
}
}
// Currently uceAln is the subsequence while inVarSites and metVals the entire sequence
// It should be the case that processing a UCE considers where the start and stop of the UCE are
// finding the best Window within that range
bestWindows := uce.ProcessUce(start, stop, metVals, *fMinWin, letters, *fLargeCore, *fNCandidates)
if *fCfg != "" {
for _, bestWindow := range bestWindows {
block := pfinder.ConfigBlock(
name, bestWindow, start, stop-1,
windows.UseFullRange(bestWindow, aln, letters),
)
pFinderConfigBlocks[uceNum] = block
}
}
alnSites := make([]int, stop-start)
for i := range alnSites {
alnSites[i] = i + start
}
frame := writers.Output(bestWindows, metVals, alnSites, name)
outputFrames[uceNum] = frame
sem <- struct{}{}
bar.Increment()
}(key, uceNum)
uceNum++
}
for i := 0; i < len(uces); i++ {
<-sem
}
bar.FinishPrint("Finished processing UCEs")
if *fCfg != "" {
pfinderFile, err := os.Create(*fCfg)
defer pfinderFile.Close()
if err != nil {
ui.Errorf("Could not create PartitionFinder2 file: %s", err)
}
block := pfinder.StartBlock(strings.TrimRight(path.Base(*fNex), ".nex"))
if _, err := io.WriteString(pfinderFile, block); err != nil {
ui.Errorf("Failed to write PartitionFinder2 start block: %s", err)
}
for _, b := range pFinderConfigBlocks {
if _, err := io.WriteString(pfinderFile, b); err != nil {
ui.Errorf("Failed to write PartitionFinder2 config block: %s", err)
}
}
block = pfinder.EndBlock()
if _, err := io.WriteString(pfinderFile, block); err != nil {
ui.Errorf("Failed to write PartitionFinder2 end block: %s", err)
}
}
outCsv := csv.NewWriter(out)
for _, s := range outputFrames {
if err := outCsv.WriteAll(s); err != nil {
ui.Errorf("Failed to write output: %v", err)
}
}
// Inform user of where output was written
fmt.Println(ui.Footer(*fOutput))
}