Author: chatellier Date: 2009-03-04 09:42:17 +0000 (Wed, 04 Mar 2009) New Revision: 123 Added: lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixStringEncoder.java lutinmatrix/trunk/src/test/java/org/codelutin/math/matrix/MatrixStringEncoderTest.java Modified: lutinmatrix/trunk/pom.xml lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/AbstractMatrixND.java lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixFactory.java lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixHelper.java lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixND.java lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixNDImpl.java lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/SubMatrix.java lutinmatrix/trunk/src/test/java/org/codelutin/math/matrix/MatrixHelperTest.java Log: Add matrix to string/from string convertion Modified: lutinmatrix/trunk/pom.xml =================================================================== --- lutinmatrix/trunk/pom.xml 2009-03-03 14:01:27 UTC (rev 122) +++ lutinmatrix/trunk/pom.xml 2009-03-04 09:42:17 UTC (rev 123) @@ -117,8 +117,19 @@ </plugin> </plugins> </build> + <reporting> + <plugins> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>cobertura-maven-plugin</artifactId> + </plugin> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>findbugs-maven-plugin</artifactId> + </plugin> + </plugins> + </reporting> - <!-- ************************************************************* --> <!-- *** Build Environment ************************************** --> <!-- ************************************************************* --> Modified: lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/AbstractMatrixND.java =================================================================== --- lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/AbstractMatrixND.java 2009-03-03 14:01:27 UTC (rev 122) +++ lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/AbstractMatrixND.java 2009-03-04 09:42:17 UTC (rev 123) @@ -198,11 +198,33 @@ return name; } - public void setDimensionName(String[] names) { + public String[] getDimensionNames() { + return dimNames; + } + + public void setDimensionNames(String[] names) { for (int i = 0; names != null && i < names.length; i++) { setDimensionName(i, names[i]); } } + + /** + * {@inheritDoc} + * + * @deprecated Use #getDimensionNames() + */ + public String[] getDimensionName() { + return getDimensionNames(); + } + + /** + * {@inheritDoc} + * + * @deprecated Use #setDimensionName(String[]) + */ + public void setDimensionName(String[] names) { + setDimensionNames(names); + } public void setDimensionName(int dim, String name) { dimNames[dim] = name; @@ -212,10 +234,6 @@ return dimNames[dim]; } - public String[] getDimensionName() { - return dimNames; - } - public double getMaxOccurence() { // on creer un tableau dans cette classe, car on ne sait pas sur quelle // implantation on s'appuie. Mais dans les sous classes, si on a deja @@ -513,7 +531,7 @@ // creation du resultat MatrixND result = getFactory().create(getName(), semantics, - getDimensionName()); + getDimensionNames()); for (int i = 0; i < result.getDim(dim); i++) { MatrixND temp = getSubMatrix(dim, i * step, step); @@ -541,7 +559,7 @@ // creation du resultat MatrixND result = getFactory().create(getName(), semantics, - getDimensionName()); + getDimensionNames()); MatrixND sub1 = this.getSubMatrix(dim, 0, start); MatrixND sub2 = this.getSubMatrix(dim, start, nb).sumOverDim(dim); Modified: lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixFactory.java =================================================================== --- lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixFactory.java 2009-03-03 14:01:27 UTC (rev 122) +++ lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixFactory.java 2009-03-04 09:42:17 UTC (rev 123) @@ -35,165 +35,185 @@ */ public class MatrixFactory { // MatrixFactory - /* - * following code in only an exception generator since lutinxml in not used - * anymore :) static { - * // on essai d'enregistrer le converter XML try { // Il faut le faire par - * pur introspection sinon l'exception // NoClassDefFoundError est levé - * avant d'entrer dans le constructeur // static :( Class converterClass = - * Class .forName("org.codelutin.math.matrix.MatrixNDXMLConverter"); Object - * converter = converterClass.newInstance(); - * - * Class converterFactoryClass = Class - * .forName("org.codelutin.xml.XMLConverterFactory"); Method m = - * converterFactoryClass.getMethod("addConverter", Class.class, Class - * .forName("org.codelutin.xml.XMLConverter")); m.invoke(null, - * MatrixND.class, converter); - * // org.codelutin.xml.XMLConverterFactory.addConverter(MatrixND.class, // - * new MatrixNDXMLConverter()); log.info("Converter XML pour MatrixND - * ajoute"); - * // on essai d'enregistrer le converter JDBC // le JDBC depend du XML try { - * converterClass = Class - * .forName("org.codelutin.math.matrix.MatrixNDJDBCConverter"); converter = - * converterClass.newInstance(); - * - * converterFactoryClass = Class - * .forName("org.codelutin.topia.persistence.jdbctransformer.JDBCTransformerFactory"); - * m = converterFactoryClass .getMethod( "addConverter", Class.class, - * Class.forName("org.codelutin.topia.persistence.jdbctransformer.JDBCTransformer")); - * m.invoke(null, MatrixND.class, converter); - * // Class converterClass = // - * org.codelutin.math.matrix.MatrixNDJDBCConverter(); // - * JDBCTransformerFactory // .addConverter(MatrixND.class, new - * MatrixNDJDBCConverter()); log.info("Converter JDBC pour MatrixND - * ajoute"); } catch (Throwable eee) { log .info("librairie topia non - * presente. Import/Export JDBC impossible"); log.debug("L'exception etait", - * eee); } - * } catch (Throwable eee) { log .info("librairie lutinxml non presente. - * Import/Export XML impossible"); log.debug("L'exception etait", eee); } - * } - */ + /* following code in only an exception generator since + * lutinxml in not used anymore :) + static { - /** Valeur par defaut si aucun type de Vector n'est donné */ - protected static Class defaultVectorClass = DoubleBigVector.class; + // on essai d'enregistrer le converter XML + try { + // Il faut le faire par pur introspection sinon l'exception + // NoClassDefFoundError est levé avant d'entrer dans le constructeur + // static :( + Class converterClass = Class + .forName("org.codelutin.math.matrix.MatrixNDXMLConverter"); + Object converter = converterClass.newInstance(); - protected Class vectorClass = null; + Class converterFactoryClass = Class + .forName("org.codelutin.xml.XMLConverterFactory"); + Method m = converterFactoryClass.getMethod("addConverter", + Class.class, Class + .forName("org.codelutin.xml.XMLConverter")); + m.invoke(null, MatrixND.class, converter); - protected MatrixFactory(Class vectorClass) { - this.vectorClass = vectorClass; - } + // org.codelutin.xml.XMLConverterFactory.addConverter(MatrixND.class, + // new MatrixNDXMLConverter()); + log.info("Converter XML pour MatrixND ajoute"); - public static void setDefaultVectorClass(Class vectorClass) { - defaultVectorClass = vectorClass; - } + // on essai d'enregistrer le converter JDBC + // le JDBC depend du XML + try { + converterClass = Class + .forName("org.codelutin.math.matrix.MatrixNDJDBCConverter"); + converter = converterClass.newInstance(); - public static Class getDefaultVectorClass() { - return defaultVectorClass; - } + converterFactoryClass = Class + .forName("org.codelutin.topia.persistence.jdbctransformer.JDBCTransformerFactory"); + m = converterFactoryClass + .getMethod( + "addConverter", + Class.class, + Class.forName("org.codelutin.topia.persistence.jdbctransformer.JDBCTransformer")); + m.invoke(null, MatrixND.class, converter); - /** - * Retourne une factory utilisant vectorClass comme classe de base a - * l'implantation des matrices - */ - public static MatrixFactory getInstance(Class vectorClass) { - return new MatrixFactory(vectorClass); - } + // Class converterClass = + // org.codelutin.math.matrix.MatrixNDJDBCConverter(); + // JDBCTransformerFactory + // .addConverter(MatrixND.class, new MatrixNDJDBCConverter()); + log.info("Converter JDBC pour MatrixND ajoute"); + } catch (Throwable eee) { + log + .info("librairie topia non presente. Import/Export JDBC impossible"); + log.debug("L'exception etait", eee); + } - /** - * Utilise par defaut {@link FloatBigVector} - */ - public static MatrixFactory getInstance() { - return getInstance(defaultVectorClass); - } + } catch (Throwable eee) { + log + .info("librairie lutinxml non presente. Import/Export XML impossible"); + log.debug("L'exception etait", eee); + } - public MatrixND create(int[] dim) { - return new MatrixNDImpl(this, dim); - } + }*/ - /** - * Convert a double array into matrix. - * - * @param values - * The values to fill the matrix - * @param dim - * An array representing the dimensions of the matrix - * @return a 2D matrix filled with the values, null if the dimension is more - * than 2 - */ - public MatrixND create(double[] values, int[] dim) { + /** Valeur par defaut si aucun type de Vector n'est donné */ + protected static Class defaultVectorClass = DoubleBigVector.class; - if (dim.length > 2) { - return null; - } - MatrixNDImpl matrix = new MatrixNDImpl(this, dim); + protected Class vectorClass = null; - if (dim.length == 2) { - for (int i = 0; i < dim[0]; i++) { - for (int j = 0; j < dim[1]; j++) { - int[] coordinates = { i, j }; - matrix.setValue(coordinates, values[i * dim[1] + j]); - } - } - } - if (dim.length == 1) { - for (int i = 0; i < dim[0]; i++) { - int[] coordinates = { i }; - matrix.setValue(coordinates, values[i]); - } - } + protected MatrixFactory(Class vectorClass) { + this.vectorClass = vectorClass; + } - return matrix; - } + public static void setDefaultVectorClass(Class vectorClass) { + defaultVectorClass = vectorClass; + } - public MatrixND create(List[] semantics) { - return new MatrixNDImpl(this, semantics); - } + public static Class getDefaultVectorClass() { + return defaultVectorClass; + } - public MatrixND create(String name, int[] dim) { - return new MatrixNDImpl(this, name, dim); - } + /** + * Retourne une factory utilisant vectorClass comme classe de base a + * l'implantation des matrices + */ + public static MatrixFactory getInstance(Class vectorClass) { + return new MatrixFactory(vectorClass); + } - public MatrixND create(String name, int[] dim, String[] dimNames) { - return new MatrixNDImpl(this, name, dim, dimNames); - } + /** + * Utilise par defaut {@link FloatBigVector} + */ + public static MatrixFactory getInstance() { + return getInstance(defaultVectorClass); + } - public MatrixND create(String name, List[] semantics) { - return new MatrixNDImpl(this, name, semantics); - } + public MatrixND create(int[] dim) { + return new MatrixNDImpl(this, dim); + } - public MatrixND create(String name, List[] semantics, String[] dimNames) { - return new MatrixNDImpl(this, name, semantics, dimNames); - } + /** + * Convert a double array into matrix. + * + * @param values + * The values to fill the matrix + * @param dim + * An array representing the dimensions of the matrix + * @return a 2D matrix filled with the values, null if the dimension is more + * than 2 + */ + public MatrixND create(double[] values, int[] dim) { - public MatrixND create(MatrixND matrix) { - return new MatrixNDImpl(this, matrix); - } + if (dim.length > 2) { + return null; + } + MatrixNDImpl matrix = new MatrixNDImpl(this, dim); - /** - * Crée une nouvelle matrice identité. Une matrice identité est une matrice - * à 2 dimensions dont tous les éléments de la diagonal vaut 1 - * - * @param size - * la taille de la matrice - * @return une nouvelle matrice identité - */ - public MatrixND matrixId(int size) { - MatrixND result = create(new int[] { size, size }); - for (int i = 0; i < size; i++) { - result.setValue(i, i, 1); - } - return result; - } + if (dim.length == 2) { + for (int i = 0; i < dim[0]; i++) { + for (int j = 0; j < dim[1]; j++) { + int[] coordinates = { i, j }; + matrix.setValue(coordinates, values[i * dim[1] + j]); + } + } + } + if (dim.length == 1) { + for (int i = 0; i < dim[0]; i++) { + int[] coordinates = { i }; + matrix.setValue(coordinates, values[i]); + } + } - protected Vector createVector(int length) { - try { - Constructor c = vectorClass - .getConstructor(new Class[] { Integer.TYPE }); - return (Vector) c.newInstance(new Object[] { length }); - } catch (Exception eee) { - throw new RuntimeException("Can't create vector", eee); - } - } + return matrix; + } + public MatrixND create(List[] semantics) { + return new MatrixNDImpl(this, semantics); + } + + public MatrixND create(String name, int[] dim) { + return new MatrixNDImpl(this, name, dim); + } + + public MatrixND create(String name, int[] dim, String[] dimNames) { + return new MatrixNDImpl(this, name, dim, dimNames); + } + + public MatrixND create(String name, List[] semantics) { + return new MatrixNDImpl(this, name, semantics); + } + + public MatrixND create(String name, List[] semantics, String[] dimNames) { + return new MatrixNDImpl(this, name, semantics, dimNames); + } + + public MatrixND create(MatrixND matrix) { + return new MatrixNDImpl(this, matrix); + } + + /** + * Crée une nouvelle matrice identité. Une matrice identité est une matrice + * à 2 dimensions dont tous les éléments de la diagonal vaut 1 + * + * @param size + * la taille de la matrice + * @return une nouvelle matrice identité + */ + public MatrixND matrixId(int size) { + MatrixND result = create(new int[] { size, size }); + for (int i = 0; i < size; i++) { + result.setValue(i, i, 1); + } + return result; + } + + protected Vector createVector(int length) { + try { + Constructor c = vectorClass + .getConstructor(new Class[] { Integer.TYPE }); + return (Vector) c.newInstance(new Object[] { length }); + } catch (Exception eee) { + throw new RuntimeException("Can't create vector", eee); + } + } + } // MatrixFactory Modified: lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixHelper.java =================================================================== --- lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixHelper.java 2009-03-03 14:01:27 UTC (rev 122) +++ lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixHelper.java 2009-03-04 09:42:17 UTC (rev 123) @@ -28,7 +28,7 @@ import org.apache.commons.logging.LogFactory; /** - * MatrixHelper. + * Contains usefull methods to get information on matrix. * * Created: 28 oct. 2004 * @@ -40,6 +40,9 @@ */ public class MatrixHelper { // MatrixHelper + /** Class logger */ + private static Log log = LogFactory.getLog(MatrixHelper.class); + /** * Convert Matrix to identity matrix must have 2 dimensions. If dimension * haven't same length, then the small dimension is used. @@ -253,21 +256,6 @@ return mat; } - // /** - // * Crée une nouvelle matrice identité. Une matrice identité est une - // * matrice à 2 dimensions dont tous les éléments de la diagonale - // * valent 1 - // * @param size la taille de la matrice - // * @return une nouvelle matrice identité - // */ - // static public MatrixND matrixId(int size){ - // MatrixND result = new MatrixNDImpl(new int[]{size, size}); - // for(int i=0; i<size; i++){ - // result.setValue(i, i , 1); - // } - // return result; - // } - /** * Retourne la valeur la plus courrement rencontrer dans un tableau. si * plusieurs valeurs ont le même nombre d'occurence la plus petite valeur @@ -335,21 +323,4 @@ return result; } - // static public String encodeToXML(MatrixND mat){ - // StringWriter out = new StringWriter(); - // XMLEncoderDecoder.getInstance().encode(out, mat); - // return out.toString(); - // } - // - // static public MatrixND decodeFromXML(String xml){ - // try{ - // return (MatrixND)XMLEncoderDecoder.getInstance().decode(new - // StringReader(xml)); - // }catch(Exception eee){ - // throw new MatrixException("Erreur durant le decodage de la matrice", - // eee); - // } - // } - } // MatrixHelper - Modified: lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixND.java =================================================================== --- lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixND.java 2009-03-03 14:01:27 UTC (rev 122) +++ lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixND.java 2009-03-04 09:42:17 UTC (rev 123) @@ -15,8 +15,6 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ - - package org.codelutin.math.matrix; import java.io.IOException; @@ -39,13 +37,20 @@ public interface MatrixND extends Serializable, Cloneable { // MatrixND /** - * Retourne la factory qui a permit de creer la matrice + * Retourne la factory qui a permit de creer la matrice. + * + * @return la {@link MatrixFactory} + * + * @see MatrixFactory */ public MatrixFactory getFactory(); /** - * Donne toutes les semantiques de la matrice Si la matrice n'a pas de - * semantique retourne null + * Donne toutes les semantiques de la matrice. + * + * Si la matrice n'a pas de semantique retourne null. + * + * @return la liste des semantics */ public List[] getSemantics(); @@ -65,6 +70,8 @@ /** * Permet de donner un nom à la matrice. + * + * @param name name to set */ public void setName(String name); @@ -77,10 +84,39 @@ /** * Permet de mettre des noms aux différentes dimension. + * + * @deprecated (since 1.0.3) Use #setDimensionNames(String[]) */ public void setDimensionName(String[] names); /** + * Permet de mettre des noms aux différentes dimension. + * + * @param names names to set + * + * @since 1.0.3 + */ + public void setDimensionNames(String[] names); + + /** + * Permet de recuperer les noms des dimension. + * + * @return tableau des noms de dimension. + * + * @deprecated (since 1.0.3) Use #getDimensionNames() + */ + public String[] getDimensionName(); + + /** + * Permet de recuperer les noms des dimension. + * + * @return tableau des noms de dimension. + * + * @since 1.0.3 + */ + public String[] getDimensionNames(); + + /** * Permet de mettre un nom à une dimension. * * @param dim la dimension dont on veut changer le nom @@ -97,8 +133,6 @@ */ public String getDimensionName(int dim); - public String[] getDimensionName(); - /** * Retourne la valeur la plus courrement rencontrer dans un tableau. si * plusieurs valeurs ont le même nombre d'occurence la plus petite valeur Modified: lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixNDImpl.java =================================================================== --- lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixNDImpl.java 2009-03-03 14:01:27 UTC (rev 122) +++ lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixNDImpl.java 2009-03-04 09:42:17 UTC (rev 123) @@ -72,7 +72,7 @@ protected MatrixNDImpl(MatrixFactory factory, MatrixND matrix) { super(factory, matrix.getName(), matrix.getSemantics(), matrix - .getDimensionName()); + .getDimensionNames()); this.matrix = new BasicMatrix(factory, dim); this.paste(matrix); } Added: lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixStringEncoder.java =================================================================== --- lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixStringEncoder.java (rev 0) +++ lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixStringEncoder.java 2009-03-04 09:42:17 UTC (rev 123) @@ -0,0 +1,342 @@ +/* *##% lutinmatrix + * Copyright (C) 2004 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ + +package org.codelutin.math.matrix; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.beanutils.BeanUtilsBean; +import org.apache.commons.beanutils.ConvertUtilsBean; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.codelutin.util.StringUtil; + +/** + * Convert matrix into {@link String} and inverse. + * + * Method from this class are non "static" to be overriden. + * + * Created: 04 mar. 2009 + * + * @author chatellier + * @version $Revision: 120 $ + * + * Mise a jour: $Date: 2009-03-03 11:19:18 +0100 (mar. 03 mars 2009) $ + * par : $Author: chatellier $ + */ +public class MatrixStringEncoder { // MatrixStringEncoder + + /** Class logger */ + private static Log log = LogFactory.getLog(MatrixStringEncoder.class); + + /** + * Convert a matrix in string representation. + * + * String representation is composed in (ordered) : + * - name + * - dim + * - dimNames + * - semantics + * - data + * + * @param matrix matrix to convert + * @return a {@link String} representation + */ + public String getMatrixAsString(MatrixND matrix) { + StringBuffer representationBuffer = new StringBuffer(); + representationBuffer.append("["); // top level + representationBuffer.append(matrix.getName()); + representationBuffer.append(","); + representationBuffer.append(getDimToString(matrix.getDim())); + representationBuffer.append(","); + representationBuffer.append(getDimensionNamesToString(matrix + .getDimensionNames())); + representationBuffer.append(","); + representationBuffer + .append(getSemanticsToString(matrix.getSemantics())); + representationBuffer.append(","); + representationBuffer.append(matrix.toList().toString()); + representationBuffer.append("]"); // top level + return representationBuffer.toString(); + } + + /** + * Parse string as matrix representation. + * + * str must be in following format : + * - [name,dim,dimNames,semantics,data] + * @param str + * @return + */ + public MatrixND getMatrixFromString(String str) { + + MatrixND matrix = null; + + // composed of 5 groups + Pattern matrixPattern = Pattern + .compile("^\\[(.*),(\\[.*\\]),(\\[.*\\]),(\\[.*\\]),(\\[.*\\])\\]$"); + Matcher matcher = matrixPattern.matcher(str); + + if (matcher.find()) { + String name = matcher.group(1); + String dimString = matcher.group(2); + String dimNamesString = matcher.group(3); + String semanticsString = matcher.group(4); + String dataString = matcher.group(5); + + int[] dim = getDimFromString(dimString); + String[] dimNames = getDimensionNamesFromString(dimNamesString); + List<Object>[] semantics = getSemanticsFromString(semanticsString); + + matrix = MatrixFactory.getInstance().create(name, semantics, + dimNames); + List<Object> data = MatrixHelper.convertStringToList(dataString); + matrix.fromList(data); + } else { + throw new IllegalArgumentException("Can't parse \"" + str + + "\" as string"); + } + + return matrix; + } + + /** + * Matrix dim to string. + * + * @param dimArray dim to convert. + * @return a {@link String} representation + */ + public String getDimToString(int[] dimArray) { + String result = "["; + String sep = ""; + for (int i = 0; i < dimArray.length; i++) { + result += sep + dimArray[i]; + sep = ", "; + } + result += "]"; + return result; + } + + /** + * String to matrix dim. + * + * @param str string to parse + * @return dim array + */ + public int[] getDimFromString(String str) { + String localStr = str.trim(); + if (localStr.startsWith("[") && localStr.endsWith("]")) { + localStr = localStr.substring(1, localStr.length() - 1); // remove [ and ] + } + String[] dimAsString = StringUtil.split(localStr, ","); + int[] result = new int[dimAsString.length]; + int i = 0; + for (String dim : dimAsString) { + int val = Integer.parseInt(dim.trim()); + result[i++] = val; + } + return result; + } + + /** + * Dim names to string. + * + * @param dimNamesArray dim array to convert + * @return a {@link String} representation + */ + public String getDimensionNamesToString(String[] dimNamesArray) { + String result = "["; + String sep = ""; + for (int i = 0; i < dimNamesArray.length; i++) { + result += sep + '"' + dimNamesArray[i] + '"'; + sep = ", "; + } + result += "]"; + return result; + } + + /** + * String to dim names array. + * + * @param str string to parse + * @return a {@link String} representation + */ + public String[] getDimensionNamesFromString(String str) { + String localStr = str.trim(); + if (localStr.startsWith("[") && localStr.endsWith("]")) { + localStr = localStr.substring(1, localStr.length() - 1); // remove [ and ] + } + String[] result = StringUtil.split(localStr, ","); + for (int i = 0; i < result.length; i++) { + result[i] = result[i].trim(); + if (result[i].startsWith("\"") && result[i].endsWith("\"")) { + result[i] = result[i].substring(1, result[i].length() - 1); // remove " and " + } + } + return result; + } + + /** + * Semantics array to string. + * + * @param semanticsArray semantics arrayy + * @return string names array + */ + public String getSemanticsToString(List<Object>[] semanticsArray) { + StringBuffer result = new StringBuffer("["); + for (int i = 0; i < semanticsArray.length; i++) { + result.append("["); + List<Object> semantics = semanticsArray[i]; + for (Iterator<Object> it = semantics.iterator(); it.hasNext();) { + appendString(result, it.next()); + if (it.hasNext()) { + result.append(", "); + } + } + result.append("]"); + if ((i + 1) < semanticsArray.length) { + result.append(", "); + } + } + return result.append("]").toString(); + } + + /** + * String to samantics. + * + * @param str la chaine representant la semantique + * @return + */ + public List<Object>[] getSemanticsFromString(String str) { + String localStr = str.trim(); + if (localStr.startsWith("[") && localStr.endsWith("]")) { + localStr = localStr.substring(1, localStr.length() - 1); // remove [ and ] + } + String[] sems = StringUtil.split(localStr, ","); + + List<Object>[] result = new List[sems.length]; + + for (int i = 0; i < sems.length; i++) { + result[i] = splitObjects(sems[i]); + } + + return result; + } + + /** + * Recréé chaque object de la chaine de caractere et l'ajoute dans une liste + * la chaine est de la forme. + * + * [null(), java.lang.String("toto"), ...] + * + * @param str la chaine representant + */ + public List<Object> splitObjects(String str) { + List<Object> result = new LinkedList<Object>(); + String localStr = str.trim(); + if (localStr.startsWith("[") && localStr.endsWith("]")) { + localStr = localStr.substring(1, localStr.length() - 1); + } + String[] elems = StringUtil.split(localStr, ","); + for (String elem : elems) { + elem = elem.trim(); + int openbrace = elem.indexOf('('); + String objectType = elem.substring(0, openbrace); + String objectString = elem.substring(openbrace + 1, + elem.length() - 1); + + if ("null".equals(objectType)) { + result.add(null); + } else { + ConvertUtilsBean converter = getConverter(); + Object o; + try { + o = converter.convert(objectString, Class + .forName(objectType)); + } catch (Exception e) { + // if can't create objet, put String representation as semantics + o = objectType + "(" + objectString + ")"; + if (log.isWarnEnabled()) { + log + .warn("Continuing but can't convert object in matrix from String: '" + + o + "'"); + } + if (log.isDebugEnabled()) { + log.debug( + "Continuing but can't convert object in matrix from String: '" + + o + "'", e); + } + } + result.add(o); + } + } + + return result; + } + + /** + * Append object type and value. + * + * qualifiedName(value) + * java.lang.String(test) + * java.lang.Double(4.5) + * + * @param buffer buffer to append to + * @param o object to put on buffer + * @return buffer + */ + public StringBuffer appendString(StringBuffer buffer, Object o) { + if (o == null) { + buffer.append("null()"); + } else { + String qualifiedName = getQualifiedName(o); + buffer.append(qualifiedName).append("("); + ConvertUtilsBean converter = getConverter(); + buffer.append(converter.convert(o)); + buffer.append(")"); + } + return buffer; + } + + /** + * Get object qualified name. + * + * Can't be overridden to put another impl. + * + * @param o object to get qulified name + * @return object qualified class name + */ + public String getQualifiedName(Object o) { + String qualifiedName = o.getClass().getName(); + return qualifiedName; + } + + /** + * Get commons-beanutils bean converter. + * @return a {@link ConvertUtilsBean} + */ + public ConvertUtilsBean getConverter() { + BeanUtilsBean instance = BeanUtilsBean.getInstance(); + ConvertUtilsBean cub = instance.getConvertUtils(); + return cub; + } + +} // MatrixStringEncoder Modified: lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/SubMatrix.java =================================================================== --- lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/SubMatrix.java 2009-03-03 14:01:27 UTC (rev 122) +++ lutinmatrix/trunk/src/main/java/org/codelutin/math/matrix/SubMatrix.java 2009-03-04 09:42:17 UTC (rev 123) @@ -46,7 +46,7 @@ public SubMatrix(MatrixND matrix, int dim, int start, int nb) { super(matrix.getFactory(), matrix.getName(), matrix.getSemantics(), - matrix.getDimensionName()); + matrix.getDimensionNames()); this.matrix = matrix; converter = new ShiftConverter(dim, start, nb); @@ -56,7 +56,7 @@ public SubMatrix(MatrixND matrix, int dim, int[] elem) { super(matrix.getFactory(), matrix.getName(), matrix.getSemantics(), - matrix.getDimensionName()); + matrix.getDimensionNames()); this.matrix = matrix; converter = new MappingConverter(dim, elem); Modified: lutinmatrix/trunk/src/test/java/org/codelutin/math/matrix/MatrixHelperTest.java =================================================================== --- lutinmatrix/trunk/src/test/java/org/codelutin/math/matrix/MatrixHelperTest.java 2009-03-03 14:01:27 UTC (rev 122) +++ lutinmatrix/trunk/src/test/java/org/codelutin/math/matrix/MatrixHelperTest.java 2009-03-04 09:42:17 UTC (rev 123) @@ -39,49 +39,51 @@ /** to use log facility, just put in your code: log.info(\"...\"); */ private static Log log = LogFactory.getLog(MatrixHelperTest.class); - - public MatrixFactory getFactory() throws Exception { + + public MatrixFactory getFactory() { return MatrixFactory.getInstance(); } @Test - public void testCoordinatesToString() throws Exception { - Assert.assertEquals("1", MatrixHelper.coordinatesToString(new int[] { 1 })); - Assert.assertEquals("2,3,4,5", MatrixHelper.coordinatesToString(new int[] { 2, - 3, 4, 5 })); - Assert.assertEquals("2,3,4,5,234", MatrixHelper.coordinatesToString(new int[] { - 2, 3, 4, 5, 234 })); + public void testCoordinatesToString() { + Assert.assertEquals("1", MatrixHelper + .coordinatesToString(new int[] { 1 })); + Assert.assertEquals("2,3,4,5", MatrixHelper + .coordinatesToString(new int[] { 2, 3, 4, 5 })); + Assert.assertEquals("2,3,4,5,234", MatrixHelper + .coordinatesToString(new int[] { 2, 3, 4, 5, 234 })); Assert.assertEquals("a", MatrixHelper .coordinatesToString(new String[] { "a" })); - Assert.assertEquals("a,b,n,m", MatrixHelper.coordinatesToString(new String[] { - "a", "b", "n", "m" })); + Assert.assertEquals("a,b,n,m", MatrixHelper + .coordinatesToString(new String[] { "a", "b", "n", "m" })); Assert.assertEquals("a,b,f,e,aze", MatrixHelper.coordinatesToString(new String[] { "a", "b", "f", "e", "aze" })); } @Test - public void testSameDimension() throws Exception { - Assert.assertTrue(MatrixHelper.sameDimension(new int[] { 1 }, new int[] { 1 })); - Assert.assertTrue(MatrixHelper.sameDimension(new int[] { 1, 2 }, new int[] { - 1, 2 })); + public void testSameDimension() { + Assert.assertTrue(MatrixHelper.sameDimension(new int[] { 1 }, + new int[] { 1 })); + Assert.assertTrue(MatrixHelper.sameDimension(new int[] { 1, 2 }, + new int[] { 1, 2 })); Assert.assertTrue(MatrixHelper.sameDimension(new int[] { 1, 324, 3 }, new int[] { 1, 324, 3 })); } @Test - public void testDimensionToSemantics() throws Exception { + public void testDimensionToSemantics() { // TODO faire un test pour dimensionToSemantics } @Test - public void testSemanticsToDimension() throws Exception { + public void testSemanticsToDimension() { // TODO faire un test pour semanticsToDimension } @Test - public void testFill() throws Exception { + public void testFill() { MatrixND mat = getFactory().create(new int[] { 3, 3 }); MatrixHelper.fill(mat, 4); @@ -89,9 +91,10 @@ } @Test - public void testMatrixId() throws Exception { + public void testMatrixId() { MatrixND mat = getFactory().matrixId(4); - Assert.assertTrue(MatrixHelper.sameDimension(new int[] { 4, 4 }, mat.getDim())); + Assert.assertTrue(MatrixHelper.sameDimension(new int[] { 4, 4 }, mat + .getDim())); Assert.assertEquals(0, mat.getValue(1, 2), 0); Assert.assertEquals(1, mat.getValue(0, 0), 0); Assert.assertEquals(1, mat.getValue(1, 1), 0); @@ -100,7 +103,7 @@ } @Test - public void testToList() throws Exception { + public void testToList() { MatrixND mat1 = getFactory().create(new int[] { 3, 2, 1 }); mat1.setValue(0, 0, 0, -1.0E-7); mat1.setValue(1, 1, 0, 2); @@ -118,7 +121,7 @@ } @Test - public void testMaxOccurence() throws Exception { + public void testMaxOccurence() { double[] val = new double[5]; Assert.assertEquals(0, MatrixHelper.maxOccurence(val), 0); @@ -154,7 +157,7 @@ val = new double[0]; try { MatrixHelper.maxOccurence(val); - Assert.fail("AN exception must be thrown"); + Assert.fail("An exception must be thrown"); } catch (IllegalArgumentException e) { if (log.isDebugEnabled()) { log.debug("Exception normally thrown", e); @@ -162,6 +165,6 @@ } } - + } // MatrixHelperTest Added: lutinmatrix/trunk/src/test/java/org/codelutin/math/matrix/MatrixStringEncoderTest.java =================================================================== --- lutinmatrix/trunk/src/test/java/org/codelutin/math/matrix/MatrixStringEncoderTest.java (rev 0) +++ lutinmatrix/trunk/src/test/java/org/codelutin/math/matrix/MatrixStringEncoderTest.java 2009-03-04 09:42:17 UTC (rev 123) @@ -0,0 +1,146 @@ +/* *##% lutinmatrix + * Copyright (C) 2004 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ + +package org.codelutin.math.matrix; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * MatrixHelperTest. + * + * Created: 29 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision: 120 $ + * + * Mise a jour: $Date: 2009-03-03 11:19:18 +0100 (mar. 03 mars 2009) $ + * par : $Author: chatellier $ + */ +public class MatrixStringEncoderTest { // MatrixHelperTest + + /** to use log facility, just put in your code: log.info(\"...\"); */ + private static Log log = LogFactory.getLog(MatrixStringEncoderTest.class); + + protected MatrixStringEncoder stringEncoder; + + @Before + public void setUp() { + stringEncoder = new MatrixStringEncoder(); + } + + public MatrixFactory getFactory() { + return MatrixFactory.getInstance(); + } + + @Test + public void testMatrixStringRepresentation() { + + MatrixND mat1 = getFactory().create(new int[] { 3, 2, 1 }); + mat1.setValue(0, 0, 0, -1.0E-7); + mat1.setValue(1, 1, 0, 2); + mat1.setValue(2, 1, 0, 5.0E-7); + + String rep = stringEncoder.getMatrixAsString(mat1); + + System.out.println(rep); + + Assert.assertTrue("Null() semantics missing", rep.indexOf("null()") > 0); + Assert.assertTrue("Dimentation missing", rep.indexOf("3, 2, 1") > 0); + Assert.assertTrue("Data missing", rep.indexOf("[2.0]") > 0); + } + + @Test + public void testMatrixFromString() { + String representation = "[,[3, 2, 1],[\"\", \"\", \"\"],[[null(), null(), null()], [null(), null()], [null()]],[[[-1.0E-7], [0.0]], [[0.0], [2.0]], [[0.0], [5.0E-7]]]]"; + + MatrixND matrix = stringEncoder.getMatrixFromString(representation); + + Assert.assertEquals(3, matrix.getDim()[0]); + Assert.assertEquals(2, matrix.getDim()[1]); + Assert.assertEquals(1, matrix.getDim()[2]); + Assert.assertEquals(-1.0E-7, matrix.getValue(0, 0, 0), 0); + Assert.assertEquals(2, matrix.getValue(1, 1, 0), 0); + Assert.assertEquals(5.0E-7, matrix.getValue(2, 1, 0), 0); + } + + @Test + public void testMatrixStringRepresentationWithMoreInfos() { + + MatrixND mat1 = getFactory().create(new int[] { 2, 5 }); + mat1.setName("StringRepresentationWithMoreInfos"); + mat1.setValue(0, 0, -2); + mat1.setValue(1, 1, 2.345); + mat1.setValue(1, 4, -8.321); + + List<Serializable> sem0 = new ArrayList<Serializable>(); + sem0.add(new String("test")); + sem0.add(new Double(3.453)); + mat1.setSemantics(0, sem0); + List<Serializable> sem1 = new ArrayList<Serializable>(); + sem1.add(new Integer(7)); + sem1.add(new Character('e')); + sem1.add(Byte.valueOf("1")); + sem1.add(Short.valueOf("3")); + sem1.add(new Integer(12)); + mat1.setSemantics(1, sem1); + + mat1.setDimensionNames(new String[] {"col1", "col2"}); + + String rep = stringEncoder.getMatrixAsString(mat1); + + System.out.println(rep); + + Assert.assertTrue("java.lang.String semantics missing", rep.indexOf("java.lang.String") > 0); + Assert.assertTrue("Dimentation missing", rep.indexOf("[2, 5]") > 0); + Assert.assertTrue("Data missing", rep.indexOf("[0.0, 2.345, 0.0, 0.0, -8.321]") > 0); + Assert.assertTrue("Columns name missing", rep.indexOf("[\"col1\", \"col2\"]") > 0); + Assert.assertTrue("Name missing", rep.indexOf("StringRepresentationWithMoreInfos") > 0); + + } + + @Test + public void testMatrixFromStringWithMoreInfos() { + String representation = "[StringRepresentationWithMoreInfos,[2, 5],[\"col1\", \"col2\"],[[java.lang.String(test), java.lang.Double(3.453)], [java.lang.Integer(7), java.lang.Character(e), java.lang.Byte(1), java.lang.Short(3), java.lang.Integer(12)]],[[-2.0, 0.0, 0.0, 0.0, 0.0], [0.0, 2.345, 0.0, 0.0, -8.321]]]"; + + MatrixND matrix = stringEncoder.getMatrixFromString(representation); + + Assert.assertEquals("StringRepresentationWithMoreInfos", matrix.getName()); + Assert.assertEquals(2, matrix.getDim()[0]); + Assert.assertEquals(5, matrix.getDim()[1]); + Assert.assertEquals("col1", matrix.getDimensionNames()[0]); + Assert.assertEquals("col2", matrix.getDimensionNames()[1]); + Assert.assertEquals("test", matrix.getSemantics(0).get(0)); + Assert.assertEquals(3.453, matrix.getSemantics(0).get(1)); + Assert.assertEquals(7, matrix.getSemantics(1).get(0)); + Assert.assertEquals('e', matrix.getSemantics(1).get(1)); + Assert.assertEquals(Byte.valueOf("1"), matrix.getSemantics(1).get(2)); + Assert.assertEquals(Short.valueOf("3"), matrix.getSemantics(1).get(3)); + Assert.assertEquals(12, matrix.getSemantics(1).get(4)); + Assert.assertEquals(-2, matrix.getValue(0, 0), 0); + Assert.assertEquals(2.345, matrix.getValue(1, 1), 0); + Assert.assertEquals(-8.321, matrix.getValue(1, 4), 0); + } +} // MatrixHelperTest +