2
|
1 package edu.unc.genomics.wigmath;
|
|
2
|
|
3 import java.io.IOException;
|
|
4 import java.nio.file.Paths;
|
|
5 import java.util.ArrayList;
|
|
6 import java.util.Iterator;
|
|
7 import java.util.List;
|
|
8
|
|
9 import org.apache.log4j.Logger;
|
|
10 import org.broad.igv.bbfile.WigItem;
|
|
11
|
|
12 import com.beust.jcommander.Parameter;
|
|
13
|
|
14 import edu.unc.genomics.CommandLineToolException;
|
|
15 import edu.unc.genomics.io.WigFile;
|
|
16 import edu.unc.genomics.io.WigFileException;
|
|
17
|
|
18 public class Average extends WigMathTool {
|
|
19
|
|
20 private static final Logger log = Logger.getLogger(Average.class);
|
|
21
|
|
22 @Parameter(description = "Input files", required = true)
|
|
23 public List<String> inputFiles = new ArrayList<String>();
|
|
24
|
|
25 int numFiles;
|
|
26
|
|
27 @Override
|
|
28 public void setup() {
|
|
29 if (inputFiles.size() < 2) {
|
|
30 throw new CommandLineToolException("No reason to add < 2 files.");
|
|
31 }
|
|
32
|
|
33 log.debug("Initializing input files");
|
|
34 for (String inputFile : inputFiles) {
|
|
35 try {
|
|
36 addInputFile(WigFile.autodetect(Paths.get(inputFile)));
|
|
37 } catch (IOException | WigFileException e) {
|
|
38 log.error("Error initializing input Wig file: " + inputFile);
|
|
39 e.printStackTrace();
|
|
40 throw new CommandLineToolException(e.getMessage());
|
|
41 }
|
|
42 }
|
|
43 log.debug("Initialized " + inputs.size() + " input files");
|
|
44
|
|
45 numFiles = inputs.size();
|
|
46 }
|
|
47
|
|
48 @Override
|
|
49 public float[] compute(String chr, int start, int stop) throws IOException, WigFileException {
|
|
50 log.debug("Computing average for chunk "+chr+":"+start+"-"+stop);
|
|
51
|
|
52 int length = stop - start + 1;
|
|
53 float[] avg = new float[length];
|
|
54
|
|
55 for (WigFile wig : inputs) {
|
|
56 Iterator<WigItem> data = wig.query(chr, start, stop);
|
|
57 while (data.hasNext()) {
|
|
58 WigItem item = data.next();
|
|
59 for (int i = item.getStartBase(); i <= item.getEndBase(); i++) {
|
|
60 if (i-start >= 0 && i-start < avg.length) {
|
|
61 avg[i-start] += item.getWigValue();
|
|
62 }
|
|
63 }
|
|
64 }
|
|
65 }
|
|
66
|
|
67 for (int i = 0; i < avg.length; i++) {
|
|
68 avg[i] = avg[i] / numFiles;
|
|
69 }
|
|
70
|
|
71 return avg;
|
|
72 }
|
|
73
|
|
74
|
|
75 /**
|
|
76 * @param args
|
|
77 * @throws WigFileException
|
|
78 * @throws IOException
|
|
79 */
|
|
80 public static void main(String[] args) throws IOException, WigFileException {
|
|
81 new Average().instanceMain(args);
|
|
82 }
|
|
83
|
|
84 }
|