SSJ API Documentation
Stochastic Simulation in Java
Loading...
Searching...
No Matches
DigitalNetFromFile.java
1/*
2 * Class: DigitalNetFromFile
3 * Description: read the parameters defining a digital net from a file
4 or from a URL address
5 * Environment: Java
6 * Software: SSJ
7 * Copyright (C) 2001 Pierre L'Ecuyer and Universite de Montreal
8 * Organization: DIRO, Universite de Montreal
9 * @author
10 * @since
11 *
12 *
13 * Licensed under the Apache License, Version 2.0 (the "License");
14 * you may not use this file except in compliance with the License.
15 * You may obtain a copy of the License at
16 *
17 * http://www.apache.org/licenses/LICENSE-2.0
18 *
19 * Unless required by applicable law or agreed to in writing, software
20 * distributed under the License is distributed on an "AS IS" BASIS,
21 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 * See the License for the specific language governing permissions and
23 * limitations under the License.
24 *
25 */
26package umontreal.ssj.hups;
27
28import java.io.*;
29import java.util.*;
30import java.net.URL;
31import java.net.MalformedURLException;
32import umontreal.ssj.util.PrintfFormat;
33
155public class DigitalNetFromFile extends DigitalNet {
156 private String filename;
157
158 private void readMatrices(StreamTokenizer st, int r, int k, int dim) throws IOException, NumberFormatException {
159 // Read dim matrices with r rows and k columns.
160 // dim is the dimension of the digital net.
161 genMat = new int[dim * k][r];
162 for (int i = 0; i < dim; i++)
163 for (int c = 0; c < k; c++) {
164 for (int j = 0; j < r; j++) {
165 st.nextToken();
166 genMat[i * numCols + c][j] = (int) st.nval;
167 }
168 // If we do not use all the rows, drop the unused ones.
169 for (int j = r; j < numRows; j++) {
170 st.nextToken();
171 }
172 }
173 }
174
175 void readData(StreamTokenizer st) throws IOException, NumberFormatException {
176 // Read beginning of data file, but do not read the matrices
177 st.eolIsSignificant(false);
178 st.slashSlashComments(true);
179 int i = st.nextToken();
180 if (i != StreamTokenizer.TT_NUMBER)
181 throw new NumberFormatException(" readData: cannot read base");
182 b = (int) st.nval;
183 st.nextToken();
184 numCols = (int) st.nval;
185 st.nextToken();
186 numRows = (int) st.nval;
187 st.nextToken();
188 numPoints = (int) st.nval;
189 st.nextToken();
190 dim = (int) st.nval;
191 if (dim < 1)
192 throw new IllegalArgumentException(" dimension dim <= 0");
193 }
194
195 static BufferedReader openURL(String filename) throws MalformedURLException, IOException {
196 try {
197 URL url = new URL(filename);
198 BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream()));
199 return input;
200
201 } catch (MalformedURLException e) {
202 System.err.println(e + " Invalid URL address: " + filename);
203 throw e;
204
205 } catch (IOException e) {
206 // This can receive a FileNotFoundException
207 System.err.println(e + " in openURL with " + filename);
208 throw e;
209 }
210 }
211
212 static BufferedReader openFile(String filename) throws IOException {
213 try {
214 BufferedReader input;
215 File f = new File(filename);
216
217 // If file with relative path name exists, read it
218 if (f.exists()) {
219 if (f.isDirectory())
220 throw new IOException(filename + " is a directory");
221 input = new BufferedReader(new FileReader(filename));
222 } else { // else read it from ssj.jar
223 String pseudo = "umontreal/ssj/hups/data/";
224 StringBuffer pathname = new StringBuffer(pseudo);
225 for (int ci = 0; ci < filename.length(); ci++) {
226 char ch = filename.charAt(ci);
227 if (ch == File.separatorChar)
228 pathname.append('/');
229 else
230 pathname.append(ch);
231 }
232 InputStream dataInput = DigitalNetFromFile.class.getClassLoader().getResourceAsStream(pathname.toString());
233 if (dataInput == null)
234 throw new FileNotFoundException();
235 input = new BufferedReader(new InputStreamReader(dataInput));
236 }
237 return input;
238
239 } catch (FileNotFoundException e) {
240 System.err.println(e + " *** cannot find " + filename);
241 throw e;
242
243 } catch (IOException e) {
244 // This will never catch FileNotFoundException since there
245 // is a catch clause above.
246 System.err.println(e + " cannot read from " + filename);
247 throw e;
248 }
249 }
250
272 public DigitalNetFromFile(String filename, int r1, int w, int s1) throws MalformedURLException, IOException {
273 super();
274 BufferedReader input = null;
275 StreamTokenizer st = null;
276 try {
277 if (filename.startsWith("http:") || filename.startsWith("ftp:"))
278 input = openURL(filename);
279 else
280 input = openFile(filename);
281 st = new StreamTokenizer(input);
282 readData(st);
283
284 } catch (MalformedURLException e) {
285 System.err.println(" Invalid URL address: " + filename);
286 throw e;
287 } catch (FileNotFoundException e) {
288 System.err.println(" Cannot find " + filename);
289 throw e;
290 } catch (NumberFormatException e) {
291 System.err.println(" Cannot read number from " + filename);
292 throw e;
293 } catch (IOException e) {
294 System.err.println(" IOException: " + filename);
295 throw e;
296 }
297
298 if (b == 2) {
299 System.err.println(" base = 2, use DigitalNetBase2FromFile");
300 throw new IllegalArgumentException("base = 2, use DigitalNetBase2FromFile");
301 }
302 if ((double) numCols * Math.log((double) b) > (31.0 * Math.log(2.0)))
303 throw new IllegalArgumentException("DigitalNetFromFile: too many points" + PrintfFormat.NEWLINE);
304 if (r1 > numRows)
305 throw new IllegalArgumentException(
306 "DigitalNetFromFile: One must have r1 <= Max num rows" + PrintfFormat.NEWLINE);
307 if (s1 > dim)
308 throw new IllegalArgumentException(
309 "DigitalNetFromFile: One must have s1 <= Max dimension" + PrintfFormat.NEWLINE);
310 if (w < 0) {
311 r1 = w = numRows;
312 s1 = dim;
313 }
314 if (w < numRows)
315 throw new IllegalArgumentException(
316 "DigitalNetFromFile: One must have w >= numRows" + PrintfFormat.NEWLINE);
317
318 try {
319 readMatrices(st, r1, numCols, s1);
320 } catch (NumberFormatException e) {
321 System.err.println(e + " cannot read matrices from " + filename);
322 throw e;
323 } catch (IOException e) {
324 System.err.println(e + " cannot read matrices from " + filename);
325 throw e;
326 }
327 input.close();
328
329 this.filename = filename;
330 numRows = r1;
331 dim = s1;
332 outDigits = w;
333 int x = b;
334 for (int i = 1; i < numCols; i++)
335 x *= b;
336 if (x != numPoints) {
337 System.out.println("DigitalNetFromFile: numPoints != b^k");
338 throw new IllegalArgumentException(" numPoints != b^k");
339 }
340
341 // Compute the normalization factors.
342 normFactor = 1.0 / Math.pow((double) b, (double) outDigits);
343 double invb = 1.0 / b;
344 factor = new double[outDigits];
345 factor[0] = invb;
346 for (int j = 1; j < outDigits; j++)
347 factor[j] = factor[j - 1] * invb;
348 }
349
357 public DigitalNetFromFile(String filename, int s) throws MalformedURLException, IOException {
358 this(filename, -1, -1, s);
359 }
360
362 super();
363 }
364
365 public String toString() {
366 StringBuffer sb = new StringBuffer("File: " + filename + PrintfFormat.NEWLINE);
367 sb.append(super.toString());
368 return sb.toString();
369 }
370
376 public String toStringDetailed() {
377 StringBuffer sb = new StringBuffer(toString());
378 sb.append(PrintfFormat.NEWLINE + "n = " + numPoints + PrintfFormat.NEWLINE);
379 sb.append("dim = " + dim + PrintfFormat.NEWLINE);
380 for (int i = 0; i < dim; i++) {
381 sb.append(PrintfFormat.NEWLINE + " // dim = " + (1 + i) + PrintfFormat.NEWLINE);
382 for (int c = 0; c < numCols; c++) {
383 for (int r = 0; r < numRows; r++)
384 sb.append(genMat[i * numCols + c][r] + " ");
385 sb.append(PrintfFormat.NEWLINE);
386 }
387 }
388 return sb.toString();
389 }
390
391 static class NetComparator implements Comparator {
392 // Used to sort list of nets. Sort first by base, then by dimension,
393 // then by the number of rows. Don't forget that base = 4 are in files
394 // named B4_2* and that the computations are done in base 2.
395 public int compare(Object o1, Object o2) {
398 if (net1.b < net2.b)
399 return -1;
400 if (net1.b > net2.b)
401 return 1;
402 if (net1.filename.indexOf("_") >= 0 && net2.filename.indexOf("_") < 0)
403 return 1;
404 if (net2.filename.indexOf("_") >= 0 && net1.filename.indexOf("_") < 0)
405 return -1;
406 if (net1.dim < net2.dim)
407 return -1;
408 if (net1.dim > net2.dim)
409 return 1;
410 if (net1.numRows < net2.numRows)
411 return -1;
412 if (net1.numRows > net2.numRows)
413 return 1;
414 return 0;
415 }
416 }
417
418 private static List getListDir(String dirname) throws IOException {
419 try {
420 String pseudo = "umontreal/ssj/hups/data/";
421 StringBuffer pathname = new StringBuffer(pseudo);
422 for (int ci = 0; ci < dirname.length(); ci++) {
423 char ch = dirname.charAt(ci);
424 if (ch == File.separatorChar)
425 pathname.append('/');
426 else
427 pathname.append(ch);
428 }
429 URL url = DigitalNetFromFile.class.getClassLoader().getResource(pathname.toString());
430 File dir = new File(url.getPath());
431 if (!dir.isDirectory())
432 throw new IllegalArgumentException(dirname + " is not a directory");
433 File[] files = dir.listFiles();
434 List alist = new ArrayList(200);
435 if (!dirname.endsWith(File.separator))
436 dirname += File.separator;
437 for (int i = 0; i < files.length; i++) {
438 if (files[i].isDirectory())
439 continue;
440 if (files[i].getName().endsWith("gz") || files[i].getName().endsWith("zip"))
441 continue;
443 BufferedReader input = net.openFile(dirname + files[i].getName());
444 StreamTokenizer st = new StreamTokenizer(input);
445 net.readData(st);
446 net.filename = files[i].getName();
447 alist.add(net);
448 }
449 if (alist != null && !files[0].isDirectory())
450 Collections.sort(alist, new NetComparator());
451 return alist;
452
453 } catch (NullPointerException e) {
454 System.err.println("getListDir: cannot find directory " + dirname);
455 throw e;
456
457 } catch (NumberFormatException e) {
458 System.err.println(e + "*** cannot read number ");
459 throw e;
460
461 } catch (IOException e) {
462 System.err.println(e);
463 throw e;
464 }
465 }
466
467 private static String listFiles(String dirname) {
468 try {
469 String pseudo = "umontreal/ssj/hups/data/";
470 StringBuffer pathname = new StringBuffer(pseudo);
471 for (int ci = 0; ci < dirname.length(); ci++) {
472 char ch = dirname.charAt(ci);
473 if (ch == File.separatorChar)
474 pathname.append('/');
475 else
476 pathname.append(ch);
477 }
478 URL url = DigitalNetFromFile.class.getClassLoader().getResource(pathname.toString());
479 File dir = new File(url.getPath());
480 File[] list = dir.listFiles();
481 List alist = new ArrayList(200);
482 final int NPRI = 3;
483 StringBuffer sb = new StringBuffer(1000);
484 for (int i = 0; i < list.length; i++) {
485 if (list[i].isDirectory()) {
486 sb.append(PrintfFormat.s(-2, list[i].getName()));
487 sb.append(File.separator + PrintfFormat.NEWLINE);
488 } else {
489 sb.append(PrintfFormat.s(-25, list[i].getName()));
490 if (i % NPRI == 2)
491 sb.append(PrintfFormat.NEWLINE);
492 }
493 }
494 if (list.length % NPRI > 0)
495 sb.append(PrintfFormat.NEWLINE);
496 return sb.toString();
497
498 } catch (NullPointerException e) {
499 System.err.println("listFiles: cannot find directory " + dirname);
500 throw e;
501 }
502 }
503
511 public static String listDir(String dirname) throws IOException {
512 try {
513 List list = getListDir(dirname);
514 if (list == null || list.size() == 0)
515 return listFiles(dirname);
516 StringBuffer sb = new StringBuffer(1000);
517
518 sb.append("Directory: " + dirname + PrintfFormat.NEWLINE + PrintfFormat.NEWLINE);
519 sb.append(
520 PrintfFormat.s(-25, " File") + PrintfFormat.s(-15, " Base") + PrintfFormat.s(-10, "Dimension")
521 + PrintfFormat.s(-10, " numRows") + PrintfFormat.s(-10, "numColumns" + PrintfFormat.NEWLINE));
522 int base = 0;
523 for (int i = 0; i < list.size(); i++) {
524 DigitalNet net = (DigitalNet) list.get(i);
525 int j = ((DigitalNetFromFile) net).filename.lastIndexOf(File.separator);
526 if (net.b != base) {
527 sb.append(
528 "----------------------------------------------------------------------" + PrintfFormat.NEWLINE);
529 base = net.b;
530 }
531 String name = ((DigitalNetFromFile) net).filename.substring(j + 1);
532 sb.append(PrintfFormat.s(-25, name) + PrintfFormat.d(10, net.b) + PrintfFormat.d(10, net.dim)
533 + PrintfFormat.d(10, net.numRows) + PrintfFormat.d(10, net.numCols) + PrintfFormat.NEWLINE);
534 }
535 return sb.toString();
536
537 } catch (NullPointerException e) {
538 System.err.println("formatPlain: cannot find directory " + dirname);
539 throw e;
540 }
541 }
542
551 public static void listDirHTML(String dirname, String filename) throws IOException {
552 String list = listDir(dirname);
553 StreamTokenizer st = new StreamTokenizer(new StringReader(list));
554 st.eolIsSignificant(true);
555 st.ordinaryChar('/');
556 st.ordinaryChar('_');
557 st.ordinaryChar('-');
558 st.wordChars('-', '-');
559 st.wordChars('_', '_');
560 st.slashSlashComments(false);
561 st.slashStarComments(false);
562 PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename)));
563 out.println("<html>" + PrintfFormat.NEWLINE + "<head>" + PrintfFormat.NEWLINE + "<title>");
564 while (st.nextToken() != st.TT_EOL)
565 ;
566 out.println(PrintfFormat.NEWLINE + "</title>" + PrintfFormat.NEWLINE + "</head>");
567// out.println ("<body background bgcolor=#e1eae8 vlink=#c00000>");
568 out.println("<body>");
569 out.println("<table border>");
570 out.println("<caption> Directory: " + dirname + "</caption>");
571 st.nextToken();
572 st.nextToken();
573 while (st.sval.compareTo("File") != 0)
574 st.nextToken();
575 out.print("<tr align=center><th>" + st.sval + "</th>");
576 while (st.nextToken() != st.TT_EOL) {
577 out.print("<th>" + st.sval + "</th>");
578 }
579 out.println("</tr>" + PrintfFormat.NEWLINE);
580 while (st.nextToken() != st.TT_EOF) {
581 switch (st.ttype) {
582 case StreamTokenizer.TT_EOL:
583 out.println("</tr>");
584 break;
585 case StreamTokenizer.TT_NUMBER:
586 out.print("<td>" + (int) st.nval + "</td>");
587 break;
588 case StreamTokenizer.TT_WORD:
589 if (st.sval.indexOf("---") >= 0) {
590 st.nextToken();
591 continue;
592 }
593 out.print("<tr align=center><td>" + st.sval + "</td>");
594 break;
595 default:
596 out.print(st.sval);
597 break;
598 }
599 }
600
601 out.println("</table>");
602 out.println("</body>" + PrintfFormat.NEWLINE + "</html>");
603 out.close();
604 }
605
606}
This class allows us to read the parameters defining a digital net either from a file,...
static void listDirHTML(String dirname, String filename)
Creates a list of all data files in directory dirname and writes that list in format HTML in output f...
static String listDir(String dirname)
Lists all files (or directories) in directory dirname.
DigitalNetFromFile(String filename, int s)
Same as DigitalNetFromFile(filename, r, r, s) where s is the dimension and r is given in data file fi...
String toStringDetailed()
Writes the parameters and the generating matrices of this digital net to a string.
String toString()
Formats a string that contains information on this digital net.
DigitalNetFromFile(String filename, int r1, int w, int s1)
Constructs a digital net after reading its parameters from file filename.
DigitalNet()
Empty constructor.
int numPoints
Number of points.
int dim
Dimension of the points.
This class acts like a StringBuffer which defines new types of append methods.
static String s(String str)
Same as s(0, str).
static String d(long x)
Same as d(0, 1, x).
static final String NEWLINE
End-of-line symbol or line separator.