Coverage details for edu.uci.ics.jung.io.MatrixFile

LineHitsSource
1 /*
2  * Copyright (c) 2003, the JUNG Project and the Regents of the University
3  * of California
4  * All rights reserved.
5  *
6  * This software is open-source under the BSD license; see either
7  * "license.txt" or
8  * http://jung.sourceforge.net/license.txt for a description.
9  */
10 /*
11  * Created on Jan 6, 2002
12  *
13  */
14 package edu.uci.ics.jung.io;
15 import java.io.BufferedReader;
16 import java.io.BufferedWriter;
17 import java.io.FileReader;
18 import java.io.FileWriter;
19 import java.io.IOException;
20 import java.text.ParseException;
21 import java.util.ArrayList;
22 import java.util.List;
23 import java.util.StringTokenizer;
24  
25 import cern.colt.list.DoubleArrayList;
26 import cern.colt.matrix.DoubleMatrix2D;
27 import cern.colt.matrix.impl.SparseDoubleMatrix2D;
28 import corejava.Format;
29 import edu.uci.ics.jung.algorithms.GraphMatrixOperations;
30 import edu.uci.ics.jung.exceptions.FatalException;
31 import edu.uci.ics.jung.graph.Graph;
32 /**
33  * Basic I/O handler for ascii matrix files. An ascii matrix is simply
34  * a square matrix where 0 values for cell (i,j) indicates no edge exists between
35  * vertex i and vertex j and non-zero values indicates there is an edge. If
36  * a non-null weight key is specified then it will be used to treat the non-zero
37  * values as a weight stored in the edges' user data keyed off the specified weight key value.
38  * <p>
39  * When loading a graph from a file, a symmetric graph will result in the construction of
40  * an undirected sparse graph while a non-symmetric graph will result in the construction of
41  * a directed sparse graph.
42  * <p>
43  * For example the following ascii matrix when loaded using the code:<br><code>
44  * MatrixFile mf = new MatrixFile(null); <br>
45  * Graph g = mf.load(filename); </code><br>
46  * will produce an undirected sparse matrix with no weights: <br>
47  * <pre>
48  * 0 1 0 1
49  * 1 0 0 1
50  * 0 0 0 0
51  * 1 1 0 0
52  * </pre><p>
53  * whereas the following ascii matrix when loaded using the code:<br><code>
54  * MatrixFile mf = new MatrixFile("WEIGHT"); <br>
55  * Graph g = mf.load(filename); </code> <br>
56  * will produce a directed sparse matrix with double weight values stored in
57  * the edges user data under the key "WEIGHT" : <br>
58  * <pre>
59   * 0 .5 10 0
60  * 0 1 0 0
61  * 0 0 0 -30
62  * 5 0 0 0
63  * </pre>
64  * @author Scott
65  *
66  */
67 public class MatrixFile implements GraphFile {
68     private String mWeightKey;
69     /**
70      * Constructs MatrixFile instance. If weightKey is not null then, it will
71      * attempt to use that key to store and retreive weights from the edges'
72      * UserData.
73      */
742    public MatrixFile(String weightKey) {
752        mWeightKey = weightKey;
762    }
77     
78     /**
79      * Loads a graph from an input reader
80      * @param reader the input reader
81      * @return the graph
82      */
83     public Graph load(BufferedReader reader) {
842        Graph graph = null;
85         try {
862            DoubleMatrix2D matrix = createMatrixFromFile(reader);
872            graph = GraphMatrixOperations.matrixToGraph(matrix,mWeightKey);
880        } catch (Exception e) {
890            throw new FatalException(
90                 "Fatal exception calling MatrixFile.load(...)",
91                 e);
922        }
932        return graph;
94     }
95  
96     private DoubleMatrix2D createMatrixFromFile(BufferedReader reader)
97         throws IOException, ParseException {
982        List rows = new ArrayList();
992        String currentLine = null;
10012        while ((currentLine = reader.readLine()) != null) {
10110            StringTokenizer tokenizer = new StringTokenizer(currentLine);
10210            if (tokenizer.countTokens() == 0) {
1030                break;
104             }
10510            DoubleArrayList currentRow = new DoubleArrayList();
10660            while (tokenizer.hasMoreTokens()) {
10750                String token = tokenizer.nextToken();
10850                currentRow.add(Double.parseDouble(token));
109             }
11010            rows.add(currentRow);
111         }
1122        int size = rows.size();
1132        DoubleMatrix2D matrix = new SparseDoubleMatrix2D(size, size);
11412        for (int i = 0; i < size; i++) {
11510            DoubleArrayList currentRow = (DoubleArrayList) rows.get(i);
11610            if (currentRow.size() != size) {
1170                throw new ParseException(
118                     "Matrix must have the same number of rows as columns",
119                     0);
120             }
12160            for (int j = 0; j < size; j++) {
12250                double currentVal = currentRow.get(j);
12350                if (currentVal != 0) {
12412                    matrix.setQuick(i, j, currentVal);
125                 }
126             }
127         }
1282        return matrix;
129     }
130     /*
131      * Loads a graph from a file
132      * @see edu.uci.ics.jung.io.GraphFile#load(java.lang.String)
133      */
134     public Graph load(String filename) {
135         try {
1362            BufferedReader reader =
137                 new BufferedReader(new FileReader(filename));
1382            Graph graph = load(reader);
1392            reader.close();
1402            return graph;
1410        } catch (IOException ioe) {
1420            throw new FatalException("Error in loading file " + filename, ioe);
143         }
144     }
145     /*
146      * Saves a graph to a file
147      * @see edu.uci.ics.jung.io.GraphFile#save(edu.uci.ics.jung.graph.Graph, java.lang.String)
148      */
149     public void save(Graph graph, String filename) {
150         try {
1512            BufferedWriter writer =
152                 new BufferedWriter(new FileWriter(filename));
153 // Vertex currentVertex = null;
1542            DoubleMatrix2D matrix = GraphMatrixOperations.graphToSparseMatrix(graph,mWeightKey);
1552            Format labelFormat = new Format("%4.2f");
15612            for (int i=0;i<matrix.rows();i++) {
15760                for (int j=0;j<matrix.columns();j++) {
15850                    writer.write(labelFormat.format(matrix.getQuick(i,j)) + " ");
159                 }
16010                writer.write("\n");
161             }
1622            writer.close();
1630        } catch (Exception e) {
1640            throw new FatalException("Error saving file: " + filename, e);
1652        }
1662    }
167 }

this report was generated by version 1.0.5 of jcoverage.
visit www.jcoverage.com for updates.

copyright © 2003, jcoverage ltd. all rights reserved.
Java is a trademark of Sun Microsystems, Inc. in the United States and other countries.