[Lutinmatrix-commits] r144 - in nuiton-matrix/trunk: . src/main/java/org src/main/java/org/nuiton src/main/java/org/nuiton/math/matrix src/main/java/org/nuiton/math/matrix/gui src/test/java/org/nuiton/math/matrix src/test/java/org/nuiton/math/matrix/gui
Author: tchemit Date: 2009-05-16 19:21:04 +0000 (Sat, 16 May 2009) New Revision: 144 Added: nuiton-matrix/trunk/src/main/java/org/nuiton/ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/AbstractMatrixND.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/BasicMatrix.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixHelper.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixStringEncoder.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/JAXXMatrixEditor.jaxx nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPanelEditor.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPopupMenu.java Removed: nuiton-matrix/trunk/src/main/java/org/codelutin/ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/AbstractMatrixND.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/BasicMatrix.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixHelper.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixStringEncoder.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/JAXXMatrixEditor.jaxx nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPanelEditor.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPopupMenu.java Modified: nuiton-matrix/trunk/pom.xml nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/BasicMatrixIterator.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/DimensionHelper.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/DoubleBigVector.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/DoubleVector.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/FloatBigVector.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/FloatVector.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MapFunction.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixEncoder.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixException.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixFactory.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixIterator.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixIteratorImpl.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixND.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixNDImpl.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/SemanticList.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/SubMatrix.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/Vector.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixEditor.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPanelEvent.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPanelListener.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixTableModel.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixTableModelLinear.java nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixTableModelND.java nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/BasicMatrixBigTest.java nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/BasicMatrixTest.java nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/FloatVectorTest.java nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/ImportExportMatrixTest.java nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/MatrixHelperTest.java nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/MatrixNDTest.java nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/MatrixStringEncoderTest.java nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/PerfTest.java nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/SubMatrixTest.java nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/gui/MatrixTableModelTest.java Log: migrate to nuiton (part two) Modified: nuiton-matrix/trunk/pom.xml =================================================================== --- nuiton-matrix/trunk/pom.xml 2009-05-16 18:41:40 UTC (rev 143) +++ nuiton-matrix/trunk/pom.xml 2009-05-16 19:21:04 UTC (rev 144) @@ -81,7 +81,7 @@ <properties> <jaxx.version>1.6.0-SNAPSHOT</jaxx.version> - <maven.test.skip>true</maven.test.skip> + <!-- a supprimer des qu'on pourra deployer les sites sur nuiton --> <site.deploy.url>scpexe://labs.libre-entreprise.org/home/groups/lutinmatrix/htdocs</site.deploy.url> @@ -165,7 +165,8 @@ </build> - <!--reporting> + <!-- devrait etre remonte dans le super-pom --> + <reporting> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> @@ -173,7 +174,7 @@ <version>1.2</version> </plugin> </plugins> - </reporting--> + </reporting> <!-- ************************************************************* --> <!-- *** Build Environment ************************************** --> Copied: nuiton-matrix/trunk/src/main/java/org/nuiton (from rev 142, nuiton-matrix/trunk/src/main/java/org/codelutin) Property changes on: nuiton-matrix/trunk/src/main/java/org/nuiton ___________________________________________________________________ Name: svn:mergeinfo + Deleted: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/AbstractMatrixND.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/AbstractMatrixND.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/AbstractMatrixND.java 2009-05-16 19:21:04 UTC (rev 144) @@ -1,1065 +0,0 @@ -/* *##% 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.IOException; -import java.io.Reader; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.regex.Pattern; - -import org.apache.commons.collections.primitives.ArrayIntList; -import org.apache.commons.lang.ObjectUtils; -import org.apache.commons.lang.math.NumberUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.codelutin.util.ArrayUtil; - -/** - * AbstractMatrixND. - * - * Created: 29 oct. 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - * @version $Revision$ - * - * Mise a jour: $Date$ - * par : $Author$ - */ -public abstract class AbstractMatrixND implements MatrixND { // AbstractMatrixND - - /** serialVersionUID. */ - private static final long serialVersionUID = -6838751468730930727L; - - /** to use log facility, just put in your code: log.info(\"...\"); */ - private static Log log = LogFactory.getLog(AbstractMatrixND.class); - - public abstract MatrixIterator iterator(); - - public abstract double getValue(int[] coordinates); - - public abstract void setValue(int[] coordinates, double d); - - protected transient DimensionHelper dimHelper = new DimensionHelper(); - - protected transient MatrixFactory factory = null; - - protected String name = ""; - - protected String[] dimNames = null; - - protected int[] dim = null; - - protected List[] semantics = null; - - protected double defaultValue = 0; - - /** - * Separateur CSV par défaut le point virgule. - */ - public static final char CSV_SEPARATOR = ';'; - - protected static final Pattern NUMBER = Pattern - .compile(" *[+-]?[0-9]*\\.?[0-9]+([eE][+-]?[0-9]+)? *"); - - protected void init(int[] dim) { - this.dim = new int[dim.length]; - System.arraycopy(dim, 0, this.dim, 0, dim.length); - semantics = new List[dim.length]; - dimNames = new String[dim.length]; - // par defaut chaine vide pour le nom des dimensions - Arrays.fill(dimNames, ""); - } - - protected AbstractMatrixND(MatrixFactory factory) { - this.factory = factory; - } - - public AbstractMatrixND(MatrixFactory factory, int[] dim) { - this(factory); - init(dim); - for (int i = 0; i < getNbDim(); i++) { - // par defaut les listes des semantiques contiennent des nulls - semantics[i] = Collections.nCopies(dim[i], null); - } - } - - public AbstractMatrixND(MatrixFactory factory, List[] semantics) { - this(factory); - int[] dim = new int[semantics.length]; - for (int i = 0; i < dim.length; i++) { - if (semantics[i] == null) { - dim[i] = 0; - } else { - dim[i] = semantics[i].size(); - } - } - init(dim); - for (int i = 0; i < getNbDim(); i++) { - setSemantics(i, semantics[i]); - } - } - - public AbstractMatrixND(MatrixFactory factory, String name, int[] dim) { - this(factory, dim); - setName(name); - } - - public AbstractMatrixND(MatrixFactory factory, String name, int[] dim, - String[] dimNames) { - this(factory, dim); - setName(name); - for (int i = 0; dimNames != null && i < dimNames.length; i++) { - setDimensionName(i, dimNames[i]); - } - } - - public AbstractMatrixND(MatrixFactory factory, String name, List[] semantics) { - this(factory, semantics); - setName(name); - } - - public AbstractMatrixND(MatrixFactory factory, String name, - List[] semantics, String[] dimNames) { - this(factory, name, semantics); - for (int i = 0; dimNames != null && i < dimNames.length; i++) { - setDimensionName(i, dimNames[i]); - } - } - - /* - * (non-Javadoc) - * - * @see org.codelutin.math.matrix.MatrixND#copy() - */ - public MatrixND copy() { - MatrixND result = getFactory().create(this); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#clone() - */ - @Override - public MatrixND clone() { - return copy(); - } - - /** - * Retourne la factory utilisée pour créer cette matrice, la factory - * peut-être réutilisé pour créer d'autre matrice si besoin. - */ - public MatrixFactory getFactory() { - return factory; - } - - public List[] getSemantics() { - return semantics; - } - - public List getSemantics(int dim) { - return semantics[dim]; - } - - public void setSemantics(int dim, List sem) { - if (!(sem instanceof SemanticList)) { - sem = new SemanticList(sem); - } - // else SemanticList is immutable and can be used in many matrix in - // same time this permit to used same indexOf optimization - semantics[dim] = sem; - } - - public void setName(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - 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; - } - - public String getDimensionName(int dim) { - return dimNames[dim]; - } - - 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 - // un tableau il ne faut pas le recréer, on peut le passer directement - int nbelem = 1; - for (int i = 0; i < getNbDim(); i++) { - nbelem *= getDim(i); - } - double[] data = new double[nbelem]; - int i = 0; - for (MatrixIterator mi = iterator(); mi.next();) { - data[i++] = mi.getValue(); - } - return MatrixHelper.maxOccurence(data); - } - - public int getNbDim() { - return dim.length; - } - - public int[] getDim() { - return dim; - } - - public int getDim(int d) { - return dim[d]; - } - - /** - * Retourne la matrice elle meme. Les modifications sont faites directement - * dessus - */ - public MatrixND map(MapFunction f) { - for (MatrixIterator i = iterator(); i.next();) { - i.setValue(f.apply(i.getValue())); - } - return this; - } - - public double getValue(Object[] coordinates) { - return getValue(MatrixHelper.semanticsToDimension(getSemantics(), - coordinates)); - } - - public double getValue(Object x) { - // on peut utiliser dimHelper car le get ne le reutilisera pas en - // interne - return getValue(dimHelper.get(x)); - } - - public double getValue(Object x, Object y) { - return getValue(dimHelper.get(x, y)); - } - - public double getValue(Object x, Object y, Object z) { - return getValue(dimHelper.get(x, y, z)); - } - - public double getValue(Object x, Object y, Object z, Object t) { - return getValue(dimHelper.get(x, y, z, t)); - }; - - public double getValue(int x) { - // on peut utiliser dimHelper car le get ne le reutilisera pas en - // interne - return getValue(dimHelper.get(x)); - } - - public double getValue(int x, int y) { - return getValue(dimHelper.get(x, y)); - } - - public double getValue(int x, int y, int z) { - return getValue(dimHelper.get(x, y, z)); - } - - public double getValue(int x, int y, int z, int t) { - return getValue(dimHelper.get(x, y, z, t)); - } - - public void setValue(Object[] coordinates, double d) { - setValue( - MatrixHelper.semanticsToDimension(getSemantics(), coordinates), - d); - } - - public void setValue(Object x, double d) { - setValue(dimHelper.get(x), d); - } - - public void setValue(Object x, Object y, double d) { - setValue(dimHelper.get(x, y), d); - } - - public void setValue(Object x, Object y, Object z, double d) { - setValue(dimHelper.get(x, y, z), d); - } - - public void setValue(Object x, Object y, Object z, Object t, double d) { - setValue(dimHelper.get(x, y, z, t), d); - } - - public void setValue(int x, double d) { - setValue(dimHelper.get(x), d); - } - - public void setValue(int x, int y, double d) { - setValue(dimHelper.get(x, y), d); - } - - public void setValue(int x, int y, int z, double d) { - setValue(dimHelper.get(x, y, z), d); - } - - public void setValue(int x, int y, int z, int t, double d) { - setValue(dimHelper.get(x, y, z, t), d); - } - - // TODO peut-etre faire une variante de equals qui regarde par rapport au - // coordonnées sémantique - public boolean equals(Object o) { - return o instanceof MatrixND && equals((MatrixND) o); - } - - public boolean equals(MatrixND mat) { - boolean result = true; - // le nom doit être le même - result = result && getName().equals(mat.getName()); - - result = result && equalsValues(mat); - - // les sémantiques doivent-être identique - for (int i = 0; result && i < getNbDim(); i++) { - String dimName1 = getDimensionName(i); - String dimName2 = mat.getDimensionName(i); - result = ObjectUtils.equals(dimName1, dimName2); - if (log.isTraceEnabled()) { - log.trace("dimName1(" + dimName1 + ")==dimName2(" + dimName2 - + ")=" + result); - } - // System.out.println("dimName1("+dimName1+")==dimName2("+dimName2+ - // ")="+result); - - List sem1 = getSemantics(i); - List sem2 = mat.getSemantics(i); - result = result && ObjectUtils.equals(sem1, sem2); - if (log.isTraceEnabled()) { - log.trace("sem1(" + sem1 + ")==sem2(" + sem2 + ")=" + result); - } - // System.out.println("sem1("+sem1+")==sem1("+sem2+ ")="+result); - } - - if (log.isTraceEnabled()) { - log.trace("result=" + result); - } - // System.out.println("result="+result); - return result; - } - - /** - * Verifie si les matrices sont egales en ne regardant que les valeurs et - * pas les semantiques - * - * @param mat - * @return - */ - public boolean equalsValues(MatrixND mat) { - boolean result = true; - // les dimensions doivent-être identique - result = result && MatrixHelper.sameDimension(getDim(), mat.getDim()); - - // toutes les données doivent être identique - for (MatrixIterator i = mat.iterator(); result && i.next();) { - double v1 = i.getValue(); - double v2 = getValue(i.getCoordinates()); - result = v1 == v2; - if (log.isDebugEnabled()) { - log.debug("v1(" + v1 + ")==v2(" + v2 + ")=" + result); - } - // System.out.println("v1("+v1+")==v2("+v2+ ")="+result); - } - - return result; - } - - public String toString() { - StringBuffer result = new StringBuffer(); - result.append("dimensions = [\n"); - for (int i = 0; i < getDim().length; i++) { - result.append(getDim()[i] + ","); - } - result.append("\n]\nmatrice = [\n"); - for (MatrixIterator i = this.iterator(); i.next();) { - result.append(i.getValue() + ","); - } - result.append("\n]\n"); - return result.toString(); - } - - public List toList() { - List result = new ArrayList(); - // [3,2,5,4] - for (MatrixIterator i = iterator(); i.next();) { - int[] coord = i.getCoordinates(); - double value = i.getValue(); - List tmp = result; - for (int dim = 0; dim < coord.length - 1; dim++) { - while (tmp.size() <= coord[dim]) { - tmp.add(new ArrayList()); - } - tmp = (List) tmp.get(coord[dim]); - } - while (tmp.size() <= coord[coord.length - 1]) { - tmp.add(NumberUtils.DOUBLE_ZERO); - } - - tmp.set(coord[coord.length - 1], value); - } - - return result; - } - - public void fromList(List list) { - // on suppose que les listes sont bien formé, c-a-d qu'elles sont - // toutes de la meme dimension pour une dimension donnée. - ArrayIntList dim = new ArrayIntList(); - List tmp = list; - while (tmp.get(tmp.size() - 1) instanceof List) { - dim.add(tmp.size()); - tmp = (List) tmp.get(tmp.size() - 1); - } - dim.add(tmp.size()); - MatrixND mat = getFactory().create(dim.toArray()); - - for (MatrixIterator i = mat.iterator(); i.next();) { - int[] coord = i.getCoordinates(); - tmp = list; - for (int d = 0; d < coord.length - 1; d++) { - tmp = (List) tmp.get(coord[d]); - } - - Double value = (Double) tmp.get(coord[coord.length - 1]); - i.setValue(value); - } - paste(mat); - } - - public boolean isValidCoordinates(int[] dim) { - boolean result = getNbDim() == dim.length; - for (int i = 0; result && i < dim.length; i++) { - result = 0 <= dim[i] && dim[i] < getDim(i); - } - return result; - } - - public boolean isValidCoordinates(Object[] semantics) { - boolean result = getNbDim() == semantics.length; - for (int i = 0; result && i < semantics.length; i++) { - result = getSemantics(i).contains(semantics[i]); - } - return result; - } - - /* - * (non-Javadoc) - * - * @see org.codelutin.math.matrix.MatrixND#sumAll() - */ - public double sumAll() { - double result = 0; - for (MatrixIterator i = iterator(); i.next();) { - result += i.getValue(); - } - return result; - } - - public MatrixND sumOverDim(int dim) { - return sumOverDim(dim, getDim(dim)); - } - - public MatrixND sumOverDim(int dim, int step) { - if (step < 0) { - step = getDim(dim); - } else if (step <= 1) { - // il n'y a rien a faire, on fait une copie et on la retrourne - return getFactory().create(this); - } - - // le nombre d'element qu'il y aura dans la dim pour le resultat - int nbDim = getDim(dim) / step; - - List[] semantics = new List[getNbDim()]; - System.arraycopy(getSemantics(), 0, semantics, 0, getNbDim()); - semantics[dim] = semantics[dim].subList(0, nbDim); - - // creation du resultat - MatrixND result = getFactory().create(getName(), semantics, - getDimensionNames()); - - for (int i = 0; i < result.getDim(dim); i++) { - MatrixND temp = getSubMatrix(dim, i * step, step); - MatrixND sum = result.getSubMatrix(dim, i, 1); - for (int s = 0; s < temp.getDim(dim); s++) { - sum.add(temp.getSubMatrix(dim, s, 1)); - } - } - return result; - } - - public MatrixND sumOverDim(int dim, int start, int nb) { - // copie de l'ancienne semantique - List[] semantics = new List[getNbDim()]; - System.arraycopy(getSemantics(), 0, semantics, 0, getNbDim()); - semantics[dim] = new ArrayList<Object>(semantics[dim]); - - // creation d'un liste qui agrege les elements sommés - List<Object> newElem = new ArrayList<Object>(); - for (int i = 0; i < nb; i++) { - newElem.add(semantics[dim].remove(start)); - } - // on ajout la liste comme nouvel element de la semantique - semantics[dim].add(start, newElem); - - // creation du resultat - MatrixND result = getFactory().create(getName(), semantics, - getDimensionNames()); - - MatrixND sub1 = this.getSubMatrix(dim, 0, start); - MatrixND sub2 = this.getSubMatrix(dim, start, nb).sumOverDim(dim); - MatrixND sub3 = this.getSubMatrix(dim, start + nb, getDim(dim) - - (start + nb)); - - int[] origin = new int[getNbDim()]; - result.paste(origin, sub1); - origin[dim] = start; - result.paste(origin, sub2); - if (start + 1 < result.getDim(dim)) { - origin[dim] = start + 1; - result.paste(origin, sub3); - } - - return result; - } - - public MatrixND cut(int dim, int[] toCut) { - throw new UnsupportedOperationException("Méthode non implantée"); - } - - /** - * Modifie la matrice actuel en metant les valeurs de mat passé en parametre - */ - public MatrixND paste(MatrixND mat) { - return paste(new int[getNbDim()], mat); - } - - /** - * Modifie la matrice actuel en metant les valeurs de mat passé en parametre - * - * @param origin le point d'origine a partir duquel on colle la matrice - * @param mat une matrice avec le meme nombre de dimension, si la matrice - * que l'on colle est trop grande, les valeurs qui depasse ne - * sont pas prises en compte - */ - public MatrixND paste(int[] origin, MatrixND mat) { - // TODO, si les matrice mat et this on les memes dimensions - // et que origin est 0 - // on doit pouvoir optimiser en appeler une methode paste - // sur BasicMatrix qui l'appel sur le vector - if (mat != null) { - for (MatrixIterator mi = mat.iterator(); mi.next();) { - int[] coordinates = ArrayUtil.sum(origin, mi.getCoordinates()); - if (isValidCoordinates(coordinates)) { - setValue(coordinates, mi.getValue()); - } - } - } - return this; - } - - /** - * Modifie la matrice actuel en metant les valeurs de mat passé en parametre - * La copie se fait en fonction de la semantique, si un element dans une - * dimension n'est pas trouvé, alors il est passé - */ - public MatrixND pasteSemantics(MatrixND mat) { - if (mat != null) { - for (MatrixIterator mi = mat.iterator(); mi.next();) { - Object[] sems = mi.getSemanticsCoordinates(); - if (isValidCoordinates(sems)) { - setValue(sems, mi.getValue()); - } - } - } - return this; - } - - public MatrixND getSubMatrix(int dim, int start, int nb) { - if (dim < 0) { - dim = getNbDim() + dim; - } - if (start < 0) { - start = getDim(dim) + start; - } - if (nb <= 0) { - nb = getDim(dim) - start; - } - return new SubMatrix(this, dim, start, nb); - } - - public MatrixND getSubMatrix(int dim, Object start, int nb) { - int begin = MatrixHelper.indexOf(getSemantics(), dim, start); - return getSubMatrix(dim, begin, nb); - } - - /** - * Add to desambiguas some call with xpath engine, but do the same thing - * {@link #getSubMatrix(int, Object[])} - * - * @param dim - * @param elem - * @return - */ - public MatrixND getSubMatrixOnSemantic(int dim, Object... elem) { - MatrixND result = getSubMatrix(dim, elem); - return result; - } - - public MatrixND getSubMatrix(int dim, Object... elem) { - int[] ielem = new int[elem.length]; - for (int i = 0; i < ielem.length; i++) { - ielem[i] = MatrixHelper.indexOf(getSemantics(), dim, elem[i]); - } - return getSubMatrix(dim, ielem); - } - - public MatrixND getSubMatrix(int dim, int[] elem) { - return new SubMatrix(this, dim, elem); - } - - /** - * Modifie la matrice actuelle en lui ajoutant les valeurs de la matrice - * passé en parametre. La matrice passé en parametre doit avoir le meme - * nombre de dimension, et chacune de ses dimensions doit avoir un nombre - * d'element au moins egal a cette matrice. - */ - public MatrixND add(MatrixND m) { - // TODO si les dimensions sont exactment les memes, on doit pouvoir - // gagner du temps en travaillant directement au niveau du vector - for (MatrixIterator i = iterator(); i.next();) { - i.setValue(i.getValue() + m.getValue(i.getCoordinates())); - // TODO faire une variante de add avec les semantiques - } - return this; - } - - /** - * Modifie la matrice actuelle en lui soustrayant les valeurs de la matrice - * passé en parametre. La matrice passé en parametre doit avoir le meme - * nombre de dimension, et chacune de ses dimensions doit avoir un nombre - * d'element au moins egal a cette matrice. - */ - public MatrixND minus(MatrixND m) { - // TODO si les dimensions sont exactment les memes, on doit pouvoir - // gagner du temps en travaillant directement au niveau du vector - for (MatrixIterator i = iterator(); i.next();) { - i.setValue(i.getValue() - m.getValue(i.getSemanticsCoordinates())); - } - return this; - } - - public MatrixND transpose() { - if (getNbDim() > 2) { - throw new MatrixException( - "La transpose ne peut-être fait que sur une matrice ayant 2 dimensions ou moins"); - } - if (getNbDim() == 1) { - MatrixND result = getFactory() - .create( - getName(), - new List[] { Collections.nCopies(1, null), - getSemantics(0) }, - new String[] { "Dimension 0", getDimensionName(0) }); - for (int x = 0; x < getDim(0); x++) { - result.setValue(0, x, getValue(x)); - } - return result; - } else { - MatrixND result = getFactory().create(getName(), - new List[] { getSemantics(1), getSemantics(0) }, - new String[] { getDimensionName(1), getDimensionName(0) }); - for (int x = 0; x < getDim(0); x++) { - for (int y = 0; y < getDim(1); y++) { - result.setValue(y, x, getValue(x, y)); - } - } - return result; - } - } - - public MatrixND reduce() { - return reduce(1); - } - - public MatrixND reduceDims(int... dims) { - Arrays.sort(dims); - // tableau permettant de faire la correspondance entre les dimensions - // de la matrice actuelle et les dimentsions de la nouvelle matrice - // l'element i du tableau qui correcpond à la dimensions i de la - // nouvelle matrice contient la dimension equivalente dans - // la matrice actuelle - int[] correspondance = new int[getNbDim()]; - // les nouvelles semantiques - List sem = new ArrayList(); - // les nouveaux noms de dimensions - List dimName = new ArrayList(); - // il faut au moins une dimension pour la matrice - int minNbDim = 1; - for (int j = getNbDim() - 1; j >= 0; j--) { - // si la dimension à plus d'un élément ou qu'il n'est pas dans dims - // on garde la dimension - if (getDim(j) > 1 || Arrays.binarySearch(dims, j) < 0 - || j < minNbDim) { - // on ne conserve que les dimensions supérieure à 1 - correspondance[sem.size()] = j; - sem.add(getSemantics(j)); - dimName.add(getDimensionName(j)); - minNbDim--; - } - } - MatrixND result = reduce(dimName, sem, correspondance); - return result; - } - - public MatrixND reduce(int minNbDim) { - // tableau permettant de faire la correspondance entre les dimensions - // de la matrice actuelle et les dimentsions de la nouvelle matrice - // l'element i du tableau qui correcpond à la dimensions i de la - // nouvelle matrice contient la dimension equivalente dans - // la matrice actuelle - int[] correspondance = new int[getNbDim()]; - // les nouvelles semantiques - List sem = new ArrayList(); - // les nouveaux noms de dimensions - List dimName = new ArrayList(); - for (int j = getNbDim() - 1; j >= 0; j--) { - // si la dimension à plus d'un élément ou si on a pas assez de - // dimension pour avoir le minimum demandé on prend la dimension - if (getDim(j) > 1 || j < minNbDim) { - // on ne conserve que les dimensions supérieure à 1 - correspondance[sem.size()] = j; - sem.add(getSemantics(j)); - dimName.add(getDimensionName(j)); - // on vient de prendre une dimension il nous en faut une de - // moins - minNbDim--; - } - } - - MatrixND result = reduce(dimName, sem, correspondance); - return result; - } - - /** - * Create new matrice from the current matrix. - * - * @param dimName dimension name for new matrix - * @param sem semantic for new matrix - * @param correspondance array to do the link between current matrix and - * returned matrix - * @return new matrix - */ - protected MatrixND reduce(List dimName, List sem, int[] correspondance) { - // on converti les listes en tableau en inversant l'ordre car on - // a fait un parcours en sens inverse - int nbDim = sem.size(); - List[] newSemantics = new List[nbDim]; - String[] newDimNames = new String[nbDim]; - int[] tmpcorrespondance = new int[nbDim]; - for (int i = 0; i < nbDim; i++) { - newSemantics[i] = (List) sem.get(nbDim - 1 - i); - newDimNames[i] = (String) dimName.get(nbDim - 1 - i); - tmpcorrespondance[i] = correspondance[nbDim - 1 - i]; - } - correspondance = tmpcorrespondance; - - MatrixND result = getFactory().create(getName(), newSemantics, - newDimNames); - - // on reprend les valeurs - int[] newCoordinates = new int[result.getNbDim()]; - for (MatrixIterator mi = iterator(); mi.next();) { - int[] oldCoordinates = mi.getCoordinates(); - for (int i = 0; i < newCoordinates.length; i++) { - newCoordinates[i] = oldCoordinates[correspondance[i]]; - } - result.setValue(newCoordinates, mi.getValue()); - } - return result; - } - - public MatrixND mult(MatrixND m) throws MatrixException { - if (this.getNbDim() > 2 || m.getNbDim() > 2) { - throw new MatrixException( - "La multiplication de matrice n'est pas applicable aux matrices de plus de 2 dimensions"); - } - if (!((this.getDim(1) == m.getDim(0)))) { - throw new MatrixException( - "Le nombre de colonnes de la matrice m1 doit etre egal au nombre de lignes de la matrice m2"); - } - - MatrixND result = getFactory().create( - new int[] { this.getDim(0), m.getDim(1) }); - double d; - for (int x = 0; x < this.getDim(0); x++) { - for (int y = 0; y < m.getDim(1); y++) { - d = this.getValue(x, 0) * m.getValue(0, y); - for (int k = 1; k < this.getDim(1); k++) { - d += this.getValue(x, k) * m.getValue(k, y); - } - result.setValue(x, y, d); - } - } - return result; - } - - public MatrixND mults(final double d) { - map(new MapFunction() { - public double apply(double val) { - return val * d; - } - }); - return this; - } - - public MatrixND divs(final double d) { - map(new MapFunction() { - public double apply(double val) { - return val / d; - } - }); - return this; - } - - public MatrixND adds(final double d) { - map(new MapFunction() { - public double apply(double val) { - return val + d; - } - }); - return this; - } - - public MatrixND minuss(final double d) { - map(new MapFunction() { - public double apply(double val) { - return val - d; - } - }); - return this; - } - - /** - * Determine si la matrice supporte l'import et l'export CSV - * - * @return support du CSV - */ - public boolean isSupportedCSV() { - return getNbDim() <= 2; - } - - /** - * Import depuis un reader au format CSV des données dans la matrice - * - * @param reader le reader à importer - * @param origin le point à partir duquel il faut faire l'importation - * int[]{x,y} - */ - public void importCSV(Reader reader, int[] origin) throws IOException { - int rowsCount = 0; - List<Double> row = new ArrayList<Double>(); - StringBuffer number = new StringBuffer(20); - boolean stop = false; - - for (int c = reader.read(); !stop; c = reader.read()) { - if (c == -1) { - stop = true; - } - if (c == ' ') { - // skip space - } else if (c == CSV_SEPARATOR) { - if (NUMBER.matcher(number.toString()).matches()) { - Double val = Double.valueOf(number.toString()); - row.add(val); - } - number.setLength(0); - } else if (c == -1 || c == '\n' || c == '\r') { - // is line return or equivalent char because space is already - // skiped - // or end of stream - - // at end of line, we must see if the leave number - if (NUMBER.matcher(number.toString()).matches()) { - Double val = Double.valueOf(number.toString()); - row.add(val); - } - number.setLength(0); - - if (!row.isEmpty()) { - if (getDim().length == 1) { - int columnNumber = origin[0]; - for (Double value : row) { - if (columnNumber < getDim(0)) { - setValue(new int[] { columnNumber }, value); - columnNumber++; - } - } - } else if (getDim().length == 2) { - MatrixND matrix = getFactory().create( - new int[] { 1, row.size() }); - int columnNumber = 0; - for (Double value : row) { - matrix.setValue(new int[] { 0, columnNumber }, - value); - columnNumber++; - } - paste(new int[] { origin[0] + rowsCount, origin[1] }, - matrix); - rowsCount++; - row.clear(); - } else { - throw new MatrixException( - "Can't import matrix with more than 2 dimensions."); - } - } - } else { - number.append((char) c); - } - } - - // cette implatation avec StreamTokenizer ne fonctionne pas - // car il ne sait pas reconnaitre tous les nombres: 5.0E-7 - // int rowsCount = 0; - // StreamTokenizer tokenizer; - // List<Double> row = new ArrayList<Double>(); - // boolean stop = false; - // - // tokenizer = new StreamTokenizer(reader); - // tokenizer.eolIsSignificant(true); - // - // while(!stop) { - // tokenizer.nextToken(); - // - // switch (tokenizer.ttype) { - // case StreamTokenizer.TT_EOF: - // stop = true; // no break we do next case too - // case StreamTokenizer.TT_EOL: - // if(!row.isEmpty()) { - // MatrixND matrix = getFactory().create(new int[]{1, row.size()}); - // int columnNumber = 0; - // for (Double value : row) { - // matrix.setValue(new int[]{0, columnNumber}, value); - // columnNumber++; - // } - // paste(new int[]{origin[0] + rowsCount, origin[1]}, matrix); - // rowsCount ++; - // row.clear(); - // } - // break; - // case StreamTokenizer.TT_NUMBER: - // System.out.println("+++++++++ " + tokenizer.nval); - // row.add(tokenizer.nval); - // break; - // case StreamTokenizer.TT_WORD: - // System.out.println("--------- " + tokenizer.nval); - // break; - // default: - // break; - // } - // } - } - - /** - * Export dans un writer au format CSV de la matrice - * - * @param writer le writer ou copier la matrice - * @param withSemantics export ou pas des semantiques de la matrice dans le - * writer - */ - public void exportCSV(Writer writer, boolean withSemantics) - throws IOException { - int dimsCount = getNbDim(); - int rowsCount = dimsCount == 1 ? 1 : getDim(0); - int columnsCount = dimsCount == 1 ? getDim(0) : getDim(1); - int[] coordinates; - - if (!isSupportedCSV()) { - throw new UnsupportedOperationException(); - } - - /* Création de l'entete */ - if (withSemantics) { - /* Recuperation de la liste sur la bonne dimenssion */ - List listSemantics = getSemantics(dimsCount - 1); - /* Ajout d'un décalage de l'entete pour la dimenssion 2 */ - writer.append(dimsCount == 2 ? " " + CSV_SEPARATOR : ""); - for (Object semantic : listSemantics) { - writer.append("\"" + semantic + "\"" + CSV_SEPARATOR); - } - writer.append("\n"); - } - - for (int rowNb = 0; rowNb < rowsCount; rowNb++) { - /* Ajout de la semantic devant la ligne pour la dimenssion 2 */ - if (withSemantics && dimsCount == 2) { - Object semantic = getSemantics(0).get(rowNb); - writer.append("\"" + semantic + "\"" + CSV_SEPARATOR); - } - - for (int columnNb = 0; columnNb < columnsCount; columnNb++) { - /* Calcul des coordonnees */ - coordinates = dimsCount == 1 ? new int[] { columnNb } - : new int[] { rowNb, columnNb }; - writer.append(getValue(coordinates) + "" + CSV_SEPARATOR); - } - writer.append("\n"); - } - } - -} // AbstractMatrixND Copied: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/AbstractMatrixND.java (from rev 143, nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/AbstractMatrixND.java) =================================================================== --- nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/AbstractMatrixND.java (rev 0) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/AbstractMatrixND.java 2009-05-16 19:21:04 UTC (rev 144) @@ -0,0 +1,1131 @@ +/* *##% 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.nuiton.math.matrix; + +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.regex.Pattern; + +import org.apache.commons.collections.primitives.ArrayIntList; +import org.apache.commons.lang.ObjectUtils; +import org.apache.commons.lang.math.NumberUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.util.ArrayUtil; + +/** + * AbstractMatrixND. + * + * Created: 29 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public abstract class AbstractMatrixND implements MatrixND { // AbstractMatrixND + + /** serialVersionUID. */ + private static final long serialVersionUID = -6838751468730930727L; + + /** to use log facility, just put in your code: log.info(\"...\"); */ + private static Log log = LogFactory.getLog(AbstractMatrixND.class); + + public abstract MatrixIterator iterator(); + + public abstract double getValue(int[] coordinates); + + public abstract void setValue(int[] coordinates, double d); + + protected transient DimensionHelper dimHelper = new DimensionHelper(); + + protected transient MatrixFactory factory = null; + + protected String name = ""; + + protected String[] dimNames = null; + + protected int[] dim = null; + + protected List[] semantics = null; + + protected double defaultValue = 0; + + /** + * Separateur CSV par défaut le point virgule. + */ + public static final char CSV_SEPARATOR = ';'; + + protected static final Pattern NUMBER = Pattern + .compile(" *[+-]?[0-9]*\\.?[0-9]+([eE][+-]?[0-9]+)? *"); + + protected void init(int[] dim) { + this.dim = new int[dim.length]; + System.arraycopy(dim, 0, this.dim, 0, dim.length); + semantics = new List[dim.length]; + dimNames = new String[dim.length]; + // par defaut chaine vide pour le nom des dimensions + Arrays.fill(dimNames, ""); + } + + protected AbstractMatrixND(MatrixFactory factory) { + this.factory = factory; + } + + public AbstractMatrixND(MatrixFactory factory, int[] dim) { + this(factory); + init(dim); + for (int i = 0; i < getNbDim(); i++) { + // par defaut les listes des semantiques contiennent des nulls + semantics[i] = Collections.nCopies(dim[i], null); + } + } + + public AbstractMatrixND(MatrixFactory factory, List[] semantics) { + this(factory); + int[] dim = new int[semantics.length]; + for (int i = 0; i < dim.length; i++) { + if (semantics[i] == null) { + dim[i] = 0; + } else { + dim[i] = semantics[i].size(); + } + } + init(dim); + for (int i = 0; i < getNbDim(); i++) { + setSemantics(i, semantics[i]); + } + } + + public AbstractMatrixND(MatrixFactory factory, String name, int[] dim) { + this(factory, dim); + setName(name); + } + + public AbstractMatrixND(MatrixFactory factory, String name, int[] dim, + String[] dimNames) { + this(factory, dim); + setName(name); + for (int i = 0; dimNames != null && i < dimNames.length; i++) { + setDimensionName(i, dimNames[i]); + } + } + + public AbstractMatrixND(MatrixFactory factory, String name, List[] semantics) { + this(factory, semantics); + setName(name); + } + + public AbstractMatrixND(MatrixFactory factory, String name, + List[] semantics, String[] dimNames) { + this(factory, name, semantics); + for (int i = 0; dimNames != null && i < dimNames.length; i++) { + setDimensionName(i, dimNames[i]); + } + } + + /* + * (non-Javadoc) + * + * @see org.codelutin.math.matrix.MatrixND#copy() + */ + public MatrixND copy() { + MatrixND result = getFactory().create(this); + return result; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#clone() + */ + @Override + public MatrixND clone() { + return copy(); + } + + /** + * Retourne la factory utilisée pour créer cette matrice, la factory + * peut-être réutilisé pour créer d'autre matrice si besoin. + */ + @Override + public MatrixFactory getFactory() { + return factory; + } + + @Override + public List[] getSemantics() { + return semantics; + } + + @Override + public List getSemantics(int dim) { + return semantics[dim]; + } + + @Override + public void setSemantics(int dim, List sem) { + if (!(sem instanceof SemanticList)) { + sem = new SemanticList(sem); + } + // else SemanticList is immutable and can be used in many matrix in + // same time this permit to used same indexOf optimization + semantics[dim] = sem; + } + + @Override + public void setName(String name) { + this.name = name; + } + + @Override + public String getName() { + return name; + } + + @Override + public String[] getDimensionNames() { + return dimNames; + } + + @Override + public void setDimensionNames(String[] names) { + for (int i = 0; names != null && i < names.length; i++) { + setDimensionName(i, names[i]); + } + } + + /** + * {@inheritDoc} + * + * @deprecated Use #getDimensionNames() + */ + @Override + public String[] getDimensionName() { + return getDimensionNames(); + } + + /** + * {@inheritDoc} + * + * @deprecated Use #setDimensionName(String[]) + */ + @Override + public void setDimensionName(String[] names) { + setDimensionNames(names); + } + + @Override + public void setDimensionName(int dim, String name) { + dimNames[dim] = name; + } + + @Override + public String getDimensionName(int dim) { + return dimNames[dim]; + } + + @Override + 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 + // un tableau il ne faut pas le recréer, on peut le passer directement + int nbelem = 1; + for (int i = 0; i < getNbDim(); i++) { + nbelem *= getDim(i); + } + double[] data = new double[nbelem]; + int i = 0; + for (MatrixIterator mi = iterator(); mi.next();) { + data[i++] = mi.getValue(); + } + return MatrixHelper.maxOccurence(data); + } + + @Override + public int getNbDim() { + return dim.length; + } + + @Override + public int[] getDim() { + return dim; + } + + @Override + public int getDim(int d) { + return dim[d]; + } + + /** + * Retourne la matrice elle meme. Les modifications sont faites directement + * dessus + */ + @Override + public MatrixND map(MapFunction f) { + for (MatrixIterator i = iterator(); i.next();) { + i.setValue(f.apply(i.getValue())); + } + return this; + } + + @Override + public double getValue(Object[] coordinates) { + return getValue(MatrixHelper.semanticsToDimension(getSemantics(), + coordinates)); + } + + @Override + public double getValue(Object x) { + // on peut utiliser dimHelper car le get ne le reutilisera pas en + // interne + return getValue(dimHelper.get(x)); + } + + @Override + public double getValue(Object x, Object y) { + return getValue(dimHelper.get(x, y)); + } + + @Override + public double getValue(Object x, Object y, Object z) { + return getValue(dimHelper.get(x, y, z)); + } + + @Override + public double getValue(Object x, Object y, Object z, Object t) { + return getValue(dimHelper.get(x, y, z, t)); + }; + + @Override + public double getValue(int x) { + // on peut utiliser dimHelper car le get ne le reutilisera pas en + // interne + return getValue(dimHelper.get(x)); + } + + @Override + public double getValue(int x, int y) { + return getValue(dimHelper.get(x, y)); + } + + @Override + public double getValue(int x, int y, int z) { + return getValue(dimHelper.get(x, y, z)); + } + + @Override + public double getValue(int x, int y, int z, int t) { + return getValue(dimHelper.get(x, y, z, t)); + } + + @Override + public void setValue(Object[] coordinates, double d) { + setValue( + MatrixHelper.semanticsToDimension(getSemantics(), coordinates), + d); + } + + @Override + public void setValue(Object x, double d) { + setValue(dimHelper.get(x), d); + } + + @Override + public void setValue(Object x, Object y, double d) { + setValue(dimHelper.get(x, y), d); + } + + @Override + public void setValue(Object x, Object y, Object z, double d) { + setValue(dimHelper.get(x, y, z), d); + } + + @Override + public void setValue(Object x, Object y, Object z, Object t, double d) { + setValue(dimHelper.get(x, y, z, t), d); + } + + @Override + public void setValue(int x, double d) { + setValue(dimHelper.get(x), d); + } + + @Override + public void setValue(int x, int y, double d) { + setValue(dimHelper.get(x, y), d); + } + + @Override + public void setValue(int x, int y, int z, double d) { + setValue(dimHelper.get(x, y, z), d); + } + + @Override + public void setValue(int x, int y, int z, int t, double d) { + setValue(dimHelper.get(x, y, z, t), d); + } + + // TODO peut-etre faire une variante de equals qui regarde par rapport au + // coordonnées sémantique + @Override + public boolean equals(Object o) { + return o instanceof MatrixND && equals((MatrixND) o); + } + + public boolean equals(MatrixND mat) { + boolean result = true; + // le nom doit être le même + result = result && getName().equals(mat.getName()); + + result = result && equalsValues(mat); + + // les sémantiques doivent-être identique + for (int i = 0; result && i < getNbDim(); i++) { + String dimName1 = getDimensionName(i); + String dimName2 = mat.getDimensionName(i); + result = ObjectUtils.equals(dimName1, dimName2); + if (log.isTraceEnabled()) { + log.trace("dimName1(" + dimName1 + ")==dimName2(" + dimName2 + + ")=" + result); + } + // System.out.println("dimName1("+dimName1+")==dimName2("+dimName2+ + // ")="+result); + + List sem1 = getSemantics(i); + List sem2 = mat.getSemantics(i); + result = result && ObjectUtils.equals(sem1, sem2); + if (log.isTraceEnabled()) { + log.trace("sem1(" + sem1 + ")==sem2(" + sem2 + ")=" + result); + } + // System.out.println("sem1("+sem1+")==sem1("+sem2+ ")="+result); + } + + if (log.isTraceEnabled()) { + log.trace("result=" + result); + } + // System.out.println("result="+result); + return result; + } + + /** + * Verifie si les matrices sont egales en ne regardant que les valeurs et + * pas les semantiques + * + * @param mat + * @return + */ + @Override + public boolean equalsValues(MatrixND mat) { + boolean result = true; + // les dimensions doivent-être identique + result = result && MatrixHelper.sameDimension(getDim(), mat.getDim()); + + // toutes les données doivent être identique + for (MatrixIterator i = mat.iterator(); result && i.next();) { + double v1 = i.getValue(); + double v2 = getValue(i.getCoordinates()); + result = v1 == v2; + if (log.isDebugEnabled()) { + log.debug("v1(" + v1 + ")==v2(" + v2 + ")=" + result); + } + // System.out.println("v1("+v1+")==v2("+v2+ ")="+result); + } + + return result; + } + + @Override + public String toString() { + StringBuffer result = new StringBuffer(); + result.append("dimensions = [\n"); + for (int i = 0; i < getDim().length; i++) { + result.append(getDim()[i] + ","); + } + result.append("\n]\nmatrice = [\n"); + for (MatrixIterator i = this.iterator(); i.next();) { + result.append(i.getValue() + ","); + } + result.append("\n]\n"); + return result.toString(); + } + + @Override + public List toList() { + List result = new ArrayList(); + // [3,2,5,4] + for (MatrixIterator i = iterator(); i.next();) { + int[] coord = i.getCoordinates(); + double value = i.getValue(); + List tmp = result; + for (int dim = 0; dim < coord.length - 1; dim++) { + while (tmp.size() <= coord[dim]) { + tmp.add(new ArrayList()); + } + tmp = (List) tmp.get(coord[dim]); + } + while (tmp.size() <= coord[coord.length - 1]) { + tmp.add(NumberUtils.DOUBLE_ZERO); + } + + tmp.set(coord[coord.length - 1], value); + } + + return result; + } + + @Override + public void fromList(List list) { + // on suppose que les listes sont bien formé, c-a-d qu'elles sont + // toutes de la meme dimension pour une dimension donnée. + ArrayIntList dim = new ArrayIntList(); + List tmp = list; + while (tmp.get(tmp.size() - 1) instanceof List) { + dim.add(tmp.size()); + tmp = (List) tmp.get(tmp.size() - 1); + } + dim.add(tmp.size()); + MatrixND mat = getFactory().create(dim.toArray()); + + for (MatrixIterator i = mat.iterator(); i.next();) { + int[] coord = i.getCoordinates(); + tmp = list; + for (int d = 0; d < coord.length - 1; d++) { + tmp = (List) tmp.get(coord[d]); + } + + Double value = (Double) tmp.get(coord[coord.length - 1]); + i.setValue(value); + } + paste(mat); + } + + public boolean isValidCoordinates(int[] dim) { + boolean result = getNbDim() == dim.length; + for (int i = 0; result && i < dim.length; i++) { + result = 0 <= dim[i] && dim[i] < getDim(i); + } + return result; + } + + public boolean isValidCoordinates(Object[] semantics) { + boolean result = getNbDim() == semantics.length; + for (int i = 0; result && i < semantics.length; i++) { + result = getSemantics(i).contains(semantics[i]); + } + return result; + } + + /* + * (non-Javadoc) + * + * @see org.codelutin.math.matrix.MatrixND#sumAll() + */ + @Override + public double sumAll() { + double result = 0; + for (MatrixIterator i = iterator(); i.next();) { + result += i.getValue(); + } + return result; + } + + @Override + public MatrixND sumOverDim(int dim) { + return sumOverDim(dim, getDim(dim)); + } + + @Override + public MatrixND sumOverDim(int dim, int step) { + if (step < 0) { + step = getDim(dim); + } else if (step <= 1) { + // il n'y a rien a faire, on fait une copie et on la retrourne + return getFactory().create(this); + } + + // le nombre d'element qu'il y aura dans la dim pour le resultat + int nbDim = getDim(dim) / step; + + List[] semantics = new List[getNbDim()]; + System.arraycopy(getSemantics(), 0, semantics, 0, getNbDim()); + semantics[dim] = semantics[dim].subList(0, nbDim); + + // creation du resultat + MatrixND result = getFactory().create(getName(), semantics, + getDimensionNames()); + + for (int i = 0; i < result.getDim(dim); i++) { + MatrixND temp = getSubMatrix(dim, i * step, step); + MatrixND sum = result.getSubMatrix(dim, i, 1); + for (int s = 0; s < temp.getDim(dim); s++) { + sum.add(temp.getSubMatrix(dim, s, 1)); + } + } + return result; + } + + @Override + public MatrixND sumOverDim(int dim, int start, int nb) { + // copie de l'ancienne semantique + List[] semantics = new List[getNbDim()]; + System.arraycopy(getSemantics(), 0, semantics, 0, getNbDim()); + semantics[dim] = new ArrayList<Object>(semantics[dim]); + + // creation d'un liste qui agrege les elements sommés + List<Object> newElem = new ArrayList<Object>(); + for (int i = 0; i < nb; i++) { + newElem.add(semantics[dim].remove(start)); + } + // on ajout la liste comme nouvel element de la semantique + semantics[dim].add(start, newElem); + + // creation du resultat + MatrixND result = getFactory().create(getName(), semantics, + getDimensionNames()); + + MatrixND sub1 = this.getSubMatrix(dim, 0, start); + MatrixND sub2 = this.getSubMatrix(dim, start, nb).sumOverDim(dim); + MatrixND sub3 = this.getSubMatrix(dim, start + nb, getDim(dim) + - (start + nb)); + + int[] origin = new int[getNbDim()]; + result.paste(origin, sub1); + origin[dim] = start; + result.paste(origin, sub2); + if (start + 1 < result.getDim(dim)) { + origin[dim] = start + 1; + result.paste(origin, sub3); + } + + return result; + } + + @Override + public MatrixND cut(int dim, int[] toCut) { + throw new UnsupportedOperationException("Méthode non implantée"); + } + + /** + * Modifie la matrice actuel en metant les valeurs de mat passé en parametre + */ + @Override + public MatrixND paste(MatrixND mat) { + return paste(new int[getNbDim()], mat); + } + + /** + * Modifie la matrice actuel en metant les valeurs de mat passé en parametre + * + * @param origin le point d'origine a partir duquel on colle la matrice + * @param mat une matrice avec le meme nombre de dimension, si la matrice + * que l'on colle est trop grande, les valeurs qui depasse ne + * sont pas prises en compte + */ + @Override + public MatrixND paste(int[] origin, MatrixND mat) { + // TODO, si les matrice mat et this on les memes dimensions + // et que origin est 0 + // on doit pouvoir optimiser en appeler une methode paste + // sur BasicMatrix qui l'appel sur le vector + if (mat != null) { + for (MatrixIterator mi = mat.iterator(); mi.next();) { + int[] coordinates = ArrayUtil.sum(origin, mi.getCoordinates()); + if (isValidCoordinates(coordinates)) { + setValue(coordinates, mi.getValue()); + } + } + } + return this; + } + + /** + * Modifie la matrice actuel en metant les valeurs de mat passé en parametre + * La copie se fait en fonction de la semantique, si un element dans une + * dimension n'est pas trouvé, alors il est passé + */ + @Override + public MatrixND pasteSemantics(MatrixND mat) { + if (mat != null) { + for (MatrixIterator mi = mat.iterator(); mi.next();) { + Object[] sems = mi.getSemanticsCoordinates(); + if (isValidCoordinates(sems)) { + setValue(sems, mi.getValue()); + } + } + } + return this; + } + + @Override + public MatrixND getSubMatrix(int dim, int start, int nb) { + if (dim < 0) { + dim = getNbDim() + dim; + } + if (start < 0) { + start = getDim(dim) + start; + } + if (nb <= 0) { + nb = getDim(dim) - start; + } + return new SubMatrix(this, dim, start, nb); + } + + @Override + public MatrixND getSubMatrix(int dim, Object start, int nb) { + int begin = MatrixHelper.indexOf(getSemantics(), dim, start); + return getSubMatrix(dim, begin, nb); + } + + /** + * Add to desambiguas some call with xpath engine, but do the same thing + * {@link #getSubMatrix(int, Object[])} + * + * @param dim + * @param elem + * @return + */ + public MatrixND getSubMatrixOnSemantic(int dim, Object... elem) { + MatrixND result = getSubMatrix(dim, elem); + return result; + } + + @Override + public MatrixND getSubMatrix(int dim, Object... elem) { + int[] ielem = new int[elem.length]; + for (int i = 0; i < ielem.length; i++) { + ielem[i] = MatrixHelper.indexOf(getSemantics(), dim, elem[i]); + } + return getSubMatrix(dim, ielem); + } + + @Override + public MatrixND getSubMatrix(int dim, int[] elem) { + return new SubMatrix(this, dim, elem); + } + + /** + * Modifie la matrice actuelle en lui ajoutant les valeurs de la matrice + * passé en parametre. La matrice passé en parametre doit avoir le meme + * nombre de dimension, et chacune de ses dimensions doit avoir un nombre + * d'element au moins egal a cette matrice. + */ + @Override + public MatrixND add(MatrixND m) { + // TODO si les dimensions sont exactment les memes, on doit pouvoir + // gagner du temps en travaillant directement au niveau du vector + for (MatrixIterator i = iterator(); i.next();) { + i.setValue(i.getValue() + m.getValue(i.getCoordinates())); + // TODO faire une variante de add avec les semantiques + } + return this; + } + + /** + * Modifie la matrice actuelle en lui soustrayant les valeurs de la matrice + * passé en parametre. La matrice passé en parametre doit avoir le meme + * nombre de dimension, et chacune de ses dimensions doit avoir un nombre + * d'element au moins egal a cette matrice. + */ + @Override + public MatrixND minus(MatrixND m) { + // TODO si les dimensions sont exactment les memes, on doit pouvoir + // gagner du temps en travaillant directement au niveau du vector + for (MatrixIterator i = iterator(); i.next();) { + i.setValue(i.getValue() - m.getValue(i.getSemanticsCoordinates())); + } + return this; + } + + @Override + public MatrixND transpose() { + if (getNbDim() > 2) { + throw new MatrixException( + "La transpose ne peut-être fait que sur une matrice ayant 2 dimensions ou moins"); + } + if (getNbDim() == 1) { + MatrixND result = getFactory() + .create( + getName(), + new List[] { Collections.nCopies(1, null), + getSemantics(0) }, + new String[] { "Dimension 0", getDimensionName(0) }); + for (int x = 0; x < getDim(0); x++) { + result.setValue(0, x, getValue(x)); + } + return result; + } else { + MatrixND result = getFactory().create(getName(), + new List[] { getSemantics(1), getSemantics(0) }, + new String[] { getDimensionName(1), getDimensionName(0) }); + for (int x = 0; x < getDim(0); x++) { + for (int y = 0; y < getDim(1); y++) { + result.setValue(y, x, getValue(x, y)); + } + } + return result; + } + } + + @Override + public MatrixND reduce() { + return reduce(1); + } + + @Override + public MatrixND reduceDims(int... dims) { + Arrays.sort(dims); + // tableau permettant de faire la correspondance entre les dimensions + // de la matrice actuelle et les dimentsions de la nouvelle matrice + // l'element i du tableau qui correcpond à la dimensions i de la + // nouvelle matrice contient la dimension equivalente dans + // la matrice actuelle + int[] correspondance = new int[getNbDim()]; + // les nouvelles semantiques + List sem = new ArrayList(); + // les nouveaux noms de dimensions + List dimName = new ArrayList(); + // il faut au moins une dimension pour la matrice + int minNbDim = 1; + for (int j = getNbDim() - 1; j >= 0; j--) { + // si la dimension à plus d'un élément ou qu'il n'est pas dans dims + // on garde la dimension + if (getDim(j) > 1 || Arrays.binarySearch(dims, j) < 0 + || j < minNbDim) { + // on ne conserve que les dimensions supérieure à 1 + correspondance[sem.size()] = j; + sem.add(getSemantics(j)); + dimName.add(getDimensionName(j)); + minNbDim--; + } + } + MatrixND result = reduce(dimName, sem, correspondance); + return result; + } + + @Override + public MatrixND reduce(int minNbDim) { + // tableau permettant de faire la correspondance entre les dimensions + // de la matrice actuelle et les dimentsions de la nouvelle matrice + // l'element i du tableau qui correcpond à la dimensions i de la + // nouvelle matrice contient la dimension equivalente dans + // la matrice actuelle + int[] correspondance = new int[getNbDim()]; + // les nouvelles semantiques + List sem = new ArrayList(); + // les nouveaux noms de dimensions + List dimName = new ArrayList(); + for (int j = getNbDim() - 1; j >= 0; j--) { + // si la dimension à plus d'un élément ou si on a pas assez de + // dimension pour avoir le minimum demandé on prend la dimension + if (getDim(j) > 1 || j < minNbDim) { + // on ne conserve que les dimensions supérieure à 1 + correspondance[sem.size()] = j; + sem.add(getSemantics(j)); + dimName.add(getDimensionName(j)); + // on vient de prendre une dimension il nous en faut une de + // moins + minNbDim--; + } + } + + MatrixND result = reduce(dimName, sem, correspondance); + return result; + } + + /** + * Create new matrice from the current matrix. + * + * @param dimName dimension name for new matrix + * @param sem semantic for new matrix + * @param correspondance array to do the link between current matrix and + * returned matrix + * @return new matrix + */ + protected MatrixND reduce(List dimName, List sem, int[] correspondance) { + // on converti les listes en tableau en inversant l'ordre car on + // a fait un parcours en sens inverse + int nbDim = sem.size(); + List[] newSemantics = new List[nbDim]; + String[] newDimNames = new String[nbDim]; + int[] tmpcorrespondance = new int[nbDim]; + for (int i = 0; i < nbDim; i++) { + newSemantics[i] = (List) sem.get(nbDim - 1 - i); + newDimNames[i] = (String) dimName.get(nbDim - 1 - i); + tmpcorrespondance[i] = correspondance[nbDim - 1 - i]; + } + correspondance = tmpcorrespondance; + + MatrixND result = getFactory().create(getName(), newSemantics, + newDimNames); + + // on reprend les valeurs + int[] newCoordinates = new int[result.getNbDim()]; + for (MatrixIterator mi = iterator(); mi.next();) { + int[] oldCoordinates = mi.getCoordinates(); + for (int i = 0; i < newCoordinates.length; i++) { + newCoordinates[i] = oldCoordinates[correspondance[i]]; + } + result.setValue(newCoordinates, mi.getValue()); + } + return result; + } + + @Override + public MatrixND mult(MatrixND m) throws MatrixException { + if (this.getNbDim() > 2 || m.getNbDim() > 2) { + throw new MatrixException( + "La multiplication de matrice n'est pas applicable aux matrices de plus de 2 dimensions"); + } + if (!((this.getDim(1) == m.getDim(0)))) { + throw new MatrixException( + "Le nombre de colonnes de la matrice m1 doit etre egal au nombre de lignes de la matrice m2"); + } + + MatrixND result = getFactory().create( + new int[] { this.getDim(0), m.getDim(1) }); + double d; + for (int x = 0; x < this.getDim(0); x++) { + for (int y = 0; y < m.getDim(1); y++) { + d = this.getValue(x, 0) * m.getValue(0, y); + for (int k = 1; k < this.getDim(1); k++) { + d += this.getValue(x, k) * m.getValue(k, y); + } + result.setValue(x, y, d); + } + } + return result; + } + + @Override + public MatrixND mults(final double d) { + map(new MapFunction() { + public double apply(double val) { + return val * d; + } + }); + return this; + } + + @Override + public MatrixND divs(final double d) { + map(new MapFunction() { + public double apply(double val) { + return val / d; + } + }); + return this; + } + + @Override + public MatrixND adds(final double d) { + map(new MapFunction() { + public double apply(double val) { + return val + d; + } + }); + return this; + } + + @Override + public MatrixND minuss(final double d) { + map(new MapFunction() { + public double apply(double val) { + return val - d; + } + }); + return this; + } + + /** + * Determine si la matrice supporte l'import et l'export CSV + * + * @return support du CSV + */ + @Override + public boolean isSupportedCSV() { + return getNbDim() <= 2; + } + + /** + * Import depuis un reader au format CSV des données dans la matrice + * + * @param reader le reader à importer + * @param origin le point à partir duquel il faut faire l'importation + * int[]{x,y} + */ + @Override + public void importCSV(Reader reader, int[] origin) throws IOException { + int rowsCount = 0; + List<Double> row = new ArrayList<Double>(); + StringBuffer number = new StringBuffer(20); + boolean stop = false; + + for (int c = reader.read(); !stop; c = reader.read()) { + if (c == -1) { + stop = true; + } + if (c == ' ') { + // skip space + } else if (c == CSV_SEPARATOR) { + if (NUMBER.matcher(number.toString()).matches()) { + Double val = Double.valueOf(number.toString()); + row.add(val); + } + number.setLength(0); + } else if (c == -1 || c == '\n' || c == '\r') { + // is line return or equivalent char because space is already + // skiped + // or end of stream + + // at end of line, we must see if the leave number + if (NUMBER.matcher(number.toString()).matches()) { + Double val = Double.valueOf(number.toString()); + row.add(val); + } + number.setLength(0); + + if (!row.isEmpty()) { + if (getDim().length == 1) { + int columnNumber = origin[0]; + for (Double value : row) { + if (columnNumber < getDim(0)) { + setValue(new int[] { columnNumber }, value); + columnNumber++; + } + } + } else if (getDim().length == 2) { + MatrixND matrix = getFactory().create( + new int[] { 1, row.size() }); + int columnNumber = 0; + for (Double value : row) { + matrix.setValue(new int[] { 0, columnNumber }, + value); + columnNumber++; + } + paste(new int[] { origin[0] + rowsCount, origin[1] }, + matrix); + rowsCount++; + row.clear(); + } else { + throw new MatrixException( + "Can't import matrix with more than 2 dimensions."); + } + } + } else { + number.append((char) c); + } + } + + // cette implatation avec StreamTokenizer ne fonctionne pas + // car il ne sait pas reconnaitre tous les nombres: 5.0E-7 + // int rowsCount = 0; + // StreamTokenizer tokenizer; + // List<Double> row = new ArrayList<Double>(); + // boolean stop = false; + // + // tokenizer = new StreamTokenizer(reader); + // tokenizer.eolIsSignificant(true); + // + // while(!stop) { + // tokenizer.nextToken(); + // + // switch (tokenizer.ttype) { + // case StreamTokenizer.TT_EOF: + // stop = true; // no break we do next case too + // case StreamTokenizer.TT_EOL: + // if(!row.isEmpty()) { + // MatrixND matrix = getFactory().create(new int[]{1, row.size()}); + // int columnNumber = 0; + // for (Double value : row) { + // matrix.setValue(new int[]{0, columnNumber}, value); + // columnNumber++; + // } + // paste(new int[]{origin[0] + rowsCount, origin[1]}, matrix); + // rowsCount ++; + // row.clear(); + // } + // break; + // case StreamTokenizer.TT_NUMBER: + // System.out.println("+++++++++ " + tokenizer.nval); + // row.add(tokenizer.nval); + // break; + // case StreamTokenizer.TT_WORD: + // System.out.println("--------- " + tokenizer.nval); + // break; + // default: + // break; + // } + // } + } + + /** + * Export dans un writer au format CSV de la matrice + * + * @param writer le writer ou copier la matrice + * @param withSemantics export ou pas des semantiques de la matrice dans le + * writer + */ + @Override + public void exportCSV(Writer writer, boolean withSemantics) + throws IOException { + int dimsCount = getNbDim(); + int rowsCount = dimsCount == 1 ? 1 : getDim(0); + int columnsCount = dimsCount == 1 ? getDim(0) : getDim(1); + int[] coordinates; + + if (!isSupportedCSV()) { + throw new UnsupportedOperationException(); + } + + /* Création de l'entete */ + if (withSemantics) { + /* Recuperation de la liste sur la bonne dimenssion */ + List listSemantics = getSemantics(dimsCount - 1); + /* Ajout d'un décalage de l'entete pour la dimenssion 2 */ + writer.append(dimsCount == 2 ? " " + CSV_SEPARATOR : ""); + for (Object semantic : listSemantics) { + writer.append("\"" + semantic + "\"" + CSV_SEPARATOR); + } + writer.append("\n"); + } + + for (int rowNb = 0; rowNb < rowsCount; rowNb++) { + /* Ajout de la semantic devant la ligne pour la dimenssion 2 */ + if (withSemantics && dimsCount == 2) { + Object semantic = getSemantics(0).get(rowNb); + writer.append("\"" + semantic + "\"" + CSV_SEPARATOR); + } + + for (int columnNb = 0; columnNb < columnsCount; columnNb++) { + /* Calcul des coordonnees */ + coordinates = dimsCount == 1 ? new int[] { columnNb } + : new int[] { rowNb, columnNb }; + writer.append(getValue(coordinates) + "" + CSV_SEPARATOR); + } + writer.append("\n"); + } + } + +} // AbstractMatrixND Deleted: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/BasicMatrix.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/BasicMatrix.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/BasicMatrix.java 2009-05-16 19:21:04 UTC (rev 144) @@ -1,334 +0,0 @@ -/* *##% 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.Arrays; -import java.util.NoSuchElementException; - -import org.codelutin.i18n.I18n; - -/** - * Objet matrice qui ne permet que le stockage de double dans un matrice à - * autant de dimension que l'on souhaite. - * - * Created: 27 oct. 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - * @version $Revision$ - * - * Mise a jour: $Date$ - * par : $Author$ - */ -public class BasicMatrix { // BasicMatrix - - /** La factory */ - protected MatrixFactory factory = null; - /** Les dimensions de la matrice */ - protected int[] dimensions = null; - /** La matrice en représentation linéaire */ - protected Vector data = null; - - /** - * tableau de facteur permettant de convertir les coordonnées dans la - * matrice en un indice dans la représentation linéaire de la matrice - */ - protected int[] linearFactor = null; - - /** - * Crée une nouvelle matrice ayant les dimensions demandées - */ - public BasicMatrix(MatrixFactory factory, int[] dimensions) { - this.factory = factory; - checkDim(dimensions); - - // copie des dimensions pour que personne à l'extérieur de l'objet - // ne puisse les modifiers par la suite - this.dimensions = new int[dimensions.length]; - System.arraycopy(dimensions, 0, this.dimensions, 0, dimensions.length); - - // calcul du linearFactor - linearFactor = new int[dimensions.length]; - linearFactor[linearFactor.length - 1] = 1; - for (int i = linearFactor.length - 2; i >= 0; i--) { - linearFactor[i] = linearFactor[i + 1] * dimensions[i + 1]; - } - - // creation de la matrice lineaire - data = factory.createVector(linearFactor[0] * dimensions[0]); - } - - /** - * Retourne la valeur la plus courrement rencontrer dans la matrice. si - * plusieurs valeurs ont le même nombre d'occurence la plus petite valeur - * est retourné. - * - * @return la valeur la plus nombreuse dans la matrice, ou la plus petite si - * plusieurs valeur se retourve le même nombre de fois - */ - public double getMaxOccurence() { - return data.getMaxOccurence(); - } - - /** - * Retourne le nombre de dimension de la matrice - * - * @return le nombre de dimension de la matrice; - */ - public int getNbDim() { - return dimensions.length; - } - - /** - * Retourne la taille d'une dimension - * - * @param dim la dimension dont on souhaite la taille - * @return la taille d'une dimension - */ - public int getDim(int dim) { - checkDim(dim); - return dimensions[dim]; - } - - /** - * Retourne un tableau representant les dimensions de la matrice. Le tableau - * retourné n'est pas une copie, il ne faut donc pas le modifier - * - * @return le tableau des dimensions. - */ - public int[] getDim() { - return dimensions; - } - - /** - * Retourne un element de la matrice - * - * @param pos la position de l'element à retourner - */ - public double getValue(int[] pos) { - int indice = coordonatesToLinear(pos); - return data.getValue(indice); - } - - /** - * Modifie un élement de la matrice - * - * @param pos la position de l'element à modifier - * @param value la nouvelle valeur à mettre dans la matrice - */ - public void setValue(int[] pos, double value) { - int indice = coordonatesToLinear(pos); - data.setValue(indice, value); - } - - /** - * Retourne un objet Inc pret a etre utilisé pour boucler sur tous les - * element de la matrice. - * - * @return un objet Inc pret à être utilisé - */ - public BasicMatrixIterator iterator() { - return new BasicMatrixIteratorImpl(this); - } - - /** - * Permet de faire un traitement sur chaque valeur de la matrice - * - * @param f la fonction a appliquer à chaque élement de la matrice - */ - public void map(MapFunction f) { - if (data.isImplementedMap()) { - data.map(f); - } else { - for (int i = 0; i < data.size(); i++) { - double result = f.apply(data.getValue(i)); - data.setValue(i, result); - } - } - } - - /** - * Permet de convertir les coordonnées d'un élément en un indice dans la - * représentation linéraire de la matrice. - * - * @param coordonates les coordonnées à lineariser - * @return un indice réprésentant les coordonnées de façon linéaire - */ - protected int coordonatesToLinear(int[] coordonates) { - checkPos(coordonates); - - int result = 0; - for (int i = 0; i < linearFactor.length; i++) { - result += coordonates[i] * linearFactor[i]; - } - return result; - } - - /** - * Convertie une coordonnée lineaire en coordonnées spaciales - * - * @param pos la coordonnée linéaire - * @return les coordonnées spaciales de l'élément - */ - protected int[] linearToCoordinates(int pos) { - int[] result = new int[linearFactor.length]; - - for (int i = 0; i < result.length; i++) { - result[i] = pos / linearFactor[i]; - pos -= result[i] * linearFactor[i]; - } - return result; - } - - /** - * Permet de vérifier que les dimensions de la nouvelle matrice sont - * corrects - * - * @param dim les dimensions de la nouvelle matrice - * @throws IllegalArgumentException si une dimension n'est pas valide - */ - protected void checkDim(int[] dim) { - for (int i = 0; i < dim.length; i++) { - if (dim[i] <= 0) { - throw new IllegalArgumentException(I18n._( - "lutinmatrix.invalid.size", Integer.valueOf(i), - Integer.valueOf(dim[i]))); - } - } - } - - /** - * Permet de vérifier qu'une dimension demandé existe bien dans la matrice - * - * @param dim la position de la dimension que l'on souhaite - * @throws IndexOutOfBoundsException si la dimension demandée n'existe pas - */ - protected void checkDim(int dim) { - if (dim < 0 || dim >= getNbDim()) { - throw new IndexOutOfBoundsException(I18n._( - "lutinmatrix.invalid.size", dim, getNbDim())); - } - } - - /** - * Verifie que les coordonnées demandé appartiennent bien à la matrice - * - * @param pos les coordonnées souhaitées dans la matrice - * @throws NoSuchElementException si les coordonnées ne correspondent pas à - * un élement de la matrice - */ - protected void checkPos(int[] pos) { - int[] dim = getDim(); - boolean result = dim.length == pos.length; - for (int i = 0; result && i < dim.length; i++) { - result = (0 <= pos[i]) && (pos[i] < dim[i]); - } - if (!result) { - throw new NoSuchElementException(I18n._( - "lutinmatrix.invalid.element", Arrays.toString(pos), Arrays - .toString(dim))); - } - } - - public String toString() { - StringBuffer result = new StringBuffer(); - if (getNbDim() == 1) { - result.append("matrix1D ["); - for (int i = 0; i < data.size(); i++) { - result.append(data.getValue(i) + ","); - } - result.append("]"); - } else if (getNbDim() == 2) { - DimensionHelper dimHelper = new DimensionHelper(); - result.append("matrix2D ["); - for (int y = 0; y < getDim(1); y++) { - result.append("\n"); - for (int x = 0; x < getDim(0); x++) { - result.append(getValue(dimHelper.get(x, y)) + ","); - } - } - result.append("]"); - } else { - result.append("dimensions = [\n"); - for (int i = 0; i < dimensions.length; i++) { - result.append(dimensions[i] + ","); - } - result.append("\n]\nmatrice = [\n"); - for (int i = 0; i < data.size(); i++) { - result.append(data.getValue(i) + ","); - } - result.append("\n]\nlinearFactor = [\n"); - for (int i = 0; i < linearFactor.length; i++) { - result.append(linearFactor[i] + ","); - } - result.append("\n]\n"); - } - return result.toString(); - } - - public boolean equals(Object o) { - if (o instanceof BasicMatrix) { - BasicMatrix other = (BasicMatrix) o; - return this == o - || (Arrays.equals(this.dimensions, other.dimensions) && this.data - .equals(other.data)); - } - return false; - } - - protected class BasicMatrixIteratorImpl implements BasicMatrixIterator { // MatrixIteratorImpl - - protected BasicMatrix matrix = null; - protected int pos = -1; - - /** - * @param matrix la matrice sur lequel l'iterator doit travailler - */ - public BasicMatrixIteratorImpl(BasicMatrix matrix) { - this.matrix = matrix; - pos = -1; - } - - public boolean hasNext() { - return pos + 1 < matrix.data.size(); - } - - public boolean next() { - if (hasNext()) { - pos++; - return true; - } else { - return false; - } - } - - public double getValue() { - return matrix.data.getValue(pos); - } - - public void setValue(double value) { - matrix.data.setValue(pos, value); - } - - public int[] getCoordinates() { - return matrix.linearToCoordinates(pos); - } - - } // BasicMatrixIteratorImpl - -} // BasicMatrix - Copied: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/BasicMatrix.java (from rev 143, nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/BasicMatrix.java) =================================================================== --- nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/BasicMatrix.java (rev 0) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/BasicMatrix.java 2009-05-16 19:21:04 UTC (rev 144) @@ -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.nuiton.math.matrix; + +import java.util.Arrays; +import java.util.NoSuchElementException; + +import org.nuiton.i18n.I18n; + +/** + * Objet matrice qui ne permet que le stockage de double dans un matrice à + * autant de dimension que l'on souhaite. + * + * Created: 27 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public class BasicMatrix { // BasicMatrix + + /** La factory */ + protected MatrixFactory factory = null; + /** Les dimensions de la matrice */ + protected int[] dimensions = null; + /** La matrice en représentation linéaire */ + protected Vector data = null; + + /** + * tableau de facteur permettant de convertir les coordonnées dans la + * matrice en un indice dans la représentation linéaire de la matrice + */ + protected int[] linearFactor = null; + + /** + * Crée une nouvelle matrice ayant les dimensions demandées + */ + public BasicMatrix(MatrixFactory factory, int[] dimensions) { + this.factory = factory; + checkDim(dimensions); + + // copie des dimensions pour que personne à l'extérieur de l'objet + // ne puisse les modifiers par la suite + this.dimensions = new int[dimensions.length]; + System.arraycopy(dimensions, 0, this.dimensions, 0, dimensions.length); + + // calcul du linearFactor + linearFactor = new int[dimensions.length]; + linearFactor[linearFactor.length - 1] = 1; + for (int i = linearFactor.length - 2; i >= 0; i--) { + linearFactor[i] = linearFactor[i + 1] * dimensions[i + 1]; + } + + // creation de la matrice lineaire + data = factory.createVector(linearFactor[0] * dimensions[0]); + } + + /** + * Retourne la valeur la plus courrement rencontrer dans la matrice. si + * plusieurs valeurs ont le même nombre d'occurence la plus petite valeur + * est retourné. + * + * @return la valeur la plus nombreuse dans la matrice, ou la plus petite si + * plusieurs valeur se retourve le même nombre de fois + */ + public double getMaxOccurence() { + return data.getMaxOccurence(); + } + + /** + * Retourne le nombre de dimension de la matrice + * + * @return le nombre de dimension de la matrice; + */ + public int getNbDim() { + return dimensions.length; + } + + /** + * Retourne la taille d'une dimension + * + * @param dim la dimension dont on souhaite la taille + * @return la taille d'une dimension + */ + public int getDim(int dim) { + checkDim(dim); + return dimensions[dim]; + } + + /** + * Retourne un tableau representant les dimensions de la matrice. Le tableau + * retourné n'est pas une copie, il ne faut donc pas le modifier + * + * @return le tableau des dimensions. + */ + public int[] getDim() { + return dimensions; + } + + /** + * Retourne un element de la matrice + * + * @param pos la position de l'element à retourner + * @return un element de la matrice + */ + public double getValue(int[] pos) { + int indice = coordonatesToLinear(pos); + return data.getValue(indice); + } + + /** + * Modifie un élement de la matrice + * + * @param pos la position de l'element à modifier + * @param value la nouvelle valeur à mettre dans la matrice + */ + public void setValue(int[] pos, double value) { + int indice = coordonatesToLinear(pos); + data.setValue(indice, value); + } + + /** + * Retourne un objet Inc pret a etre utilisé pour boucler sur tous les + * element de la matrice. + * + * @return un objet Inc pret à être utilisé + */ + public BasicMatrixIterator iterator() { + return new BasicMatrixIteratorImpl(this); + } + + /** + * Permet de faire un traitement sur chaque valeur de la matrice + * + * @param f la fonction a appliquer à chaque élement de la matrice + */ + public void map(MapFunction f) { + if (data.isImplementedMap()) { + data.map(f); + } else { + for (int i = 0; i < data.size(); i++) { + double result = f.apply(data.getValue(i)); + data.setValue(i, result); + } + } + } + + /** + * Permet de convertir les coordonnées d'un élément en un indice dans la + * représentation linéraire de la matrice. + * + * @param coordonates les coordonnées à lineariser + * @return un indice réprésentant les coordonnées de façon linéaire + */ + protected int coordonatesToLinear(int[] coordonates) { + checkPos(coordonates); + + int result = 0; + for (int i = 0; i < linearFactor.length; i++) { + result += coordonates[i] * linearFactor[i]; + } + return result; + } + + /** + * Convertie une coordonnée lineaire en coordonnées spaciales + * + * @param pos la coordonnée linéaire + * @return les coordonnées spaciales de l'élément + */ + protected int[] linearToCoordinates(int pos) { + int[] result = new int[linearFactor.length]; + + for (int i = 0; i < result.length; i++) { + result[i] = pos / linearFactor[i]; + pos -= result[i] * linearFactor[i]; + } + return result; + } + + /** + * Permet de vérifier que les dimensions de la nouvelle matrice sont + * corrects + * + * @param dim les dimensions de la nouvelle matrice + * @throws IllegalArgumentException si une dimension n'est pas valide + */ + protected void checkDim(int[] dim) { + for (int i = 0; i < dim.length; i++) { + if (dim[i] <= 0) { + throw new IllegalArgumentException(I18n._( + "lutinmatrix.invalid.size", Integer.valueOf(i), + Integer.valueOf(dim[i]))); + } + } + } + + /** + * Permet de vérifier qu'une dimension demandé existe bien dans la matrice + * + * @param dim la position de la dimension que l'on souhaite + * @throws IndexOutOfBoundsException si la dimension demandée n'existe pas + */ + protected void checkDim(int dim) { + if (dim < 0 || dim >= getNbDim()) { + throw new IndexOutOfBoundsException(I18n._( + "lutinmatrix.invalid.size", dim, getNbDim())); + } + } + + /** + * Verifie que les coordonnées demandé appartiennent bien à la matrice + * + * @param pos les coordonnées souhaitées dans la matrice + * @throws NoSuchElementException si les coordonnées ne correspondent pas à + * un élement de la matrice + */ + protected void checkPos(int[] pos) { + int[] dim = getDim(); + boolean result = dim.length == pos.length; + for (int i = 0; result && i < dim.length; i++) { + result = (0 <= pos[i]) && (pos[i] < dim[i]); + } + if (!result) { + throw new NoSuchElementException(I18n._( + "lutinmatrix.invalid.element", Arrays.toString(pos), Arrays + .toString(dim))); + } + } + + @Override + public String toString() { + StringBuffer result = new StringBuffer(); + if (getNbDim() == 1) { + result.append("matrix1D ["); + for (int i = 0; i < data.size(); i++) { + result.append(data.getValue(i) + ","); + } + result.append("]"); + } else if (getNbDim() == 2) { + DimensionHelper dimHelper = new DimensionHelper(); + result.append("matrix2D ["); + for (int y = 0; y < getDim(1); y++) { + result.append("\n"); + for (int x = 0; x < getDim(0); x++) { + result.append(getValue(dimHelper.get(x, y)) + ","); + } + } + result.append("]"); + } else { + result.append("dimensions = [\n"); + for (int i = 0; i < dimensions.length; i++) { + result.append(dimensions[i] + ","); + } + result.append("\n]\nmatrice = [\n"); + for (int i = 0; i < data.size(); i++) { + result.append(data.getValue(i) + ","); + } + result.append("\n]\nlinearFactor = [\n"); + for (int i = 0; i < linearFactor.length; i++) { + result.append(linearFactor[i] + ","); + } + result.append("\n]\n"); + } + return result.toString(); + } + + @Override + public boolean equals(Object o) { + if (o instanceof BasicMatrix) { + BasicMatrix other = (BasicMatrix) o; + return this == o + || (Arrays.equals(this.dimensions, other.dimensions) && this.data + .equals(other.data)); + } + return false; + } + + protected class BasicMatrixIteratorImpl implements BasicMatrixIterator { // MatrixIteratorImpl + + protected BasicMatrix matrix = null; + protected int pos = -1; + + /** + * @param matrix la matrice sur lequel l'iterator doit travailler + */ + public BasicMatrixIteratorImpl(BasicMatrix matrix) { + this.matrix = matrix; + pos = -1; + } + + @Override + public boolean hasNext() { + return pos + 1 < matrix.data.size(); + } + + @Override + public boolean next() { + if (hasNext()) { + pos++; + return true; + } else { + return false; + } + } + + @Override + public double getValue() { + return matrix.data.getValue(pos); + } + + @Override + public void setValue(double value) { + matrix.data.setValue(pos, value); + } + + @Override + public int[] getCoordinates() { + return matrix.linearToCoordinates(pos); + } + + } // BasicMatrixIteratorImpl + +} // BasicMatrix + Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/BasicMatrixIterator.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/BasicMatrixIterator.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/BasicMatrixIterator.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; /** * BasicMatrixIterator. Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/DimensionHelper.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/DimensionHelper.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/DimensionHelper.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; /** * Classe permettant de diminuer au maximum l'allocation de tableau de int pour Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/DoubleBigVector.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/DoubleBigVector.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/DoubleBigVector.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; import java.util.Arrays; Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/DoubleVector.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/DoubleVector.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/DoubleVector.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; import java.util.Arrays; Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/FloatBigVector.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/FloatBigVector.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/FloatBigVector.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; import java.util.Arrays; Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/FloatVector.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/FloatVector.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/FloatVector.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; import java.util.Arrays; Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MapFunction.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/MapFunction.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MapFunction.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; /** * Permet de faire un traitement sur des valeurs et d'en retourner Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixEncoder.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixEncoder.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixEncoder.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; import java.io.IOException; import java.io.Writer; Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixException.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixException.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixException.java 2009-05-16 19:21:04 UTC (rev 144) @@ -26,7 +26,7 @@ * Mise a jour: $Date$ * par : $Author$ */ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; public class MatrixException extends RuntimeException { Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixFactory.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixFactory.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixFactory.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; import java.lang.reflect.Constructor; import java.util.List; Deleted: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixHelper.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixHelper.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixHelper.java 2009-05-16 19:21:04 UTC (rev 144) @@ -1,326 +0,0 @@ -/* *##% 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.StreamTokenizer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Stack; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Contains usefull methods to get information on matrix. - * - * Created: 28 oct. 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - * @version $Revision$ - * - * Mise a jour: $Date$ - * par : $Author$ - */ -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. - * - * @param mat - * @return - */ - public static MatrixND convertToId(MatrixND mat) { - int size = mat.getDim(0); - if (size > mat.getDim(1)) { - size = mat.getDim(1); - } - - fill(mat, 0); - - for (int i = 0; i < size; i++) { - mat.setValue(i, i, 1); - } - return mat; - } - - /** - * Permet de relire une chaine du type [[[1, 2], [3, 4]],[[3, 5], [1, 4]]] - * <p> - * Remarque: une premiere implantantion avait ete faite en utilisant - * {@link StreamTokenizer} mais en fait il y a un bug dedans, il ne sait pas - * parser les chiffres avec un exposant: 5.0E-7 par exemple est lu comme 5.0 - * :( - * <p> - * Remarque: une autre implantation de remplacement a ete faite en utilisant - * le {@link org.codelutin.util.StringUtil#split(String, String)} mais elle - * etait moins performante (x2) - * - * @param s la chaine representant les listes de liste - * @return une liste de liste ... de Double - */ - public static List convertStringToList(String s) { - List result = null; - Stack<List> stack = new Stack<List>(); - StringBuffer number = new StringBuffer(20); // initial to 20 char - - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (c == ' ') { - // skip space - } - if (c == '[') { - stack.push(new ArrayList()); - } else if (c == ',') { - if (number.length() != 0) { - // on a une ',' on doit donc avoir un nombre dans number - // a moins que ce ne soit une ',' entre deux listes - Double value = Double.valueOf(number.toString()); - stack.peek().add(value); - } - number.setLength(0); - } else if (c == ']') { - // fin d'une liste, il doit rester un nombre dans number - // a mois que la liste etait vide - if (number.length() != 0) { - Double value = Double.valueOf(number.toString()); - stack.peek().add(value); - number.setLength(0); - } - - List current = stack.pop(); - if (stack.empty()) { - result = current; - } else { - stack.peek().add(current); - } - } else { - // pas un '[' ou ']', pas une ',' devrait etre - // un bout du nombre, si c un espace qui traine n'importe ou - // c pas grace car Double.valueOf gere les espaces - number.append(c); - } - } - return result; - } - - /** - * permet de donner une représentation String d'un tableau de coordonnées - * - * @param coordinates les coordonnées - * @return la chaine demandée de la forme 1,3,34,23 - */ - public static String coordinatesToString(int[] coordinates) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < coordinates.length; i++) { - sb.append(coordinates[i]); - if (i + 1 < coordinates.length) { - sb.append(','); - } - } - return sb.toString(); - } - - /** - * permet de donner une représentation String d'un tableau de coordonnées - * - * @param coordinates les coordonnées - * @return la chaine demandée de la forme "Ob1","Ob2,"Ob3", ... la chaine - * prise pour l'objet est celle retournée par la méthode toString de - * l'objet - */ - public static String coordinatesToString(Object[] coordinates) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < coordinates.length; i++) { - sb.append(coordinates[i]); - if (i + 1 < coordinates.length) { - sb.append(','); - } - } - return sb.toString(); - } - - /** - * Permet de savoir si deux dimension sont identiques. - */ - public static boolean sameDimension(int[] dim1, int[] dim2) { - return Arrays.equals(dim1, dim2); - } - - /** - * Permet de convertir des coordonnées définies par des entiers en coordonnées - * semantique par des objets - * - * @param semantics la semantique à utilisé pour la conversion - * @param coordinates les coordonnées à convertir - * @return un tableau donnant les coordonnées sous forme semantique s'il n'y - * a pas de semantique (liste pleine de null) alors un objet Integer - * est créer pour représenter la semantique de la dimension. - */ - public static Object[] dimensionToSemantics(List[] semantics, - int[] coordinates) { - Object[] result = new Object[coordinates.length]; - for (int i = 0; i < result.length; i++) { - result[i] = semantics[i].get(coordinates[i]); - if (result[i] == null) { - result[i] = Integer.valueOf(coordinates[i]); - } - } - return result; - } - - /** - * Permet de convertir des coordonnées sémantiques en coordonnées défini par - * des entiers. Cette fonction est l'inverse de - * {@link #dimensionToSemantics}. - * - * @param semantics la semantique à utiliser pour la conversion - * @param coordinates les coordonnées sémantique - * @return les coordonnées en entier. Si la sémantique est représentéé par un - * Integer alors la valeur de l'integer est utilisé pour la - * conversion. - */ - public static int[] semanticsToDimension(List[] semantics, - Object[] coordinates) { - int[] result = new int[coordinates.length]; - for (int i = 0; i < coordinates.length; i++) { - if (coordinates[i] == null) { - result[i] = -1; - } else { - result[i] = indexOf(semantics, i, coordinates[i]); - } - } - return result; - } - - /** - * Permet de retrouver la position d'un objet dans une liste - * - * @param semantics la semantique à utilisé pour la recherche - * @param dim la dimension dans lequel il faut faire la recherche - * @param o l'objet à rechercher - * @return la position de l'objet dans la dimension demandée - * - * @throws NoSuchElementException If element doesn't exists - */ - public static int indexOf(List[] semantics, int dim, Object o) - throws NoSuchElementException { - if (o instanceof Integer) { - return ((Integer) o).intValue(); - } - int result = -1; - if ((0 <= dim) && (dim < semantics.length)) { - result = semantics[dim].indexOf(o); - } - if (result == -1) { - throw new NoSuchElementException( - "L'objet passé en argument n'a pas été retrouvé ou la dimension donnée ne convient pas:" - + o + " in " + semantics[dim]); - } - return result; - } - - /** - * Permet de remplir toute la matrice avec la même donnée - * - * @param mat la matrice à remplir - * @param value la valeur de remplissage - * @return la matrice passé en paramêtre - */ - public static MatrixND fill(MatrixND mat, final double value) { - mat.map(new MapFunction() { - public double apply(double v) { - return value; - } - }); - return mat; - } - - /** - * Retourne la valeur la plus courrement rencontrer dans un tableau. si - * plusieurs valeurs ont le même nombre d'occurence la plus petite valeur - * est retournée. - * - * @param tab le tableau de valeur - * @return la valeur la plus nombreuse dans le tableau - */ - public static double maxOccurence(double[] tab) { - double[] tmp = new double[tab.length]; - System.arraycopy(tab, 0, tmp, 0, tab.length); - return maxOccurence1(tmp); - } - - public static double maxOccurence(float[] tab) { - double[] tmp = new double[tab.length]; - for (int i = 0; i < tab.length; i++) { - tmp[i] = tab[i]; - } - return maxOccurence1(tmp); - } - - /** - * le tableau en entre est trie durant l'execution de la methode, il est - * donc modifié - */ - protected static double maxOccurence1(double[] tmp) { - if (tmp.length == 0) { - throw new IllegalArgumentException("Array must be not empty"); - } - // double [] tmp = new double[tab.length]; - // System.arraycopy(tab, 0, tmp, 0, tab.length); - Arrays.sort(tmp); - - // le nombre de fois que l'on a rencontrer la valeur la plus nombreuse - int max = 1; - // le nombre de fois que l'on a rencontrer la valeur courante - int count = 1; - // la valeur la plus rencontrer - double result = tmp[0]; - // la valeur que l'on vient de traiter précédement - double old = tmp[0]; - // la valeur courante lu dans le tableaux - double current = tmp[0]; - // tant que l'on peut encore trouve un element plus nombreux dans le - // tableau on le parcours - for (int i = 1; max < tmp.length - i + count && i < tmp.length; i++) { - current = tmp[i]; - - if (current == old) { - count++; - } else { - if (count > max) { - max = count; - result = old; - } - count = 1; - old = current; - } - } - if (count > max) { - max = count; - result = current; - } - return result; - } - -} // MatrixHelper Copied: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixHelper.java (from rev 143, nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixHelper.java) =================================================================== --- nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixHelper.java (rev 0) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixHelper.java 2009-05-16 19:21:04 UTC (rev 144) @@ -0,0 +1,326 @@ +/* *##% 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.nuiton.math.matrix; + +import java.io.StreamTokenizer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Stack; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Contains usefull methods to get information on matrix. + * + * Created: 28 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +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. + * + * @param mat + * @return + */ + public static MatrixND convertToId(MatrixND mat) { + int size = mat.getDim(0); + if (size > mat.getDim(1)) { + size = mat.getDim(1); + } + + fill(mat, 0); + + for (int i = 0; i < size; i++) { + mat.setValue(i, i, 1); + } + return mat; + } + + /** + * Permet de relire une chaine du type [[[1, 2], [3, 4]],[[3, 5], [1, 4]]] + * <p> + * Remarque: une premiere implantantion avait ete faite en utilisant + * {@link StreamTokenizer} mais en fait il y a un bug dedans, il ne sait pas + * parser les chiffres avec un exposant: 5.0E-7 par exemple est lu comme 5.0 + * :( + * <p> + * Remarque: une autre implantation de remplacement a ete faite en utilisant + * le {@link org.nuiton.util.StringUtil#split(String, String)} mais elle + * etait moins performante (x2) + * + * @param s la chaine representant les listes de liste + * @return une liste de liste ... de Double + */ + public static List convertStringToList(String s) { + List result = null; + Stack<List> stack = new Stack<List>(); + StringBuffer number = new StringBuffer(20); // initial to 20 char + + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == ' ') { + // skip space + } + if (c == '[') { + stack.push(new ArrayList()); + } else if (c == ',') { + if (number.length() != 0) { + // on a une ',' on doit donc avoir un nombre dans number + // a moins que ce ne soit une ',' entre deux listes + Double value = Double.valueOf(number.toString()); + stack.peek().add(value); + } + number.setLength(0); + } else if (c == ']') { + // fin d'une liste, il doit rester un nombre dans number + // a mois que la liste etait vide + if (number.length() != 0) { + Double value = Double.valueOf(number.toString()); + stack.peek().add(value); + number.setLength(0); + } + + List current = stack.pop(); + if (stack.empty()) { + result = current; + } else { + stack.peek().add(current); + } + } else { + // pas un '[' ou ']', pas une ',' devrait etre + // un bout du nombre, si c un espace qui traine n'importe ou + // c pas grace car Double.valueOf gere les espaces + number.append(c); + } + } + return result; + } + + /** + * permet de donner une représentation String d'un tableau de coordonnées + * + * @param coordinates les coordonnées + * @return la chaine demandée de la forme 1,3,34,23 + */ + public static String coordinatesToString(int[] coordinates) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < coordinates.length; i++) { + sb.append(coordinates[i]); + if (i + 1 < coordinates.length) { + sb.append(','); + } + } + return sb.toString(); + } + + /** + * permet de donner une représentation String d'un tableau de coordonnées + * + * @param coordinates les coordonnées + * @return la chaine demandée de la forme "Ob1","Ob2,"Ob3", ... la chaine + * prise pour l'objet est celle retournée par la méthode toString de + * l'objet + */ + public static String coordinatesToString(Object[] coordinates) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < coordinates.length; i++) { + sb.append(coordinates[i]); + if (i + 1 < coordinates.length) { + sb.append(','); + } + } + return sb.toString(); + } + + /** + * Permet de savoir si deux dimension sont identiques. + */ + public static boolean sameDimension(int[] dim1, int[] dim2) { + return Arrays.equals(dim1, dim2); + } + + /** + * Permet de convertir des coordonnées définies par des entiers en coordonnées + * semantique par des objets + * + * @param semantics la semantique à utilisé pour la conversion + * @param coordinates les coordonnées à convertir + * @return un tableau donnant les coordonnées sous forme semantique s'il n'y + * a pas de semantique (liste pleine de null) alors un objet Integer + * est créer pour représenter la semantique de la dimension. + */ + public static Object[] dimensionToSemantics(List[] semantics, + int[] coordinates) { + Object[] result = new Object[coordinates.length]; + for (int i = 0; i < result.length; i++) { + result[i] = semantics[i].get(coordinates[i]); + if (result[i] == null) { + result[i] = Integer.valueOf(coordinates[i]); + } + } + return result; + } + + /** + * Permet de convertir des coordonnées sémantiques en coordonnées défini par + * des entiers. Cette fonction est l'inverse de + * {@link #dimensionToSemantics}. + * + * @param semantics la semantique à utiliser pour la conversion + * @param coordinates les coordonnées sémantique + * @return les coordonnées en entier. Si la sémantique est représentéé par un + * Integer alors la valeur de l'integer est utilisé pour la + * conversion. + */ + public static int[] semanticsToDimension(List[] semantics, + Object[] coordinates) { + int[] result = new int[coordinates.length]; + for (int i = 0; i < coordinates.length; i++) { + if (coordinates[i] == null) { + result[i] = -1; + } else { + result[i] = indexOf(semantics, i, coordinates[i]); + } + } + return result; + } + + /** + * Permet de retrouver la position d'un objet dans une liste + * + * @param semantics la semantique à utilisé pour la recherche + * @param dim la dimension dans lequel il faut faire la recherche + * @param o l'objet à rechercher + * @return la position de l'objet dans la dimension demandée + * + * @throws NoSuchElementException If element doesn't exists + */ + public static int indexOf(List[] semantics, int dim, Object o) + throws NoSuchElementException { + if (o instanceof Integer) { + return ((Integer) o).intValue(); + } + int result = -1; + if ((0 <= dim) && (dim < semantics.length)) { + result = semantics[dim].indexOf(o); + } + if (result == -1) { + throw new NoSuchElementException( + "L'objet passé en argument n'a pas été retrouvé ou la dimension donnée ne convient pas:" + + o + " in " + semantics[dim]); + } + return result; + } + + /** + * Permet de remplir toute la matrice avec la même donnée + * + * @param mat la matrice à remplir + * @param value la valeur de remplissage + * @return la matrice passé en paramêtre + */ + public static MatrixND fill(MatrixND mat, final double value) { + mat.map(new MapFunction() { + public double apply(double v) { + return value; + } + }); + return mat; + } + + /** + * Retourne la valeur la plus courrement rencontrer dans un tableau. si + * plusieurs valeurs ont le même nombre d'occurence la plus petite valeur + * est retournée. + * + * @param tab le tableau de valeur + * @return la valeur la plus nombreuse dans le tableau + */ + public static double maxOccurence(double[] tab) { + double[] tmp = new double[tab.length]; + System.arraycopy(tab, 0, tmp, 0, tab.length); + return maxOccurence1(tmp); + } + + public static double maxOccurence(float[] tab) { + double[] tmp = new double[tab.length]; + for (int i = 0; i < tab.length; i++) { + tmp[i] = tab[i]; + } + return maxOccurence1(tmp); + } + + /** + * le tableau en entre est trie durant l'execution de la methode, il est + * donc modifié + */ + protected static double maxOccurence1(double[] tmp) { + if (tmp.length == 0) { + throw new IllegalArgumentException("Array must be not empty"); + } + // double [] tmp = new double[tab.length]; + // System.arraycopy(tab, 0, tmp, 0, tab.length); + Arrays.sort(tmp); + + // le nombre de fois que l'on a rencontrer la valeur la plus nombreuse + int max = 1; + // le nombre de fois que l'on a rencontrer la valeur courante + int count = 1; + // la valeur la plus rencontrer + double result = tmp[0]; + // la valeur que l'on vient de traiter précédement + double old = tmp[0]; + // la valeur courante lu dans le tableaux + double current = tmp[0]; + // tant que l'on peut encore trouve un element plus nombreux dans le + // tableau on le parcours + for (int i = 1; max < tmp.length - i + count && i < tmp.length; i++) { + current = tmp[i]; + + if (current == old) { + count++; + } else { + if (count > max) { + max = count; + result = old; + } + count = 1; + old = current; + } + } + if (count > max) { + max = count; + result = current; + } + return result; + } + +} // MatrixHelper Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixIterator.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixIterator.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixIterator.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; /** * MatrixIterator. Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixIteratorImpl.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixIteratorImpl.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixIteratorImpl.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; import java.util.List; Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixND.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixND.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixND.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; import java.io.IOException; import java.io.Reader; Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixNDImpl.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixNDImpl.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixNDImpl.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; import java.util.Arrays; import java.util.List; Deleted: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixStringEncoder.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixStringEncoder.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixStringEncoder.java 2009-05-16 19:21:04 UTC (rev 144) @@ -1,345 +0,0 @@ -/* *##% 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.lang.StringEscapeUtils; -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 + '"' + StringEscapeUtils.escapeJava(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("\"")) { - String resultString = result[i].substring(1, result[i].length() - 1);// remove " and " - resultString = StringEscapeUtils.unescapeJava(resultString); - result[i] = resultString; - } - } - 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 Copied: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixStringEncoder.java (from rev 143, nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/MatrixStringEncoder.java) =================================================================== --- nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixStringEncoder.java (rev 0) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/MatrixStringEncoder.java 2009-05-16 19:21:04 UTC (rev 144) @@ -0,0 +1,345 @@ +/* *##% 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.nuiton.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.lang.StringEscapeUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.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 + '"' + StringEscapeUtils.escapeJava(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("\"")) { + String resultString = result[i].substring(1, result[i].length() - 1);// remove " and " + resultString = StringEscapeUtils.unescapeJava(resultString); + result[i] = resultString; + } + } + 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: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/SemanticList.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/SemanticList.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/SemanticList.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; import java.util.AbstractList; import java.util.ArrayList; Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/SubMatrix.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/SubMatrix.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/SubMatrix.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; import java.io.Serializable; import java.util.Arrays; Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/Vector.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/Vector.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/Vector.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix; +package org.nuiton.math.matrix; /** * Vector. Deleted: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/JAXXMatrixEditor.jaxx =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/gui/JAXXMatrixEditor.jaxx 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/JAXXMatrixEditor.jaxx 2009-05-16 19:21:04 UTC (rev 144) @@ -1,173 +0,0 @@ -<!-- -/* *##% - * Copyright (C) 2005 - * Ifremer, Code Lutin, Cedric Pineau, Benjamin Poussin - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * 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 Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - *##%*/ - -/* * - * IsisFish.java - * - * Created: 1 aout 2005 18:37:25 CEST - * - * @author Benjamin POUSSIN <poussin@codelutin.com> - * @version $Revision: 1312 $ - * - * Last update: $Date: 2008-08-28 10:21:07 +0200 (jeu, 28 aoû 2008) $ - * by : $Author: sletellier $ - */ - --> -<MatrixEditor id='jaxxMatrixManel' layout='{new BorderLayout()}'> - - <MatrixTableModel id='tableModel' javaBean='null'/> - - <!-- if true, use linear representation of matrix --> - <Boolean id='linearModel' javaBean='false'/> - - <!-- if false don't show default value in matrix (ex: 0) --> - <Boolean id='linearModelShowDefault' javaBean='false'/> - - <!-- Boolean to autorize matrice dimension changes. --> - <Boolean id='dimensionEdit' javaBean='false'/> - - <script><![CDATA[ - -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Event; -import java.awt.event.KeyEvent; -import java.awt.event.MouseEvent; -import java.util.Iterator; - -import org.codelutin.i18n.I18n; -import org.codelutin.math.matrix.MatrixFactory; -import org.codelutin.math.matrix.MatrixND; -import org.codelutin.util.ListenerSet; - -private final static int DEFAULT_WIDTH = 150; - -private final static int DEFAULT_HEIGHT = 150; - -protected ListenerSet listeners = new ListenerSet(); -protected MatrixPopupMenu popupMenu = null; -protected MatrixND matrix = null; -initObject(); -public JAXXMatrixEditor(MatrixND m, boolean dimensionEdit) { - this(dimensionEdit, DEFAULT_WIDTH, DEFAULT_HEIGHT); -} - -public JAXXMatrixEditor(boolean dimensionEdit, int width, int height) { - this.dimensionEdit = dimensionEdit; - setPreferredSize(new Dimension(width, height)); -} - -public JAXXMatrixEditor(boolean dimensionEdit) { - this(dimensionEdit, DEFAULT_WIDTH, DEFAULT_HEIGHT); -} - -public void setMatrix(MatrixND m){ - this.matrix = m; - initObject(); -} - -public MatrixND getMatrix() { - return matrix; -} - -protected MatrixFactory getFactory() { - return MatrixFactory.getInstance(); -} - -public void addMatrixListener(MatrixPanelListener l) { - listeners.add(l); -} - -public void removeMatrixPanelListener(MatrixPanelListener l) { - listeners.remove(l); -} - -protected void initObject() { - if (getMatrix() == null) { - editArea.setViewportView(null); - } - else { - popupMenu = new MatrixPopupMenu(this); - table = new JTable() { - public void processMouseEvent(MouseEvent event) { - if (event.isPopupTrigger()) { - popupMenu.show(event.getComponent(), event.getX(), event.getY()); - } - super.processMouseEvent(event); - } - }; - - table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_C, Event.CTRL_MASK),"copy"); - table.getActionMap().put("copy",popupMenu.getSendToClipBoardSelectionCopyAction()); - table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_V, Event.CTRL_MASK),"paste"); - table.getActionMap().put("paste",popupMenu.getSendToClipBoardCurrentPasteAction()); - if (isLinearModel()) { - setTableModel(new MatrixTableModelLinear(getMatrix(), isLinearModelShowDefault())); - } - else { - setTableModel(new MatrixTableModelND(getMatrix())); - } - - getTableModel().addTableModelListener(new TableModelListener() { - - @Override - public void tableChanged(TableModelEvent e) { - fireEvent(); - } - }); - - table.setModel(getTableModel()); - table.setDefaultRenderer(String.class, tableModel.getMatrixCellRenderer()); - table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); - table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); - editArea.setViewportView(table); - } - repaint(); -} - -protected void btnAction(){ - String dim; - dim = JOptionPane.showInputDialog(null, I18n._("lutinmatrix.create.matrix.message"), I18n._("lutinmatrix.create.matrix.title"), JOptionPane.DEFAULT_OPTION); - - if (dim != null) { - String[] sdim = dim.split(";"); - int[] idim = new int[sdim.length]; - for (int i = 0; i < idim.length; i++) { - idim[i] = Integer.parseInt(sdim[i]); - } - setMatrix(getFactory().create(idim)); - } -} - -protected void fireEvent() { - MatrixPanelEvent e = new MatrixPanelEvent(this); - for (Iterator i = listeners.iterator(); i.hasNext();) { - MatrixPanelListener l = (MatrixPanelListener) i.next(); - l.matrixChanged(e); - } -} - ]]> - </script> - <JScrollPane id='editArea' constraints='BorderLayout.CENTER'> - <JTable id='table' autoResizeMode='{JTable.AUTO_RESIZE_OFF}' cellSelectionEnabled='{true}' selectionMode='{ListSelectionModel.SINGLE_INTERVAL_SELECTION}'/> - </JScrollPane> - <JButton id='buttonEdit' text='lutinmatrix.create.matrix.button' visible='{isDimensionEdit()}' - onActionPerformed='btnAction()' constraints='BorderLayout.SOUTH'/> -</MatrixEditor> \ No newline at end of file Copied: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/JAXXMatrixEditor.jaxx (from rev 143, nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/gui/JAXXMatrixEditor.jaxx) =================================================================== --- nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/JAXXMatrixEditor.jaxx (rev 0) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/JAXXMatrixEditor.jaxx 2009-05-16 19:21:04 UTC (rev 144) @@ -0,0 +1,173 @@ +<!-- +/* *##% + * Copyright (C) 2005 + * Ifremer, Code Lutin, Cedric Pineau, Benjamin Poussin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * 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 Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + *##%*/ + +/* * + * IsisFish.java + * + * Created: 1 aout 2005 18:37:25 CEST + * + * @author Benjamin POUSSIN <poussin@codelutin.com> + * @version $Revision: 1312 $ + * + * Last update: $Date: 2008-08-28 10:21:07 +0200 (jeu, 28 aoû 2008) $ + * by : $Author: sletellier $ + */ + --> +<MatrixEditor id='jaxxMatrixManel' layout='{new BorderLayout()}'> + + <MatrixTableModel id='tableModel' javaBean='null'/> + + <!-- if true, use linear representation of matrix --> + <Boolean id='linearModel' javaBean='false'/> + + <!-- if false don't show default value in matrix (ex: 0) --> + <Boolean id='linearModelShowDefault' javaBean='false'/> + + <!-- Boolean to autorize matrice dimension changes. --> + <Boolean id='dimensionEdit' javaBean='false'/> + + <script><![CDATA[ + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Event; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.util.Iterator; + +import org.nuiton.i18n.I18n; +import org.nuiton.math.matrix.MatrixFactory; +import org.nuiton.math.matrix.MatrixND; +import org.nuiton.util.ListenerSet; + +private final static int DEFAULT_WIDTH = 150; + +private final static int DEFAULT_HEIGHT = 150; + +protected ListenerSet listeners = new ListenerSet(); +protected MatrixPopupMenu popupMenu = null; +protected MatrixND matrix = null; +initObject(); +public JAXXMatrixEditor(MatrixND m, boolean dimensionEdit) { + this(dimensionEdit, DEFAULT_WIDTH, DEFAULT_HEIGHT); +} + +public JAXXMatrixEditor(boolean dimensionEdit, int width, int height) { + this.dimensionEdit = dimensionEdit; + setPreferredSize(new Dimension(width, height)); +} + +public JAXXMatrixEditor(boolean dimensionEdit) { + this(dimensionEdit, DEFAULT_WIDTH, DEFAULT_HEIGHT); +} + +public void setMatrix(MatrixND m){ + this.matrix = m; + initObject(); +} + +public MatrixND getMatrix() { + return matrix; +} + +protected MatrixFactory getFactory() { + return MatrixFactory.getInstance(); +} + +public void addMatrixListener(MatrixPanelListener l) { + listeners.add(l); +} + +public void removeMatrixPanelListener(MatrixPanelListener l) { + listeners.remove(l); +} + +protected void initObject() { + if (getMatrix() == null) { + editArea.setViewportView(null); + } + else { + popupMenu = new MatrixPopupMenu(this); + table = new JTable() { + public void processMouseEvent(MouseEvent event) { + if (event.isPopupTrigger()) { + popupMenu.show(event.getComponent(), event.getX(), event.getY()); + } + super.processMouseEvent(event); + } + }; + + table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_C, Event.CTRL_MASK),"copy"); + table.getActionMap().put("copy",popupMenu.getSendToClipBoardSelectionCopyAction()); + table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_V, Event.CTRL_MASK),"paste"); + table.getActionMap().put("paste",popupMenu.getSendToClipBoardCurrentPasteAction()); + if (isLinearModel()) { + setTableModel(new MatrixTableModelLinear(getMatrix(), isLinearModelShowDefault())); + } + else { + setTableModel(new MatrixTableModelND(getMatrix())); + } + + getTableModel().addTableModelListener(new TableModelListener() { + + @Override + public void tableChanged(TableModelEvent e) { + fireEvent(); + } + }); + + table.setModel(getTableModel()); + table.setDefaultRenderer(String.class, tableModel.getMatrixCellRenderer()); + table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); + editArea.setViewportView(table); + } + repaint(); +} + +protected void btnAction(){ + String dim; + dim = JOptionPane.showInputDialog(null, I18n._("lutinmatrix.create.matrix.message"), I18n._("lutinmatrix.create.matrix.title"), JOptionPane.DEFAULT_OPTION); + + if (dim != null) { + String[] sdim = dim.split(";"); + int[] idim = new int[sdim.length]; + for (int i = 0; i < idim.length; i++) { + idim[i] = Integer.parseInt(sdim[i]); + } + setMatrix(getFactory().create(idim)); + } +} + +protected void fireEvent() { + MatrixPanelEvent e = new MatrixPanelEvent(this); + for (Iterator i = listeners.iterator(); i.hasNext();) { + MatrixPanelListener l = (MatrixPanelListener) i.next(); + l.matrixChanged(e); + } +} + ]]> + </script> + <JScrollPane id='editArea' constraints='BorderLayout.CENTER'> + <JTable id='table' autoResizeMode='{JTable.AUTO_RESIZE_OFF}' cellSelectionEnabled='{true}' selectionMode='{ListSelectionModel.SINGLE_INTERVAL_SELECTION}'/> + </JScrollPane> + <JButton id='buttonEdit' text='lutinmatrix.create.matrix.button' visible='{isDimensionEdit()}' + onActionPerformed='btnAction()' constraints='BorderLayout.SOUTH'/> +</MatrixEditor> \ No newline at end of file Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixEditor.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/gui/MatrixEditor.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixEditor.java 2009-05-16 19:21:04 UTC (rev 144) @@ -3,11 +3,11 @@ * and open the template in the editor. */ -package org.codelutin.math.matrix.gui; +package org.nuiton.math.matrix.gui; import javax.swing.JButton; import javax.swing.JPanel; -import org.codelutin.math.matrix.MatrixND; +import org.nuiton.math.matrix.MatrixND; import javax.swing.JTable; /** Deleted: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPanelEditor.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/gui/MatrixPanelEditor.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPanelEditor.java 2009-05-16 19:21:04 UTC (rev 144) @@ -1,464 +0,0 @@ -/* - * *##% 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.gui; - -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Event; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.KeyStroke; -import javax.swing.ListSelectionModel; -import javax.swing.event.TableModelEvent; -import javax.swing.event.TableModelListener; - -import org.codelutin.i18n.I18n; -import org.codelutin.math.matrix.MatrixException; -import org.codelutin.math.matrix.MatrixFactory; -import org.codelutin.math.matrix.MatrixND; -import org.codelutin.util.ListenerSet; - -/** - * JPanel contenant une JTable pour afficher une Matrice a une ou deux - * dimension. - * - * TODO: Une methode permettant de retourne la sous matrice de la selection que - * la matrice soit reprensentée en lineaire ou non. (avoir un mapping cellule de - * table vers element de matrice - * - * Created: 29 oct. 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - * @version $Revision$ - * - * Mise a jour: $Date$ - * par : $Author$ - */ -public class MatrixPanelEditor extends MatrixEditor implements TableModelListener { // MatrixPanelEditor - - /** serialVersionUID */ - private static final long serialVersionUID = 2097859265435050946L; - - private final static int DEFAULT_WIDTH = 150; - - private final static int DEFAULT_HEIGHT = 150; - - protected ListenerSet listeners = new ListenerSet(); - - protected JTable table; - - protected MatrixND m; - - protected MatrixTableModel tableModel; - - protected JScrollPane editArea; - - protected MatrixPopupMenu popupMenu; - // protected JTextArea text; - - /** if true, use linear representation of matrix */ - protected boolean linearModel = false; - /** if false don't show default value in matrix (ex: 0) */ - protected boolean linearModelShowDefault = false; - - /** Boolean to autorize table editing. */ - protected boolean enabled = true; - - /** Boolean to show matrix. */ - protected boolean visible = true; - - /** Boolean to autorize matrice dimension changes. */ - protected boolean dimensionEdit; - - /** - * Construct a new JPanel to edit matrix. - * - * @param m the matrix to edit. - * @param dimensionEdit to enabled matrix dimension changes. - */ - public MatrixPanelEditor(MatrixND m, boolean dimensionEdit) { - this(dimensionEdit, DEFAULT_WIDTH, DEFAULT_HEIGHT); - setMatrix(m); - } - - /** - * Construct a new JPanel to edit matrix. - * - * @param dimensionEdit to enabled matrix dimension changes. - * @param width width prefered for the component - * @param height height prefered for the component - */ - public MatrixPanelEditor(boolean dimensionEdit, int width, int height) { - this.dimensionEdit = dimensionEdit; - setPreferredSize(new Dimension(width, height)); - initObjet(); - } - - /** - * Construct a new JPanel to edit matrix. - * - * @param dimensionEdit to enabled matrix dimension changes. - */ - public MatrixPanelEditor(boolean dimensionEdit) { - this(dimensionEdit, DEFAULT_WIDTH, DEFAULT_HEIGHT); - } - - /** - * Construct a new JPanel to edit matrix. Matrix dimension can not change. - */ - public MatrixPanelEditor() { - this(false); - } - - protected MatrixFactory getFactory() { - return MatrixFactory.getInstance(); - } - - public void addMatrixListener(MatrixPanelListener l) { - listeners.add(l); - } - - public void removeMatrixPanelListener(MatrixPanelListener l) { - listeners.remove(l); - } - - protected void initObjet() { - setLayout(new BorderLayout()); - editArea = new JScrollPane(); - add(editArea, BorderLayout.CENTER); - initDimensionEdit(); - } - - protected JButton bEdit = null; - - public JButton getButtonEdit() { - if (bEdit == null) { - bEdit = new JButton(I18n._("lutinmatrix.create.matrix.button")); - bEdit.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent e) { - String dim; - dim = JOptionPane.showInputDialog(null, I18n - ._("lutinmatrix.create.matrix.message"), I18n - ._("lutinmatrix.create.matrix.title"), - JOptionPane.DEFAULT_OPTION); - - if (dim != null) { - String[] sdim = dim.split(";"); - int[] idim = new int[sdim.length]; - for (int i = 0; i < idim.length; i++) { - idim[i] = Integer.parseInt(sdim[i]); - } - setMatrix(getFactory().create(idim)); - } - } - }); - add(bEdit, BorderLayout.SOUTH); - } - return bEdit; - } - - /** - * @return Returns the linearModel. - */ - public Boolean isLinearModel() { - return this.linearModel; - } - - /** - * @param linearModel The linearModel to set. - */ - public void setLinearModel(Boolean linearModel) { - this.linearModel = linearModel; - initObject(m); - } - - /** - * @return Returns the linearModelShowDefault. - */ - public Boolean isLinearModelShowDefault() { - return this.linearModelShowDefault; - } - - /** - * @param linearModelShowDefault The linearModelShowDefault to set. - */ - public void setLinearModelShowDefault(Boolean linearModelShowDefault) { - this.linearModelShowDefault = linearModelShowDefault; - initObject(m); - } - - /** - * Get the value of dimensionEdit. - * - * @return value of dimensionEdit. - */ - public boolean isDimensionEdit() { - return dimensionEdit; - } - - /** - * Set the value of dimensionEdit. - * - * @param v Value to assign to dimensionEdit. - */ - public void setDimensionEdit(boolean v) { - this.dimensionEdit = v; - initDimensionEdit(); - } - - protected void initDimensionEdit() { - getButtonEdit().setVisible(dimensionEdit); - } - - protected void initObject(MatrixND m) { - if (m == null) { - editArea.setViewportView(null); - } else { // if (m.getNbDim() <= 2) { - // pour les matrices 1D et 2D - JTable table = getTable(); - if (isLinearModel()) { - tableModel = new MatrixTableModelLinear(m, - isLinearModelShowDefault()); - } else { - tableModel = new MatrixTableModelND(m); - } - table.getModel().removeTableModelListener(this); - tableModel.addTableModelListener(this); - table.setModel(tableModel); - table.setDefaultRenderer(String.class, tableModel - .getMatrixCellRenderer()); - editArea.setViewportView(table); - // next line is needed otherwize matrix doesn't appear - add(editArea, BorderLayout.CENTER); - // if (table.getColumnCount() > 0 && m.getNbDim() > 1) { - // table.getColumnModel().getColumn(0).setCellRenderer( - // tableModel.getMatrixCellRenderer()); - // } - // text = null; - } - // else { - // // pour les matrices 3D et plus - // text = new JTextArea(); - // editArea.setViewportView(text); - // text.setText(MatrixHelper.encodeToXML(m)); - // table = null; - // editArea.setColumnHeaderView(null); - // } - setEnabled(enabled); - setVisible(visible); - repaint(); - } - - public JTable getTable() { - if (table == null) { - popupMenu = new MatrixPopupMenu(this); - table = new JTable() { - public void processMouseEvent(MouseEvent event) { - if (event.isPopupTrigger()) { - popupMenu.show(event.getComponent(), event.getX(), - event.getY()); - } - super.processMouseEvent(event); - } - }; - - table.getInputMap().put( - KeyStroke.getKeyStroke(KeyEvent.VK_C, Event.CTRL_MASK), - "copy"); - table.getActionMap().put("copy", - popupMenu.getSendToClipBoardSelectionCopyAction()); - - table.getInputMap().put( - KeyStroke.getKeyStroke(KeyEvent.VK_V, Event.CTRL_MASK), - "paste"); - table.getActionMap().put("paste", - popupMenu.getSendToClipBoardCurrentPasteAction()); - - /* - * table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_A, - * Event.CTRL_MASK), "selectAll"); - * table.getActionMap().put("selectAll", new AbstractAction(){ - * public void actionPerformed(ActionEvent e) { table.selectAll(); - * }}); - */ - - table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); - table - .setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); - table.setCellSelectionEnabled(true); - - } - return table; - } - - public void setMatrix(MatrixND m) throws MatrixException { - initObject(m); - this.m = m; - fireEvent(); - } - - public MatrixND getMatrix() { - // if (m == null) { - return m; - // } else if (m.getNbDim() <= 2) { - // return m; - // } else { - // return MatrixHelper.decodeFromXML(text.getText()); - // } - } - - /** - * Enable the matrix to be edited. By default, the matrix is editable. - */ - public void setEnabled(boolean enabled) { - if (tableModel != null) { - tableModel.setEnabled(enabled); - } - if (table != null){ - table.setEnabled(enabled); - } - super.setEnabled(enabled); - // if (text != null) { - // text.setEditable(enabled); - // } - // si la table n'est pas editable, inutile de laisser le bouton - // de creation de matrice. - if (!enabled && dimensionEdit) { - dimensionEdit = false; - initDimensionEdit(); - } - if (!enabled) { - editArea.setViewportView(null); - } - this.enabled = enabled; - } - - public boolean isEnabled() { - return enabled; - } - - /** - * Set the matrix visible. By default, the matrix is visible. - */ - public void setVisible(boolean visible) { - if (table != null){ - table.setVisible(visible); - } - super.setVisible(visible); - this.visible = visible; - } - - public boolean isVisible() { - return visible; - } - /* - * @see javax.swing.event.TableModelListener#tableChanged(javax.swing.event.TableModelEvent) - */ - public void tableChanged(TableModelEvent e) { - fireEvent(); - } - - protected void fireEvent() { - MatrixPanelEvent e = new MatrixPanelEvent(this); - for (Iterator i = listeners.iterator(); i.hasNext();) { - MatrixPanelListener l = (MatrixPanelListener) i.next(); - l.matrixChanged(e); - } - } - - /** - * Une petite fonction main pour le test... - */ - public static void main(String[] args) { - I18n.init("fr", "FR"); - // I18n.init("en","EN"); - - JFrame frame = new JFrame(); - MatrixPanelEditor ed = null; - - try { - ed = new MatrixPanelEditor(true); - ed.setLinearModel(false); - frame.getContentPane().add(ed); - - // MatriceND m = new MatriceNDImpl(new int[]{4,4}); - // m.set(new int[]{0,0}, new Const(0)); - // m.set(new int[]{0,1}, new Const(1)); - // m.set(new int[]{0,2}, new Const(2)); - // m.set(new int[]{1,0}, new Const(3)); - // m.set(new int[]{1,1}, new Const(4)); - // m.set(new int[]{1,2}, new Const(5)); - - List sem1 = Arrays.asList(new String[] { "toto", "titi", "tutu" }); - List sem2 = Arrays.asList(new String[] { "tata", "tete", "tyty" }); - List sem3 = Arrays - .asList(new String[] { "riri", "fifi", "loulou" }); - - /* - * MatrixND m = MatrixFactory.getInstance().create(new - * int[]{100,100}); - */ - - /* - * MatrixND m = MatrixFactory.getInstance().create("name", new - * List[] { sem1, sem2 }, new String[]{"dim1", "dim2"}); - * m.setValue(0, 0, 1); m.setValue(0, 1, 2); m.setValue(0, 2, 3); - */ - - MatrixND m = MatrixFactory.getInstance().create("name", - new List[] { sem1, sem2, sem3 }, - new String[] { "dim1", "dim2", "dim3" }); - - m.setValue(0, 0, 0, 1); - m.setValue(0, 1, 0, 2); - m.setValue(0, 0, 1, 3); - - ed.setMatrix(m); - // ed.setEnabled(false); - } catch (MatrixException e) { - e.printStackTrace(); - System.exit(0); - } - - // final MatrixPanelEditor mp = ed; - frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(0); - } - }); - frame.pack(); - frame.setVisible(true); - } - -} // MatrixPanelEditor Copied: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPanelEditor.java (from rev 143, nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/gui/MatrixPanelEditor.java) =================================================================== --- nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPanelEditor.java (rev 0) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPanelEditor.java 2009-05-16 19:21:04 UTC (rev 144) @@ -0,0 +1,464 @@ +/* + * *##% 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.nuiton.math.matrix.gui; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Event; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.KeyStroke; +import javax.swing.ListSelectionModel; +import javax.swing.event.TableModelEvent; +import javax.swing.event.TableModelListener; + +import org.nuiton.i18n.I18n; +import org.nuiton.math.matrix.MatrixException; +import org.nuiton.math.matrix.MatrixFactory; +import org.nuiton.math.matrix.MatrixND; +import org.nuiton.util.ListenerSet; + +/** + * JPanel contenant une JTable pour afficher une Matrice a une ou deux + * dimension. + * + * TODO: Une methode permettant de retourne la sous matrice de la selection que + * la matrice soit reprensentée en lineaire ou non. (avoir un mapping cellule de + * table vers element de matrice + * + * Created: 29 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public class MatrixPanelEditor extends MatrixEditor implements TableModelListener { // MatrixPanelEditor + + /** serialVersionUID */ + private static final long serialVersionUID = 2097859265435050946L; + + private final static int DEFAULT_WIDTH = 150; + + private final static int DEFAULT_HEIGHT = 150; + + protected ListenerSet listeners = new ListenerSet(); + + protected JTable table; + + protected MatrixND m; + + protected MatrixTableModel tableModel; + + protected JScrollPane editArea; + + protected MatrixPopupMenu popupMenu; + // protected JTextArea text; + + /** if true, use linear representation of matrix */ + protected boolean linearModel = false; + /** if false don't show default value in matrix (ex: 0) */ + protected boolean linearModelShowDefault = false; + + /** Boolean to autorize table editing. */ + protected boolean enabled = true; + + /** Boolean to show matrix. */ + protected boolean visible = true; + + /** Boolean to autorize matrice dimension changes. */ + protected boolean dimensionEdit; + + /** + * Construct a new JPanel to edit matrix. + * + * @param m the matrix to edit. + * @param dimensionEdit to enabled matrix dimension changes. + */ + public MatrixPanelEditor(MatrixND m, boolean dimensionEdit) { + this(dimensionEdit, DEFAULT_WIDTH, DEFAULT_HEIGHT); + setMatrix(m); + } + + /** + * Construct a new JPanel to edit matrix. + * + * @param dimensionEdit to enabled matrix dimension changes. + * @param width width prefered for the component + * @param height height prefered for the component + */ + public MatrixPanelEditor(boolean dimensionEdit, int width, int height) { + this.dimensionEdit = dimensionEdit; + setPreferredSize(new Dimension(width, height)); + initObjet(); + } + + /** + * Construct a new JPanel to edit matrix. + * + * @param dimensionEdit to enabled matrix dimension changes. + */ + public MatrixPanelEditor(boolean dimensionEdit) { + this(dimensionEdit, DEFAULT_WIDTH, DEFAULT_HEIGHT); + } + + /** + * Construct a new JPanel to edit matrix. Matrix dimension can not change. + */ + public MatrixPanelEditor() { + this(false); + } + + protected MatrixFactory getFactory() { + return MatrixFactory.getInstance(); + } + + public void addMatrixListener(MatrixPanelListener l) { + listeners.add(l); + } + + public void removeMatrixPanelListener(MatrixPanelListener l) { + listeners.remove(l); + } + + protected void initObjet() { + setLayout(new BorderLayout()); + editArea = new JScrollPane(); + add(editArea, BorderLayout.CENTER); + initDimensionEdit(); + } + + protected JButton bEdit = null; + + public JButton getButtonEdit() { + if (bEdit == null) { + bEdit = new JButton(I18n._("lutinmatrix.create.matrix.button")); + bEdit.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + String dim; + dim = JOptionPane.showInputDialog(null, I18n + ._("lutinmatrix.create.matrix.message"), I18n + ._("lutinmatrix.create.matrix.title"), + JOptionPane.DEFAULT_OPTION); + + if (dim != null) { + String[] sdim = dim.split(";"); + int[] idim = new int[sdim.length]; + for (int i = 0; i < idim.length; i++) { + idim[i] = Integer.parseInt(sdim[i]); + } + setMatrix(getFactory().create(idim)); + } + } + }); + add(bEdit, BorderLayout.SOUTH); + } + return bEdit; + } + + /** + * @return Returns the linearModel. + */ + public Boolean isLinearModel() { + return this.linearModel; + } + + /** + * @param linearModel The linearModel to set. + */ + public void setLinearModel(Boolean linearModel) { + this.linearModel = linearModel; + initObject(m); + } + + /** + * @return Returns the linearModelShowDefault. + */ + public Boolean isLinearModelShowDefault() { + return this.linearModelShowDefault; + } + + /** + * @param linearModelShowDefault The linearModelShowDefault to set. + */ + public void setLinearModelShowDefault(Boolean linearModelShowDefault) { + this.linearModelShowDefault = linearModelShowDefault; + initObject(m); + } + + /** + * Get the value of dimensionEdit. + * + * @return value of dimensionEdit. + */ + public boolean isDimensionEdit() { + return dimensionEdit; + } + + /** + * Set the value of dimensionEdit. + * + * @param v Value to assign to dimensionEdit. + */ + public void setDimensionEdit(boolean v) { + this.dimensionEdit = v; + initDimensionEdit(); + } + + protected void initDimensionEdit() { + getButtonEdit().setVisible(dimensionEdit); + } + + protected void initObject(MatrixND m) { + if (m == null) { + editArea.setViewportView(null); + } else { // if (m.getNbDim() <= 2) { + // pour les matrices 1D et 2D + JTable table = getTable(); + if (isLinearModel()) { + tableModel = new MatrixTableModelLinear(m, + isLinearModelShowDefault()); + } else { + tableModel = new MatrixTableModelND(m); + } + table.getModel().removeTableModelListener(this); + tableModel.addTableModelListener(this); + table.setModel(tableModel); + table.setDefaultRenderer(String.class, tableModel + .getMatrixCellRenderer()); + editArea.setViewportView(table); + // next line is needed otherwize matrix doesn't appear + add(editArea, BorderLayout.CENTER); + // if (table.getColumnCount() > 0 && m.getNbDim() > 1) { + // table.getColumnModel().getColumn(0).setCellRenderer( + // tableModel.getMatrixCellRenderer()); + // } + // text = null; + } + // else { + // // pour les matrices 3D et plus + // text = new JTextArea(); + // editArea.setViewportView(text); + // text.setText(MatrixHelper.encodeToXML(m)); + // table = null; + // editArea.setColumnHeaderView(null); + // } + setEnabled(enabled); + setVisible(visible); + repaint(); + } + + public JTable getTable() { + if (table == null) { + popupMenu = new MatrixPopupMenu(this); + table = new JTable() { + public void processMouseEvent(MouseEvent event) { + if (event.isPopupTrigger()) { + popupMenu.show(event.getComponent(), event.getX(), + event.getY()); + } + super.processMouseEvent(event); + } + }; + + table.getInputMap().put( + KeyStroke.getKeyStroke(KeyEvent.VK_C, Event.CTRL_MASK), + "copy"); + table.getActionMap().put("copy", + popupMenu.getSendToClipBoardSelectionCopyAction()); + + table.getInputMap().put( + KeyStroke.getKeyStroke(KeyEvent.VK_V, Event.CTRL_MASK), + "paste"); + table.getActionMap().put("paste", + popupMenu.getSendToClipBoardCurrentPasteAction()); + + /* + * table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_A, + * Event.CTRL_MASK), "selectAll"); + * table.getActionMap().put("selectAll", new AbstractAction(){ + * public void actionPerformed(ActionEvent e) { table.selectAll(); + * }}); + */ + + table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + table + .setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); + table.setCellSelectionEnabled(true); + + } + return table; + } + + public void setMatrix(MatrixND m) throws MatrixException { + initObject(m); + this.m = m; + fireEvent(); + } + + public MatrixND getMatrix() { + // if (m == null) { + return m; + // } else if (m.getNbDim() <= 2) { + // return m; + // } else { + // return MatrixHelper.decodeFromXML(text.getText()); + // } + } + + /** + * Enable the matrix to be edited. By default, the matrix is editable. + */ + public void setEnabled(boolean enabled) { + if (tableModel != null) { + tableModel.setEnabled(enabled); + } + if (table != null){ + table.setEnabled(enabled); + } + super.setEnabled(enabled); + // if (text != null) { + // text.setEditable(enabled); + // } + // si la table n'est pas editable, inutile de laisser le bouton + // de creation de matrice. + if (!enabled && dimensionEdit) { + dimensionEdit = false; + initDimensionEdit(); + } + if (!enabled) { + editArea.setViewportView(null); + } + this.enabled = enabled; + } + + public boolean isEnabled() { + return enabled; + } + + /** + * Set the matrix visible. By default, the matrix is visible. + */ + public void setVisible(boolean visible) { + if (table != null){ + table.setVisible(visible); + } + super.setVisible(visible); + this.visible = visible; + } + + public boolean isVisible() { + return visible; + } + /* + * @see javax.swing.event.TableModelListener#tableChanged(javax.swing.event.TableModelEvent) + */ + public void tableChanged(TableModelEvent e) { + fireEvent(); + } + + protected void fireEvent() { + MatrixPanelEvent e = new MatrixPanelEvent(this); + for (Iterator i = listeners.iterator(); i.hasNext();) { + MatrixPanelListener l = (MatrixPanelListener) i.next(); + l.matrixChanged(e); + } + } + + /** + * Une petite fonction main pour le test... + */ + public static void main(String[] args) { + I18n.init("fr", "FR"); + // I18n.init("en","EN"); + + JFrame frame = new JFrame(); + MatrixPanelEditor ed = null; + + try { + ed = new MatrixPanelEditor(true); + ed.setLinearModel(false); + frame.getContentPane().add(ed); + + // MatriceND m = new MatriceNDImpl(new int[]{4,4}); + // m.set(new int[]{0,0}, new Const(0)); + // m.set(new int[]{0,1}, new Const(1)); + // m.set(new int[]{0,2}, new Const(2)); + // m.set(new int[]{1,0}, new Const(3)); + // m.set(new int[]{1,1}, new Const(4)); + // m.set(new int[]{1,2}, new Const(5)); + + List sem1 = Arrays.asList(new String[] { "toto", "titi", "tutu" }); + List sem2 = Arrays.asList(new String[] { "tata", "tete", "tyty" }); + List sem3 = Arrays + .asList(new String[] { "riri", "fifi", "loulou" }); + + /* + * MatrixND m = MatrixFactory.getInstance().create(new + * int[]{100,100}); + */ + + /* + * MatrixND m = MatrixFactory.getInstance().create("name", new + * List[] { sem1, sem2 }, new String[]{"dim1", "dim2"}); + * m.setValue(0, 0, 1); m.setValue(0, 1, 2); m.setValue(0, 2, 3); + */ + + MatrixND m = MatrixFactory.getInstance().create("name", + new List[] { sem1, sem2, sem3 }, + new String[] { "dim1", "dim2", "dim3" }); + + m.setValue(0, 0, 0, 1); + m.setValue(0, 1, 0, 2); + m.setValue(0, 0, 1, 3); + + ed.setMatrix(m); + // ed.setEnabled(false); + } catch (MatrixException e) { + e.printStackTrace(); + System.exit(0); + } + + // final MatrixPanelEditor mp = ed; + frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + System.exit(0); + } + }); + frame.pack(); + frame.setVisible(true); + } + +} // MatrixPanelEditor Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPanelEvent.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/gui/MatrixPanelEvent.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPanelEvent.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,11 +15,11 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix.gui; +package org.nuiton.math.matrix.gui; import java.util.EventObject; -import org.codelutin.math.matrix.MatrixND; +import org.nuiton.math.matrix.MatrixND; /** * MatrixPanelEvent. Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPanelListener.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/gui/MatrixPanelListener.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPanelListener.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix.gui; +package org.nuiton.math.matrix.gui; /** * MatrixPanelListener. Deleted: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPopupMenu.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/gui/MatrixPopupMenu.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPopupMenu.java 2009-05-16 19:21:04 UTC (rev 144) @@ -1,573 +0,0 @@ -/* *##% 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.gui; - -import static org.codelutin.i18n.I18n._; - -import java.awt.Toolkit; -import java.awt.datatransfer.Clipboard; -import java.awt.datatransfer.DataFlavor; -import java.awt.datatransfer.StringSelection; -import java.awt.datatransfer.Transferable; -import java.awt.event.ActionEvent; -import java.io.File; -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JFileChooser; -import javax.swing.JMenu; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPopupMenu; -import javax.swing.JSeparator; -import javax.swing.filechooser.FileFilter; - -import org.codelutin.math.matrix.MatrixND; -import org.codelutin.util.FileUtil; - -/** - * Ajout d'un menu contextuel sur la matrice dans l'editeur. - * - * Created: 22 mars 2006 12:11:46 - * - * @author ruchaud - * @version $Revision$ - * - * Last update: $Date$ - * by : $Author$ - */ -public class MatrixPopupMenu extends JPopupMenu { - - /** serialVersionUID. */ - private static final long serialVersionUID = 3349189688987885915L; - - private MatrixEditor matrixEditor; - private JFileChooser fileChooser; - - private JMenu sendToClipBoard; - private JMenu sendToFile; - - private JCheckBoxMenuItem withSemantics; - - private Action sendToClipBoardAllCopyAction; - private Action sendToClipBoardAllPasteAction; - private Action sendToClipBoardSelectionCopyAction; - private Action sendToClipBoardCurrentPasteAction; - - private Action sendToFileAllCopyAction; - private Action sendToFileAllPasteAction; - private Action sendToFileSelectionCopyAction; - private Action sendToFileCurrentPasteAction; - - public MatrixPopupMenu(MatrixEditor matrixEditor) { - super(); - this.matrixEditor = matrixEditor; - - sendToClipBoard = getSendToClipBoard(); - sendToFile = getSendToFile(); - - withSemantics = new JCheckBoxMenuItem( - _("lutinmatrix.menu.option.semantics"), false); - - add(sendToClipBoard); - add(sendToFile); - add(new JSeparator()); - add(withSemantics); - } - - /** - * @return retourne le menu d'action pour le bloc note - */ - public JMenu getSendToClipBoard() { - if (sendToClipBoard == null) { - sendToClipBoard = new JMenu(_("lutinmatrix.menu.action")); - JMenuItem sendToClipBoardAllCopy = new JMenuItem( - _("lutinmatrix.menu.action.copy")); - JMenuItem sendToClipBoardAllPaste = new JMenuItem( - _("lutinmatrix.menu.action.paste")); - JMenuItem sendToClipBoardSelectionCopy = new JMenuItem( - _("lutinmatrix.menu.action.copy.selection")); - JMenuItem sendToClipBoardCurrentPaste = new JMenuItem( - _("lutinmatrix.menu.action.paste.position")); - - sendToClipBoard.add(sendToClipBoardAllCopy); - sendToClipBoard.add(sendToClipBoardAllPaste); - sendToClipBoard.add(new JSeparator()); - sendToClipBoard.add(sendToClipBoardSelectionCopy); - sendToClipBoard.add(sendToClipBoardCurrentPaste); - - sendToClipBoardAllCopy - .addActionListener(getSendToClipBoardAllCopyAction()); - sendToClipBoardAllPaste - .addActionListener(getSendToClipBoardAllPasteAction()); - sendToClipBoardSelectionCopy - .addActionListener(getSendToClipBoardSelectionCopyAction()); - sendToClipBoardCurrentPaste - .addActionListener(getSendToClipBoardCurrentPasteAction()); - } - - return sendToClipBoard; - } - - /** - * @return retourne le menu d'action pour les fichiers CSV - */ - public JMenu getSendToFile() { - if (sendToFile == null) { - sendToFile = new JMenu(_("lutinmatrix.menu.csv")); - JMenuItem sendToFileAllCopy = new JMenuItem( - _("lutinmatrix.menu.csv.export.file")); - JMenuItem sendToFileAllPaste = new JMenuItem( - _("lutinmatrix.menu.csv.import.file")); - JMenuItem sendToFileSelectionCopy = new JMenuItem( - _("lutinmatrix.menu.csv.export.selection")); - JMenuItem sendToFileCurrentPaste = new JMenuItem( - _("lutinmatrix.menu.csv.import.position")); - - sendToFile.add(sendToFileAllCopy); - sendToFile.add(sendToFileAllPaste); - sendToFile.add(new JSeparator()); - sendToFile.add(sendToFileSelectionCopy); - sendToFile.add(sendToFileCurrentPaste); - - sendToFileAllCopy.addActionListener(getSendToFileAllCopyAction()); - sendToFileAllPaste.addActionListener(getSendToFileAllPasteAction()); - sendToFileSelectionCopy - .addActionListener(getSendToFileSelectionCopyAction()); - sendToFileCurrentPaste - .addActionListener(getSendToFileCurrentPasteAction()); - } - - return sendToFile; - } - - /** - * @return retourne un writer du fichier choisi dans le selecteur de fichier - * @throws IOException - */ - private Writer getFileChooserWriter() throws IOException { - int returnVal = getFileChooser().showOpenDialog(matrixEditor); - if (returnVal == JFileChooser.APPROVE_OPTION) { - File selectedFile = getFileChooser().getSelectedFile(); - return FileUtil.getWriter(selectedFile); - } - return null; - } - - /** - * @return retourne un writer pour le bloc note - */ - private Writer getClipBoardWriter() { - return new StringWriter(); - } - - /** - * @return retourne un reader du fichier choisi dans le selecteur de fichier - * @throws IOException - */ - private Reader getFileChooserReader() throws IOException { - int returnVal = getFileChooser().showOpenDialog(matrixEditor); - if (returnVal == JFileChooser.APPROVE_OPTION) { - File selectedFile = getFileChooser().getSelectedFile(); - return FileUtil.getReader(selectedFile); - } - return null; - } - - /** - * @return retourne le contenu du bloc note sous la forme d'un reader - */ - private Reader getClipBoardReader() { - Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); - Transferable contents = clipboard.getContents(clipboard); - if (contents != null) { - try { - String data = (String) contents - .getTransferData(DataFlavor.stringFlavor); - return new StringReader(data); - } catch (Exception e) { - JOptionPane.showMessageDialog(matrixEditor, - "Impossible de coller les données", "Warning", - JOptionPane.WARNING_MESSAGE); - e.printStackTrace(); - } - } - return null; - } - - /** - * Desactive le menu si la matrice ne supporte pas le mode CSV - */ - protected void firePopupMenuWillBecomeVisible() { - if (!getMatrix().isSupportedCSV()) { - sendToClipBoard.setEnabled(false); - sendToFile.setEnabled(false); - } else { - sendToClipBoard.setEnabled(true); - sendToFile.setEnabled(true); - } - super.firePopupMenuWillBecomeVisible(); - } - - /** - * @return Matrice en cours de saisie dans l'editeur - */ - private MatrixND getMatrix() { - return matrixEditor.getMatrix(); - } - - /** - * @return la sous matrice en cours de saisie dans l'editeur c'est a dire la - * partie selectionnee - */ - private MatrixND getSelectedMatrix() { - int beginSelectedColumn = matrixEditor.getTable().getSelectedColumn(); - int nbSelectedColumn = matrixEditor.getTable().getSelectedColumnCount(); - - /* Prend en compte le décalage des lignes par rapport aux dimenssions */ - int nbColumnDimRow = matrixEditor.getMatrix().getNbDim() - 1; - beginSelectedColumn -= nbColumnDimRow; - if (beginSelectedColumn < 0) { - beginSelectedColumn = 0; - nbSelectedColumn -= nbColumnDimRow; - } - - int beginSelectedRow = matrixEditor.getTable().getSelectedRow() - 1; - int nbSelectedRow = matrixEditor.getTable().getSelectedRowCount(); - - if (getMatrix().getNbDim() == 1) { - return matrixEditor.getMatrix().getSubMatrix(0, - beginSelectedColumn, nbSelectedColumn); - } else { - return matrixEditor.getMatrix().getSubMatrix(0, beginSelectedRow, - nbSelectedRow).getSubMatrix(1, beginSelectedColumn, - nbSelectedColumn); - } - } - - /** - * @return retourne les coordonnees de la première cellule selectionnee - */ - private int[] getCoordinatesFirstCellSelectedMatrix() { - int selectedColumn = matrixEditor.getTable().getSelectedColumn(); - - /* Prend en compte le décalage des lignes par rapport aux dimenssions */ - int nbColumnDimRow = matrixEditor.getMatrix().getNbDim() - 1; - selectedColumn -= nbColumnDimRow; - if (selectedColumn < 0) { - selectedColumn = 0; - } - - int selectedRow = matrixEditor.getTable().getSelectedRow() - 1; - - return new int[] { selectedRow, selectedColumn }; - } - - /** - * @return Selecteur de fichier CSV - */ - private JFileChooser getFileChooser() { - if (fileChooser == null) { - fileChooser = new JFileChooser(); - FileFilter filter = new FileFilter() { - public boolean accept(File pathname) { - if (pathname.isDirectory()) { - return true; - } - - String extension = FileUtil.extension(pathname); - if (extension != null) { - if (extension.equals("csv")) { - return true; - } else { - return false; - } - } - - return false; - } - - public String getDescription() { - return "Texte CSV (*.csv)"; - } - }; - fileChooser.setFileFilter(filter); - } - return fileChooser; - } - - /** - * @return retourne l'action du bloc note permettant la copie entere de la - * matrice - */ - public Action getSendToClipBoardAllCopyAction() { - if (sendToClipBoardAllCopyAction == null) { - sendToClipBoardAllCopyAction = new AbstractAction() { - public void actionPerformed(ActionEvent e) { - sendToClipBoardAllCopyPerformed(); - } - }; - } - return sendToClipBoardAllCopyAction; - } - - /** - * @return retourne l'action du bloc note permettant la recopie entere de la - * matrice depuis le bloc note - */ - public Action getSendToClipBoardAllPasteAction() { - if (sendToClipBoardAllPasteAction == null) { - sendToClipBoardAllPasteAction = new AbstractAction() { - public void actionPerformed(ActionEvent e) { - sendToClipBoardAllPastePerformed(); - } - }; - } - return sendToClipBoardAllPasteAction; - } - - /** - * @return retourne l'action du bloc note permettant la copie de la partie - * selectionnee - */ - public Action getSendToClipBoardSelectionCopyAction() { - if (sendToClipBoardSelectionCopyAction == null) { - sendToClipBoardSelectionCopyAction = new AbstractAction() { - public void actionPerformed(ActionEvent e) { - sendToClipBoardSelectionCopyPerformed(); - } - }; - } - return sendToClipBoardSelectionCopyAction; - } - - /** - * @return retourne l'action du bloc note permettant la recopie de la partie - * selectionnee de la matrice depuis le bloc note - */ - public Action getSendToClipBoardCurrentPasteAction() { - if (sendToClipBoardCurrentPasteAction == null) { - sendToClipBoardCurrentPasteAction = new AbstractAction() { - public void actionPerformed(ActionEvent e) { - sendToClipBoardCurrentPastePerformed(); - } - }; - } - return sendToClipBoardCurrentPasteAction; - } - - private void sendToClipBoardAllCopyPerformed() { - try { - Writer writer = getClipBoardWriter(); - getMatrix().exportCSV(writer, withSemantics.getState()); - StringSelection contents = new StringSelection(writer.toString()); - Clipboard clipboard = Toolkit.getDefaultToolkit() - .getSystemClipboard(); - clipboard.setContents(contents, contents); - writer.close(); - matrixEditor.repaint(); - } catch (Exception e) { - JOptionPane.showMessageDialog(matrixEditor, - _("lutinmatrix.error.clipboard.write"), - _("lutinmatrix.error"), JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); - } - } - - private void sendToClipBoardAllPastePerformed() { - try { - Reader reader = getClipBoardReader(); - getMatrix().importCSV(reader, new int[] { 0, 0 }); - reader.close(); - matrixEditor.fireEvent(); - matrixEditor.repaint(); - } catch (Exception e) { - JOptionPane.showMessageDialog(matrixEditor, - _("lutinmatrix.error.clipboard.read"), - _("lutinmatrix.error"), JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); - } - } - - private void sendToClipBoardSelectionCopyPerformed() { - try { - Writer writer = getClipBoardWriter(); - getSelectedMatrix().exportCSV(writer, withSemantics.getState()); - StringSelection contents = new StringSelection(writer.toString()); - Clipboard clipboard = Toolkit.getDefaultToolkit() - .getSystemClipboard(); - clipboard.setContents(contents, contents); - writer.close(); - matrixEditor.repaint(); - } catch (Exception e) { - JOptionPane.showMessageDialog(matrixEditor, - _("lutinmatrix.error.clipboard.write"), - _("lutinmatrix.error"), JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); - } - } - - private void sendToClipBoardCurrentPastePerformed() { - try { - Reader reader = getClipBoardReader(); - getMatrix().importCSV(reader, - getCoordinatesFirstCellSelectedMatrix()); - reader.close(); - matrixEditor.fireEvent(); - matrixEditor.repaint(); - } catch (Exception e) { - JOptionPane.showMessageDialog(matrixEditor, - _("lutinmatrix.error.clipboard.read"), - _("lutinmatrix.error"), JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); - } - } - - /** - * @return retourne l'action du fichier permettant la copie entere de la - * matrice - */ - public Action getSendToFileAllCopyAction() { - if (sendToFileAllCopyAction == null) { - sendToFileAllCopyAction = new AbstractAction() { - public void actionPerformed(ActionEvent e) { - sendToFileAllCopyPerformed(); - } - }; - } - return sendToFileAllCopyAction; - } - - /** - * @return retourne l'action du fichier permettant la recopie entere de la - * matrice depuis le fichier - */ - public Action getSendToFileAllPasteAction() { - if (sendToFileAllPasteAction == null) { - sendToFileAllPasteAction = new AbstractAction() { - public void actionPerformed(ActionEvent e) { - sendToFileAllPastePerformed(); - } - }; - } - return sendToFileAllPasteAction; - } - - /** - * @return retourne l'action du fichier permettant la copie de la partie - * selectionnee - */ - public Action getSendToFileSelectionCopyAction() { - if (sendToFileSelectionCopyAction == null) { - sendToFileSelectionCopyAction = new AbstractAction() { - public void actionPerformed(ActionEvent e) { - sendToFileSelectionCopyPerformed(); - } - }; - } - return sendToFileSelectionCopyAction; - } - - /** - * @return retourne l'action du fichier permettant la recopie de la partie - * selectionnee de la matrice depuis le fichier - */ - public Action getSendToFileCurrentPasteAction() { - if (sendToFileCurrentPasteAction == null) { - sendToFileCurrentPasteAction = new AbstractAction() { - public void actionPerformed(ActionEvent e) { - sendToFileCurrentPastePerformed(); - } - }; - } - return sendToFileCurrentPasteAction; - } - - private void sendToFileAllCopyPerformed() { - try { - Writer writer = getFileChooserWriter(); - if (writer != null) { - getMatrix().exportCSV(writer, withSemantics.getState()); - writer.close(); - matrixEditor.repaint(); - } - } catch (Exception e) { - JOptionPane.showMessageDialog(matrixEditor, - _("lutinmatrix.error.file.write"), _("lutinmatrix.error"), - JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); - } - } - - private void sendToFileAllPastePerformed() { - try { - Reader reader = getFileChooserReader(); - if (reader != null) { // cancel - getMatrix().importCSV(reader, new int[] { 0, 0 }); - reader.close(); - matrixEditor.fireEvent(); - matrixEditor.repaint(); - } - } catch (Exception e) { - JOptionPane.showMessageDialog(matrixEditor, - _("lutinmatrix.error.file.read"), _("lutinmatrix.error"), - JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); - } - } - - private void sendToFileSelectionCopyPerformed() { - try { - Writer writer = getFileChooserWriter(); - if (writer != null) { - getSelectedMatrix().exportCSV(writer, withSemantics.getState()); - writer.close(); - matrixEditor.repaint(); - } - } catch (Exception e) { - JOptionPane.showMessageDialog(matrixEditor, - _("lutinmatrix.error.file.write"), _("lutinmatrix.error"), - JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); - } - } - - private void sendToFileCurrentPastePerformed() { - try { - Reader reader = getFileChooserReader(); - if (reader != null) { // cancel - getMatrix().importCSV(reader, - getCoordinatesFirstCellSelectedMatrix()); - reader.close(); - matrixEditor.fireEvent(); - matrixEditor.repaint(); - } - } catch (Exception e) { - JOptionPane.showMessageDialog(matrixEditor, - _("lutinmatrix.error.file.read"), _("lutinmatrix.error"), - JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); - } - } -} Copied: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPopupMenu.java (from rev 143, nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/gui/MatrixPopupMenu.java) =================================================================== --- nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPopupMenu.java (rev 0) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixPopupMenu.java 2009-05-16 19:21:04 UTC (rev 144) @@ -0,0 +1,573 @@ +/* *##% 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.nuiton.math.matrix.gui; + +import static org.nuiton.i18n.I18n._; + +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.StringSelection; +import java.awt.datatransfer.Transferable; +import java.awt.event.ActionEvent; +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JFileChooser; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPopupMenu; +import javax.swing.JSeparator; +import javax.swing.filechooser.FileFilter; + +import org.nuiton.math.matrix.MatrixND; +import org.nuiton.util.FileUtil; + +/** + * Ajout d'un menu contextuel sur la matrice dans l'editeur. + * + * Created: 22 mars 2006 12:11:46 + * + * @author ruchaud + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ +public class MatrixPopupMenu extends JPopupMenu { + + /** serialVersionUID. */ + private static final long serialVersionUID = 3349189688987885915L; + + private MatrixEditor matrixEditor; + private JFileChooser fileChooser; + + private JMenu sendToClipBoard; + private JMenu sendToFile; + + private JCheckBoxMenuItem withSemantics; + + private Action sendToClipBoardAllCopyAction; + private Action sendToClipBoardAllPasteAction; + private Action sendToClipBoardSelectionCopyAction; + private Action sendToClipBoardCurrentPasteAction; + + private Action sendToFileAllCopyAction; + private Action sendToFileAllPasteAction; + private Action sendToFileSelectionCopyAction; + private Action sendToFileCurrentPasteAction; + + public MatrixPopupMenu(MatrixEditor matrixEditor) { + super(); + this.matrixEditor = matrixEditor; + + sendToClipBoard = getSendToClipBoard(); + sendToFile = getSendToFile(); + + withSemantics = new JCheckBoxMenuItem( + _("lutinmatrix.menu.option.semantics"), false); + + add(sendToClipBoard); + add(sendToFile); + add(new JSeparator()); + add(withSemantics); + } + + /** + * @return retourne le menu d'action pour le bloc note + */ + public JMenu getSendToClipBoard() { + if (sendToClipBoard == null) { + sendToClipBoard = new JMenu(_("lutinmatrix.menu.action")); + JMenuItem sendToClipBoardAllCopy = new JMenuItem( + _("lutinmatrix.menu.action.copy")); + JMenuItem sendToClipBoardAllPaste = new JMenuItem( + _("lutinmatrix.menu.action.paste")); + JMenuItem sendToClipBoardSelectionCopy = new JMenuItem( + _("lutinmatrix.menu.action.copy.selection")); + JMenuItem sendToClipBoardCurrentPaste = new JMenuItem( + _("lutinmatrix.menu.action.paste.position")); + + sendToClipBoard.add(sendToClipBoardAllCopy); + sendToClipBoard.add(sendToClipBoardAllPaste); + sendToClipBoard.add(new JSeparator()); + sendToClipBoard.add(sendToClipBoardSelectionCopy); + sendToClipBoard.add(sendToClipBoardCurrentPaste); + + sendToClipBoardAllCopy + .addActionListener(getSendToClipBoardAllCopyAction()); + sendToClipBoardAllPaste + .addActionListener(getSendToClipBoardAllPasteAction()); + sendToClipBoardSelectionCopy + .addActionListener(getSendToClipBoardSelectionCopyAction()); + sendToClipBoardCurrentPaste + .addActionListener(getSendToClipBoardCurrentPasteAction()); + } + + return sendToClipBoard; + } + + /** + * @return retourne le menu d'action pour les fichiers CSV + */ + public JMenu getSendToFile() { + if (sendToFile == null) { + sendToFile = new JMenu(_("lutinmatrix.menu.csv")); + JMenuItem sendToFileAllCopy = new JMenuItem( + _("lutinmatrix.menu.csv.export.file")); + JMenuItem sendToFileAllPaste = new JMenuItem( + _("lutinmatrix.menu.csv.import.file")); + JMenuItem sendToFileSelectionCopy = new JMenuItem( + _("lutinmatrix.menu.csv.export.selection")); + JMenuItem sendToFileCurrentPaste = new JMenuItem( + _("lutinmatrix.menu.csv.import.position")); + + sendToFile.add(sendToFileAllCopy); + sendToFile.add(sendToFileAllPaste); + sendToFile.add(new JSeparator()); + sendToFile.add(sendToFileSelectionCopy); + sendToFile.add(sendToFileCurrentPaste); + + sendToFileAllCopy.addActionListener(getSendToFileAllCopyAction()); + sendToFileAllPaste.addActionListener(getSendToFileAllPasteAction()); + sendToFileSelectionCopy + .addActionListener(getSendToFileSelectionCopyAction()); + sendToFileCurrentPaste + .addActionListener(getSendToFileCurrentPasteAction()); + } + + return sendToFile; + } + + /** + * @return retourne un writer du fichier choisi dans le selecteur de fichier + * @throws IOException + */ + private Writer getFileChooserWriter() throws IOException { + int returnVal = getFileChooser().showOpenDialog(matrixEditor); + if (returnVal == JFileChooser.APPROVE_OPTION) { + File selectedFile = getFileChooser().getSelectedFile(); + return FileUtil.getWriter(selectedFile); + } + return null; + } + + /** + * @return retourne un writer pour le bloc note + */ + private Writer getClipBoardWriter() { + return new StringWriter(); + } + + /** + * @return retourne un reader du fichier choisi dans le selecteur de fichier + * @throws IOException + */ + private Reader getFileChooserReader() throws IOException { + int returnVal = getFileChooser().showOpenDialog(matrixEditor); + if (returnVal == JFileChooser.APPROVE_OPTION) { + File selectedFile = getFileChooser().getSelectedFile(); + return FileUtil.getReader(selectedFile); + } + return null; + } + + /** + * @return retourne le contenu du bloc note sous la forme d'un reader + */ + private Reader getClipBoardReader() { + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + Transferable contents = clipboard.getContents(clipboard); + if (contents != null) { + try { + String data = (String) contents + .getTransferData(DataFlavor.stringFlavor); + return new StringReader(data); + } catch (Exception e) { + JOptionPane.showMessageDialog(matrixEditor, + "Impossible de coller les données", "Warning", + JOptionPane.WARNING_MESSAGE); + e.printStackTrace(); + } + } + return null; + } + + /** + * Desactive le menu si la matrice ne supporte pas le mode CSV + */ + protected void firePopupMenuWillBecomeVisible() { + if (!getMatrix().isSupportedCSV()) { + sendToClipBoard.setEnabled(false); + sendToFile.setEnabled(false); + } else { + sendToClipBoard.setEnabled(true); + sendToFile.setEnabled(true); + } + super.firePopupMenuWillBecomeVisible(); + } + + /** + * @return Matrice en cours de saisie dans l'editeur + */ + private MatrixND getMatrix() { + return matrixEditor.getMatrix(); + } + + /** + * @return la sous matrice en cours de saisie dans l'editeur c'est a dire la + * partie selectionnee + */ + private MatrixND getSelectedMatrix() { + int beginSelectedColumn = matrixEditor.getTable().getSelectedColumn(); + int nbSelectedColumn = matrixEditor.getTable().getSelectedColumnCount(); + + /* Prend en compte le décalage des lignes par rapport aux dimenssions */ + int nbColumnDimRow = matrixEditor.getMatrix().getNbDim() - 1; + beginSelectedColumn -= nbColumnDimRow; + if (beginSelectedColumn < 0) { + beginSelectedColumn = 0; + nbSelectedColumn -= nbColumnDimRow; + } + + int beginSelectedRow = matrixEditor.getTable().getSelectedRow() - 1; + int nbSelectedRow = matrixEditor.getTable().getSelectedRowCount(); + + if (getMatrix().getNbDim() == 1) { + return matrixEditor.getMatrix().getSubMatrix(0, + beginSelectedColumn, nbSelectedColumn); + } else { + return matrixEditor.getMatrix().getSubMatrix(0, beginSelectedRow, + nbSelectedRow).getSubMatrix(1, beginSelectedColumn, + nbSelectedColumn); + } + } + + /** + * @return retourne les coordonnees de la première cellule selectionnee + */ + private int[] getCoordinatesFirstCellSelectedMatrix() { + int selectedColumn = matrixEditor.getTable().getSelectedColumn(); + + /* Prend en compte le décalage des lignes par rapport aux dimenssions */ + int nbColumnDimRow = matrixEditor.getMatrix().getNbDim() - 1; + selectedColumn -= nbColumnDimRow; + if (selectedColumn < 0) { + selectedColumn = 0; + } + + int selectedRow = matrixEditor.getTable().getSelectedRow() - 1; + + return new int[] { selectedRow, selectedColumn }; + } + + /** + * @return Selecteur de fichier CSV + */ + private JFileChooser getFileChooser() { + if (fileChooser == null) { + fileChooser = new JFileChooser(); + FileFilter filter = new FileFilter() { + public boolean accept(File pathname) { + if (pathname.isDirectory()) { + return true; + } + + String extension = FileUtil.extension(pathname); + if (extension != null) { + if (extension.equals("csv")) { + return true; + } else { + return false; + } + } + + return false; + } + + public String getDescription() { + return "Texte CSV (*.csv)"; + } + }; + fileChooser.setFileFilter(filter); + } + return fileChooser; + } + + /** + * @return retourne l'action du bloc note permettant la copie entere de la + * matrice + */ + public Action getSendToClipBoardAllCopyAction() { + if (sendToClipBoardAllCopyAction == null) { + sendToClipBoardAllCopyAction = new AbstractAction() { + public void actionPerformed(ActionEvent e) { + sendToClipBoardAllCopyPerformed(); + } + }; + } + return sendToClipBoardAllCopyAction; + } + + /** + * @return retourne l'action du bloc note permettant la recopie entere de la + * matrice depuis le bloc note + */ + public Action getSendToClipBoardAllPasteAction() { + if (sendToClipBoardAllPasteAction == null) { + sendToClipBoardAllPasteAction = new AbstractAction() { + public void actionPerformed(ActionEvent e) { + sendToClipBoardAllPastePerformed(); + } + }; + } + return sendToClipBoardAllPasteAction; + } + + /** + * @return retourne l'action du bloc note permettant la copie de la partie + * selectionnee + */ + public Action getSendToClipBoardSelectionCopyAction() { + if (sendToClipBoardSelectionCopyAction == null) { + sendToClipBoardSelectionCopyAction = new AbstractAction() { + public void actionPerformed(ActionEvent e) { + sendToClipBoardSelectionCopyPerformed(); + } + }; + } + return sendToClipBoardSelectionCopyAction; + } + + /** + * @return retourne l'action du bloc note permettant la recopie de la partie + * selectionnee de la matrice depuis le bloc note + */ + public Action getSendToClipBoardCurrentPasteAction() { + if (sendToClipBoardCurrentPasteAction == null) { + sendToClipBoardCurrentPasteAction = new AbstractAction() { + public void actionPerformed(ActionEvent e) { + sendToClipBoardCurrentPastePerformed(); + } + }; + } + return sendToClipBoardCurrentPasteAction; + } + + private void sendToClipBoardAllCopyPerformed() { + try { + Writer writer = getClipBoardWriter(); + getMatrix().exportCSV(writer, withSemantics.getState()); + StringSelection contents = new StringSelection(writer.toString()); + Clipboard clipboard = Toolkit.getDefaultToolkit() + .getSystemClipboard(); + clipboard.setContents(contents, contents); + writer.close(); + matrixEditor.repaint(); + } catch (Exception e) { + JOptionPane.showMessageDialog(matrixEditor, + _("lutinmatrix.error.clipboard.write"), + _("lutinmatrix.error"), JOptionPane.ERROR_MESSAGE); + e.printStackTrace(); + } + } + + private void sendToClipBoardAllPastePerformed() { + try { + Reader reader = getClipBoardReader(); + getMatrix().importCSV(reader, new int[] { 0, 0 }); + reader.close(); + matrixEditor.fireEvent(); + matrixEditor.repaint(); + } catch (Exception e) { + JOptionPane.showMessageDialog(matrixEditor, + _("lutinmatrix.error.clipboard.read"), + _("lutinmatrix.error"), JOptionPane.ERROR_MESSAGE); + e.printStackTrace(); + } + } + + private void sendToClipBoardSelectionCopyPerformed() { + try { + Writer writer = getClipBoardWriter(); + getSelectedMatrix().exportCSV(writer, withSemantics.getState()); + StringSelection contents = new StringSelection(writer.toString()); + Clipboard clipboard = Toolkit.getDefaultToolkit() + .getSystemClipboard(); + clipboard.setContents(contents, contents); + writer.close(); + matrixEditor.repaint(); + } catch (Exception e) { + JOptionPane.showMessageDialog(matrixEditor, + _("lutinmatrix.error.clipboard.write"), + _("lutinmatrix.error"), JOptionPane.ERROR_MESSAGE); + e.printStackTrace(); + } + } + + private void sendToClipBoardCurrentPastePerformed() { + try { + Reader reader = getClipBoardReader(); + getMatrix().importCSV(reader, + getCoordinatesFirstCellSelectedMatrix()); + reader.close(); + matrixEditor.fireEvent(); + matrixEditor.repaint(); + } catch (Exception e) { + JOptionPane.showMessageDialog(matrixEditor, + _("lutinmatrix.error.clipboard.read"), + _("lutinmatrix.error"), JOptionPane.ERROR_MESSAGE); + e.printStackTrace(); + } + } + + /** + * @return retourne l'action du fichier permettant la copie entere de la + * matrice + */ + public Action getSendToFileAllCopyAction() { + if (sendToFileAllCopyAction == null) { + sendToFileAllCopyAction = new AbstractAction() { + public void actionPerformed(ActionEvent e) { + sendToFileAllCopyPerformed(); + } + }; + } + return sendToFileAllCopyAction; + } + + /** + * @return retourne l'action du fichier permettant la recopie entere de la + * matrice depuis le fichier + */ + public Action getSendToFileAllPasteAction() { + if (sendToFileAllPasteAction == null) { + sendToFileAllPasteAction = new AbstractAction() { + public void actionPerformed(ActionEvent e) { + sendToFileAllPastePerformed(); + } + }; + } + return sendToFileAllPasteAction; + } + + /** + * @return retourne l'action du fichier permettant la copie de la partie + * selectionnee + */ + public Action getSendToFileSelectionCopyAction() { + if (sendToFileSelectionCopyAction == null) { + sendToFileSelectionCopyAction = new AbstractAction() { + public void actionPerformed(ActionEvent e) { + sendToFileSelectionCopyPerformed(); + } + }; + } + return sendToFileSelectionCopyAction; + } + + /** + * @return retourne l'action du fichier permettant la recopie de la partie + * selectionnee de la matrice depuis le fichier + */ + public Action getSendToFileCurrentPasteAction() { + if (sendToFileCurrentPasteAction == null) { + sendToFileCurrentPasteAction = new AbstractAction() { + public void actionPerformed(ActionEvent e) { + sendToFileCurrentPastePerformed(); + } + }; + } + return sendToFileCurrentPasteAction; + } + + private void sendToFileAllCopyPerformed() { + try { + Writer writer = getFileChooserWriter(); + if (writer != null) { + getMatrix().exportCSV(writer, withSemantics.getState()); + writer.close(); + matrixEditor.repaint(); + } + } catch (Exception e) { + JOptionPane.showMessageDialog(matrixEditor, + _("lutinmatrix.error.file.write"), _("lutinmatrix.error"), + JOptionPane.ERROR_MESSAGE); + e.printStackTrace(); + } + } + + private void sendToFileAllPastePerformed() { + try { + Reader reader = getFileChooserReader(); + if (reader != null) { // cancel + getMatrix().importCSV(reader, new int[] { 0, 0 }); + reader.close(); + matrixEditor.fireEvent(); + matrixEditor.repaint(); + } + } catch (Exception e) { + JOptionPane.showMessageDialog(matrixEditor, + _("lutinmatrix.error.file.read"), _("lutinmatrix.error"), + JOptionPane.ERROR_MESSAGE); + e.printStackTrace(); + } + } + + private void sendToFileSelectionCopyPerformed() { + try { + Writer writer = getFileChooserWriter(); + if (writer != null) { + getSelectedMatrix().exportCSV(writer, withSemantics.getState()); + writer.close(); + matrixEditor.repaint(); + } + } catch (Exception e) { + JOptionPane.showMessageDialog(matrixEditor, + _("lutinmatrix.error.file.write"), _("lutinmatrix.error"), + JOptionPane.ERROR_MESSAGE); + e.printStackTrace(); + } + } + + private void sendToFileCurrentPastePerformed() { + try { + Reader reader = getFileChooserReader(); + if (reader != null) { // cancel + getMatrix().importCSV(reader, + getCoordinatesFirstCellSelectedMatrix()); + reader.close(); + matrixEditor.fireEvent(); + matrixEditor.repaint(); + } + } catch (Exception e) { + JOptionPane.showMessageDialog(matrixEditor, + _("lutinmatrix.error.file.read"), _("lutinmatrix.error"), + JOptionPane.ERROR_MESSAGE); + e.printStackTrace(); + } + } +} Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixTableModel.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/gui/MatrixTableModel.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixTableModel.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,12 +15,12 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix.gui; +package org.nuiton.math.matrix.gui; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; -import org.codelutin.math.matrix.MatrixND; +import org.nuiton.math.matrix.MatrixND; /** * MatrixTableModel. Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixTableModelLinear.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/gui/MatrixTableModelLinear.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixTableModelLinear.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix.gui; +package org.nuiton.math.matrix.gui; import java.awt.Color; import java.awt.Component; @@ -33,8 +33,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.codelutin.math.matrix.MatrixIterator; -import org.codelutin.math.matrix.MatrixND; +import org.nuiton.math.matrix.MatrixIterator; +import org.nuiton.math.matrix.MatrixND; /** * MatrixTableModelLinear. Modified: nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixTableModelND.java =================================================================== --- nuiton-matrix/trunk/src/main/java/org/codelutin/math/matrix/gui/MatrixTableModelND.java 2009-05-16 15:40:30 UTC (rev 142) +++ nuiton-matrix/trunk/src/main/java/org/nuiton/math/matrix/gui/MatrixTableModelND.java 2009-05-16 19:21:04 UTC (rev 144) @@ -15,7 +15,7 @@ * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ -package org.codelutin.math.matrix.gui; +package org.nuiton.math.matrix.gui; import java.awt.Color; import java.awt.Component; @@ -31,8 +31,8 @@ import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; -import org.codelutin.math.matrix.MatrixException; -import org.codelutin.math.matrix.MatrixND; +import org.nuiton.math.matrix.MatrixException; +import org.nuiton.math.matrix.MatrixND; /** * Extension de AbstractTableModel pour definir un TableModel avec une Modified: nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/BasicMatrixBigTest.java =================================================================== --- nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/BasicMatrixBigTest.java 2009-05-16 18:41:40 UTC (rev 143) +++ nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/BasicMatrixBigTest.java 2009-05-16 19:21:04 UTC (rev 144) @@ -17,8 +17,6 @@ package org.nuiton.math.matrix; -import org.codelutin.math.matrix.*; - /** * BasicMatrixBigTest. * @@ -32,6 +30,7 @@ */ public class BasicMatrixBigTest extends BasicMatrixTest { // BasicMatrixBigTest + @Override public MatrixFactory getFactory() throws Exception { return MatrixFactory.getInstance(FloatBigVector.class); } Modified: nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/BasicMatrixTest.java =================================================================== --- nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/BasicMatrixTest.java 2009-05-16 18:41:40 UTC (rev 143) +++ nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/BasicMatrixTest.java 2009-05-16 19:21:04 UTC (rev 144) @@ -17,7 +17,6 @@ package org.nuiton.math.matrix; -import org.codelutin.math.matrix.*; import java.util.Arrays; import java.util.NoSuchElementException; Modified: nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/FloatVectorTest.java =================================================================== --- nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/FloatVectorTest.java 2009-05-16 18:41:40 UTC (rev 143) +++ nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/FloatVectorTest.java 2009-05-16 19:21:04 UTC (rev 144) @@ -17,7 +17,6 @@ package org.nuiton.math.matrix; -import org.codelutin.math.matrix.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Assert; Modified: nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/ImportExportMatrixTest.java =================================================================== --- nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/ImportExportMatrixTest.java 2009-05-16 18:41:40 UTC (rev 143) +++ nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/ImportExportMatrixTest.java 2009-05-16 19:21:04 UTC (rev 144) @@ -17,7 +17,6 @@ package org.nuiton.math.matrix; -import org.codelutin.math.matrix.*; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; Modified: nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/MatrixHelperTest.java =================================================================== --- nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/MatrixHelperTest.java 2009-05-16 18:41:40 UTC (rev 143) +++ nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/MatrixHelperTest.java 2009-05-16 19:21:04 UTC (rev 144) @@ -17,7 +17,6 @@ package org.nuiton.math.matrix; -import org.codelutin.math.matrix.*; import java.util.List; import org.apache.commons.logging.Log; Modified: nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/MatrixNDTest.java =================================================================== --- nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/MatrixNDTest.java 2009-05-16 18:41:40 UTC (rev 143) +++ nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/MatrixNDTest.java 2009-05-16 19:21:04 UTC (rev 144) @@ -17,7 +17,6 @@ package org.nuiton.math.matrix; -import org.codelutin.math.matrix.*; import java.io.IOException; import java.io.StreamTokenizer; import java.io.StringReader; Modified: nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/MatrixStringEncoderTest.java =================================================================== --- nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/MatrixStringEncoderTest.java 2009-05-16 18:41:40 UTC (rev 143) +++ nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/MatrixStringEncoderTest.java 2009-05-16 19:21:04 UTC (rev 144) @@ -17,7 +17,6 @@ package org.nuiton.math.matrix; -import org.codelutin.math.matrix.*; import java.io.Serializable; import java.util.ArrayList; import java.util.List; Modified: nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/PerfTest.java =================================================================== --- nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/PerfTest.java 2009-05-16 18:41:40 UTC (rev 143) +++ nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/PerfTest.java 2009-05-16 19:21:04 UTC (rev 144) @@ -17,7 +17,6 @@ package org.nuiton.math.matrix; -import org.codelutin.math.matrix.*; import java.util.ArrayList; import java.util.List; Modified: nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/SubMatrixTest.java =================================================================== --- nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/SubMatrixTest.java 2009-05-16 18:41:40 UTC (rev 143) +++ nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/SubMatrixTest.java 2009-05-16 19:21:04 UTC (rev 144) @@ -17,7 +17,6 @@ package org.nuiton.math.matrix; -import org.codelutin.math.matrix.*; import java.util.Arrays; import java.util.List; Modified: nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/gui/MatrixTableModelTest.java =================================================================== --- nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/gui/MatrixTableModelTest.java 2009-05-16 18:41:40 UTC (rev 143) +++ nuiton-matrix/trunk/src/test/java/org/nuiton/math/matrix/gui/MatrixTableModelTest.java 2009-05-16 19:21:04 UTC (rev 144) @@ -17,12 +17,11 @@ package org.nuiton.math.matrix.gui; -import org.codelutin.math.matrix.gui.*; import java.util.Arrays; import java.util.List; -import org.codelutin.math.matrix.MatrixFactory; -import org.codelutin.math.matrix.MatrixND; +import org.nuiton.math.matrix.MatrixFactory; +import org.nuiton.math.matrix.MatrixND; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -48,16 +47,16 @@ */ @Before public void setUp() throws Exception { - List dim0 = Arrays.asList(new String[] { "dim0-0", "dim0-1", "dim0-2", + List<String> dim0 = Arrays.asList(new String[] { "dim0-0", "dim0-1", "dim0-2", "dim0-3" }); - List dim1 = Arrays.asList(new String[] { "dim1-0", "dim1-1" }); - List dim2 = Arrays.asList(new String[] { "dim2-0", "dim2-1" }); - List dim3 = Arrays.asList(new String[] { "dim3-0", "dim3-1", "dim3-2", + List<String> dim1 = Arrays.asList(new String[] { "dim1-0", "dim1-1" }); + List<String> dim2 = Arrays.asList(new String[] { "dim2-0", "dim2-1" }); + List<String> dim3 = Arrays.asList(new String[] { "dim3-0", "dim3-1", "dim3-2", "dim3-3" }); - List dim4 = Arrays + List<String> dim4 = Arrays .asList(new String[] { "dim4-0", "dim4-1", "dim4-2" }); mat = MatrixFactory.getInstance().create("mat", - new List[] { dim0, dim1, dim2, dim3, dim4 }, + new List<?>[] { dim0, dim1, dim2, dim3, dim4 }, new String[] { "dim0", "dim1", "dim2", "dim3", "dim4" }); model = new MatrixTableModelND(mat); }
participants (1)
-
tchemit@users.labs.libre-entreprise.org