View Javadoc

1   /*--------------------------------------------------------------------------
2    *  Copyright 2009 utgenome.org
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   *--------------------------------------------------------------------------*/
16  //--------------------------------------
17  // utgb-core Project
18  //
19  // WIG2Silk.java
20  // Since: 2009/05/07
21  //
22  //--------------------------------------
23  package org.utgenome.format.wig;
24  
25  import java.io.BufferedReader;
26  import java.io.File;
27  import java.io.FileReader;
28  import java.io.IOException;
29  import java.io.PrintWriter;
30  import java.io.Reader;
31  import java.io.StringReader;
32  import java.io.StringWriter;
33  import java.util.ArrayList;
34  
35  import org.antlr.runtime.ANTLRReaderStream;
36  import org.antlr.runtime.CommonTokenStream;
37  import org.antlr.runtime.RecognitionException;
38  import org.antlr.runtime.tree.Tree;
39  import org.utgenome.UTGBException;
40  import org.xerial.core.XerialException;
41  import org.xerial.lens.Lens;
42  import org.xerial.util.log.Logger;
43  
44  /**
45   * @author yoshimura
46   * 
47   */
48  public class WIG2Silk {
49  
50  	private static Logger _logger = Logger.getLogger(WIG2Silk.class);
51  
52  	private final BufferedReader reader;
53  
54  	public static class WIGHeaderDescription {
55  		String name;
56  		ArrayList<WIGHeaderAttribute> attributes = new ArrayList<WIGHeaderAttribute>();
57  
58  		public void setName(String name) {
59  			this.name = name;
60  		}
61  
62  		public void addAttribute(WIGHeaderAttribute attribute) {
63  			attributes.add(attribute);
64  		}
65  
66  		@Override
67  		public String toString() {
68  			return String.format("name=%s, attributes=%s", name, attributes.toString());
69  		}
70  	}
71  
72  	public static class WIGHeaderAttribute {
73  		String name;
74  		String value;
75  
76  		public void setName(String name) {
77  			this.name = name;
78  		}
79  
80  		public void setValue(String value) {
81  			this.value = value;
82  		}
83  
84  		@Override
85  		public String toString() {
86  			return String.format("{name=%s, value=%s}", name, value);
87  		}
88  	}
89  
90  	public WIG2Silk(File wigFile) throws IOException {
91  		this(new FileReader(wigFile));
92  	}
93  
94  	/**
95  	 * 
96  	 * @param wigFile
97  	 * @throws IOException
98  	 */
99  	public WIG2Silk(Reader wigFile) throws IOException {
100 
101 		// track = new WIGHeaderDescription();
102 		// genes = new ArrayList<String[]>();
103 
104 		this.reader = new BufferedReader(wigFile);
105 
106 	}
107 
108 	/**
109 	 * 
110 	 * @param out
111 	 * @throws IOException
112 	 * @throws UTGBShellException
113 	 */
114 
115 	public void toSilk(PrintWriter out) throws IOException, UTGBException {
116 
117 		// print header line
118 		out.print("%silk(version:1.0)");
119 		out.flush();
120 
121 		int lineNum = 1;
122 		for (String line; (line = reader.readLine()) != null; lineNum++) {
123 
124 			try {
125 				if (line.startsWith("#") || line.length() == 0) {
126 				}
127 				else if (line.startsWith("browser")) {
128 					// this.browser = readTrackLine(line,i);
129 				}
130 				else if (line.startsWith("track")) {
131 					// print track line
132 					StringBuffer sb = new StringBuffer("\n-track(");
133 					sb = readHeaderLine(sb, line);
134 					out.println(sb.toString());
135 					out.flush();
136 				}
137 				else if (line.startsWith("variableStep")) {
138 					StringBuffer sb = new StringBuffer(" -coordinate(stepType:variable, ");
139 					sb = readHeaderLine(sb, line);
140 					sb.append("\n  -data(start, value)|");
141 					out.println(sb.toString());
142 					out.flush();
143 				}
144 				else if (line.startsWith("fixedStep")) {
145 					StringBuffer sb = new StringBuffer(" -coordinate(stepType:fixed, ");
146 					sb = readHeaderLine(sb, line);
147 					sb.append("\n  -data(value)|");
148 					out.println(sb.toString());
149 					out.flush();
150 				}
151 				else {
152 					String[] lineValues = readWIGLine(line, lineNum);
153 					StringBuilder sb = new StringBuilder();
154 					for (String value : lineValues) {
155 						sb.append(value + "\t");
156 					}
157 					out.println(sb.toString().trim());
158 					out.flush();
159 				}
160 			}
161 			catch (RecognitionException e) {
162 				throw new UTGBException(String.format("line %d: %s", lineNum, e));
163 			}
164 			catch (XerialException e) {
165 				throw new UTGBException(String.format("line %d: %s", lineNum, e));
166 			}
167 		}
168 	}
169 
170 	public String toSilk() throws IOException, UTGBException {
171 		StringWriter out = new StringWriter();
172 		toSilk(new PrintWriter(out));
173 		return out.toString();
174 	}
175 
176 	private static String[] readWIGLine(String line, int lineNo) {
177 		String[] temp = line.replace(" ", "\t").trim().split("\t+");
178 		// split by tab or space
179 		if (temp.length > 2) {
180 			_logger.error("Error data -> line:" + lineNo);
181 		}
182 		return temp;
183 	}
184 
185 	private static StringBuffer readHeaderLine(StringBuffer sb, String line) throws IOException, XerialException, RecognitionException {
186 		WIGLexer lexer = new WIGLexer(new ANTLRReaderStream(new StringReader(line)));
187 		CommonTokenStream tokens = new CommonTokenStream(lexer);
188 
189 		WIGParser parser = new WIGParser(tokens);
190 		WIGParser.description_return ret = parser.description();
191 
192 		for (WIGHeaderAttribute a : Lens.loadANTLRParseTree(WIGHeaderDescription.class, (Tree) ret.getTree(), WIGParser.tokenNames).attributes) {
193 			sb.append(a.name + ":");
194 			if ((a.value.contains(",") || a.value.contains(" ") || a.value.contains(":")) && !a.value.startsWith("\"") && !a.value.endsWith("\"")) {
195 				sb.append("\"" + a.value + "\", ");
196 			}
197 			else {
198 				sb.append(a.value + ", ");
199 			}
200 		}
201 		return sb.delete(sb.lastIndexOf(","), sb.length()).append(")");
202 	}
203 
204 	private static String changeRGB2Hex(String rgb) {
205 		String[] temp = rgb.split(",");
206 		StringBuffer ret = new StringBuffer("\"#");
207 		if (temp.length >= 3) {
208 			for (int i = 0; i < 3; i++) {
209 				if (Integer.valueOf(temp[i]) > 255 || Integer.valueOf(temp[i]) < 0) {
210 					System.err.println("Warn : out of color range 0-255");
211 					return "";
212 				}
213 				if (Integer.toHexString(Integer.valueOf(temp[i])).length() == 1) {
214 					ret.append("0");
215 				}
216 				ret.append(Integer.toHexString(Integer.valueOf(temp[i])));
217 			}
218 			return ret.append("\"").toString();
219 		}
220 		else {
221 			return "";
222 		}
223 	}
224 }