[Lutinmatrix-commits] r64 - in trunk/lutinmatrix: . src src/main src/main/java src/main/java/org src/main/java/org/codelutin src/main/java/org/codelutin/math src/main/java/org/codelutin/math/matrix src/main/java/org/codelutin/math/matrix/gui src/main/resources src/test src/test/java src/test/java/org src/test/java/org/codelutin src/test/java/org/codelutin/math src/test/java/org/codelutin/math/matrix src/test/java/org/codelutin/math/matrix/gui
Author: bpoussin Date: 2008-09-01 09:24:33 +0000 (Mon, 01 Sep 2008) New Revision: 64 Added: trunk/lutinmatrix/src/main/ trunk/lutinmatrix/src/main/java/ trunk/lutinmatrix/src/main/java/org/ trunk/lutinmatrix/src/main/java/org/codelutin/ trunk/lutinmatrix/src/main/java/org/codelutin/math/ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/AbstractMatrixND.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/BasicMatrix.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/BasicMatrixIterator.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/DimensionHelper.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/DoubleBigVector.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/DoubleVector.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/FloatBigVector.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/FloatVector.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MapFunction.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixEncoder.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixException.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixFactory.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixHelper.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixIterator.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixIteratorImpl.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixND.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixNDImpl.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/SemanticList.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/SubMatrix.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/Vector.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixPanelEditor.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixPanelEvent.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixPanelListener.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixPopupMenu.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixTableModel.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixTableModelLinear.java trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixTableModelND.java trunk/lutinmatrix/src/main/resources/ trunk/lutinmatrix/src/main/resources/i18n/ trunk/lutinmatrix/src/test/java/ trunk/lutinmatrix/src/test/java/org/ trunk/lutinmatrix/src/test/java/org/codelutin/ trunk/lutinmatrix/src/test/java/org/codelutin/math/ trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/ trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/BasicMatrixBigTest.java trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/BasicMatrixTest.java trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/FloatVectorTest.java trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/ImportExportMatrixTest.java trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/MatrixEncoderDecoderTest.java trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/MatrixHelperTest.java trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/MatrixNDTest.java trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/PerfTest.java trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/SubMatrixTest.java trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/gui/ trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/gui/MatrixTableModelTest.java Removed: trunk/lutinmatrix/lutincheckstyle.xml trunk/lutinmatrix/lutinheader.txt trunk/lutinmatrix/lutinproject.xml trunk/lutinmatrix/maven.xml trunk/lutinmatrix/profiles.xml trunk/lutinmatrix/project.properties trunk/lutinmatrix/project.xml Modified: trunk/lutinmatrix/ trunk/lutinmatrix/README trunk/lutinmatrix/changelog Log: - modif de toute l'arbo pour prendre la norme maven - passage en 1.0 - modif dependance Property changes on: trunk/lutinmatrix ___________________________________________________________________ Name: svn:ignore + target Modified: trunk/lutinmatrix/README =================================================================== --- trunk/lutinmatrix/README 2008-09-01 09:22:15 UTC (rev 63) +++ trunk/lutinmatrix/README 2008-09-01 09:24:33 UTC (rev 64) @@ -2,20 +2,20 @@ ------------ genapp - pour generer le skelette du r�pertoire de projet + pour generer le skelette du répertoire de projet jar - pour compiler et g�n�rer un jar + pour compiler et générer un jar uberjar - pour g�n�rer un jar qui contient toutes ses d�pendances que l'on peut - ex�cuter avec un java -jar ... + pour générer un jar qui contient toutes ses dépendances que l'on peut + exécuter avec un java -jar ... site:deploy - pour mettre � jour les pages web du site + pour mettre à jour les pages web du site jar:deploy - pour mettre � jour la version dans le repository + pour mettre à jour la version dans le repository jar:deploy-snapshot pour mettre en place une nouvelle version snapshot dans le repository @@ -34,20 +34,20 @@ Installation de maven --------------------- -R�cup�rer la derni�re version de maven sur http://maven.apache.org -Installer le en le d�compressant dans un r�pertoire, par exemple /opt +Récupérer la dernière version de maven sur http://maven.apache.org +Installer le en le décompressant dans un répertoire, par exemple /opt -Ajouter le r�pertoire de bin maven dans votre PATH (peut-etre dans le +Ajouter le répertoire de bin maven dans votre PATH (peut-etre dans le fichier /etc/profile ou ~/.bash_profile):: export PATH=$PATH:/opt/maven/bin -modifier les droits du r�pertoire /opt/maven/plugin si vous souhaitez +modifier les droits du répertoire /opt/maven/plugin si vous souhaitez installer de nouveau plugin en tant qu'uilisateur normal et non pas seulement en root. -Par exemple cr�ez un group dev dans lequel vous mettrez tous les -d�veloppeurs qui devront pouvoir ajouter des plugins � votre installation +Par exemple créez un group dev dans lequel vous mettrez tous les +développeurs qui devront pouvoir ajouter des plugins à votre installation maven. ensuite:: @@ -56,16 +56,16 @@ chmod g+w /opt/maven/plugin chmod go+s /opt/maven/plugin -Maven d�compresse les plugins et download les librairies dans un r�pertoire. -Normalement ce r�pertoire est dans le HOME de chaque utilisateur, mais il -peut tr�s bien �tre partag�, et cela permet de ne pas avoir un r�pertoire de -plusieurs m�ga dans son HOME. +Maven décompresse les plugins et download les librairies dans un répertoire. +Normalement ce répertoire est dans le HOME de chaque utilisateur, mais il +peut très bien être partagé, et cela permet de ne pas avoir un répertoire de +plusieurs méga dans son HOME. -Pour cela ajout� dans votre fichier ~/build.properties ceci:: +Pour cela ajouté dans votre fichier ~/build.properties ceci:: maven.home.local=/var/cache/maven -Il faut ensuite cr�er ce r�pertoire et lui mettre les bons droits:: +Il faut ensuite créer ce répertoire et lui mettre les bons droits:: mkdir -p /var/cache/maven chown .dev /var/cache/maven @@ -81,7 +81,7 @@ maven.checkstyle.format=sun - # pour que le home ne soit pas submerger de .jar �norme + # pour que le home ne soit pas submerger de .jar énorme maven.home.local=/var/cache/maven # pour la creation de nouveau projet @@ -97,10 +97,10 @@ -------------------------- On voit dans l'exemple de fichier build.properties ci-dessus que le template -utilis� est topia. Pour cr�er ou ajouter un template il faut le faire dans -le r�pertoire ~/.maven/template/nom_du_template +utilisé est topia. Pour créer ou ajouter un template il faut le faire dans +le répertoire ~/.maven/template/nom_du_template -par exemple vous pouvez r�cuperer le template topia et l'installer +par exemple vous pouvez récuperer le template topia et l'installer (http://lutinbuilder.labs.libre-entreprise.org/maven/template/topia-0.1.tar.g...) TODO @@ -111,7 +111,7 @@ fermeture des forums, ...) labs:release - pour publier une nouvelle version sur labs (mise � jour du site web, + pour publier une nouvelle version sur labs (mise à jour du site web, enregistrement des fichiers dowloads, ajout du jar dans le repository maven, update du XXX-last.jar pointant vers cette derniere version. Modified: trunk/lutinmatrix/changelog =================================================================== --- trunk/lutinmatrix/changelog 2008-09-01 09:22:15 UTC (rev 63) +++ trunk/lutinmatrix/changelog 2008-09-01 09:24:33 UTC (rev 64) @@ -1,4 +1,5 @@ -ver- +ver-0-17 + * suppress MatrixNDXMLConverter.java and MatrixXMLDelegator.java * add reduceDims method to reduce on specific dimension * add sumAll to compute the sum on all value in matrix Deleted: trunk/lutinmatrix/lutincheckstyle.xml =================================================================== --- trunk/lutinmatrix/lutincheckstyle.xml 2008-09-01 09:22:15 UTC (rev 63) +++ trunk/lutinmatrix/lutincheckstyle.xml 2008-09-01 09:24:33 UTC (rev 64) @@ -1,189 +0,0 @@ -<?xml version="1.0" encoding="ISO-8859-1"?> -<!DOCTYPE module PUBLIC - "-//Puppy Crawl//DTD Check Configuration 1.1//EN" - "http://www.puppycrawl.com/dtds/configuration_1_1.dtd"> - -<!-- - - Checkstyle configuration that checks the sun coding conventions from: - - - the Java Language Specification at - http://java.sun.com/docs/books/jls/second_edition/html/index.html - - - the Sun Code Conventions at http://java.sun.com/docs/codeconv/ - - - the Javadoc guidelines at - http://java.sun.com/j2se/javadoc/writingdoccomments/index.html - - - the JDK Api documentation http://java.sun.com/j2se/docs/api/index.html - - - some best practices - - Checkstyle is very configurable. Be sure to read the documentation at - http://checkstyle.sf.net (or in your downloaded distribution). - - Most Checks are configurable, be sure to consult the documentation. - - To completely disable a check, just comment it out or delete it from the file. - - Finally, it is worth reading the documentation. - ---> - -<module name="Checker"> - - <!-- Checks that a package.html file exists for each package. --> - <!-- See http://checkstyle.sf.net/config_javadoc.html#PackageHtml --> - <module name="PackageHtml"/> - - <!-- Checks whether files end with a new line. --> - <!-- See http://checkstyle.sf.net/config_misc.html#NewlineAtEndOfFile --> - <module name="NewlineAtEndOfFile"/> - - <!-- Checks that property files contain the same keys. --> - <!-- See http://checkstyle.sf.net/config_misc.html#Translation --> - <module name="Translation"/> - - - <module name="TreeWalker"> - - <property name="cacheFile" value="${checkstyle.cache.file}"/> - - <!-- Checks for Javadoc comments. --> - <!-- See http://checkstyle.sf.net/config_javadoc.html --> - <module name="JavadocMethod"/> - <module name="JavadocType"/> - <module name="JavadocVariable"/> - - - <!-- Checks for Naming Conventions. --> - <!-- See http://checkstyle.sf.net/config_naming.html --> - <module name="ConstantName"/> - <module name="LocalFinalVariableName"/> - <module name="LocalVariableName"/> - <module name="MemberName"/> - <module name="MethodName"/> - <module name="PackageName"/> - <module name="ParameterName"/> - <module name="StaticVariableName"/> - <module name="TypeName"/> - - - <!-- Checks for Headers --> - <!-- See http://checkstyle.sf.net/config_header.html --> - <module name="Header"> - <!-- The follow property value demonstrates the ability --> - <!-- to have access to ANT properties. In this case it uses --> - <!-- the ${basedir} property to allow Checkstyle to be run --> - <!-- from any directory within a project. --> - <property name="headerFile" value="${checkstyle.header.file}"/> - <property name="ignoreLines" value="4,22,24,26,27,29,30"/> - </module> - - <!-- Following interprets the header file as regular expressions. --> - <!-- <module name="RegexpHeader"/> --> - - - <!-- Checks for imports --> - <!-- See http://checkstyle.sf.net/config_import.html --> - <module name="AvoidStarImport"/> - <module name="IllegalImport"/> <!-- defaults to sun.* packages --> - <module name="RedundantImport"/> - <module name="UnusedImports"/> - - - <!-- Checks for Size Violations. --> - <!-- See http://checkstyle.sf.net/config_sizes.html --> - <module name="FileLength"/> - <module name="LineLength"/> - <module name="MethodLength"/> - <module name="ParameterNumber"/> - - - <!-- Checks for whitespace --> - <!-- See http://checkstyle.sf.net/config_whitespace.html --> - <module name="EmptyForIteratorPad"/> - <module name="NoWhitespaceAfter"/> - <module name="NoWhitespaceBefore"/> - <module name="OperatorWrap"/> - <module name="ParenPad"/> - <module name="TabCharacter"/> - <module name="WhitespaceAfter"> - <property name="tokens" value="COMMA, SEMI"/> - </module> - <module name="WhitespaceAround"> - <property name="tokens" value="ASSIGN, BAND, BAND_ASSIGN, BOR, BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN, EQUAL, GE, GT, LAND, LCURLY, LE, LITERAL_ASSERT, LITERAL_RETURN, LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS, MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION, RCURLY, SL, SLIST, SL_ASSIGN, SR, SR_ASSIGN, STAR, STAR_ASSIGN"/> - <!-- BB: LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF, --> - </module> - - <!-- Modifier Checks --> - <!-- See http://checkstyle.sf.net/config_modifiers.html --> - <module name="ModifierOrder"/> - <module name="RedundantModifier"/> - - - <!-- Checks for blocks. You know, those {}'s --> - <!-- See http://checkstyle.sf.net/config_blocks.html --> - <module name="AvoidNestedBlocks"/> - <module name="EmptyBlock"/> - <module name="LeftCurly"> - <property name="option" value="eol"/> - </module> - <module name="NeedBraces"/> - <module name="RightCurly"/> - - - <!-- Checks for common coding problems --> - <!-- See http://checkstyle.sf.net/config_coding.html --> - <module name="AvoidInlineConditionals"/> - <module name="DoubleCheckedLocking"/> <!-- MY FAVOURITE --> - <module name="EmptyStatement"/> - <module name="EqualsHashCode"/> - <module name="HiddenField"> - <property name="ignoreConstructorParameter" value="true"/> - </module> - <module name="IllegalInstantiation"/> - <module name="InnerAssignment"/> - <module name="MagicNumber"/> - <module name="MissingSwitchDefault"/> - <module name="RedundantThrows"/> - <module name="SimplifyBooleanExpression"/> - <module name="SimplifyBooleanReturn"/> - <module name="SuperClone"/> - <module name="SuperFinalize"/> - <module name="PackageDeclaration"/> - <module name="ReturnCount"/> - <module name="DeclarationOrder"/> - <module name="ParameterAssignment"/> - <module name="DefaultComesLast"/> - <module name="FallThrough"/> -<!-- BB que dans le 3.5 :( <module name="MultipleStringLiterals"/> --> - <module name="MultipleVariableDeclarations"/> - - - - <!-- Checks for class design --> - <!-- See http://checkstyle.sf.net/config_design.html --> -<!-- BB <module name="DesignForExtension"/> --> - <module name="FinalClass"/> - <module name="HideUtilityClassConstructor"/> - <module name="InterfaceIsType"/> - <module name="VisibilityModifier"> - <property name="protectedAllowed" value="true"/> - </module> - - - <!-- Miscellaneous other checks. --> - <!-- See http://checkstyle.sf.net/config_misc.html --> - <module name="ArrayTypeStyle"/> -<!-- BB peut-�tre <module name="FinalParameters"/> --> - <module name="GenericIllegalRegexp"> - <property name="format" value="\s+$"/> - <property name="message" value="Line has trailing spaces."/> - </module> - <module name="TodoComment"/> - <module name="UpperEll"/> - - </module> - -</module> Deleted: trunk/lutinmatrix/lutinheader.txt =================================================================== --- trunk/lutinmatrix/lutinheader.txt 2008-09-01 09:22:15 UTC (rev 63) +++ trunk/lutinmatrix/lutinheader.txt 2008-09-01 09:24:33 UTC (rev 64) @@ -1,31 +0,0 @@ -/* *##% -* Copyright (C) 2002, 2003, 2004, 2005 Code Lutin, -* C�dric 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. -*##%*/ - -/* * -* <FILENAME.java> -* -* Created: <DATE> -* -* @author Benjamin Poussin <poussin@codelutin.com> -* @version $Revision$ -* -* Mise a jour: $Date$ -* par : $Author$ -*/ Deleted: trunk/lutinmatrix/lutinproject.xml =================================================================== --- trunk/lutinmatrix/lutinproject.xml 2008-09-01 09:22:15 UTC (rev 63) +++ trunk/lutinmatrix/lutinproject.xml 2008-09-01 09:24:33 UTC (rev 64) @@ -1,134 +0,0 @@ -<?xml version="1.0" encoding="ISO-8859-1"?> -<project> - - <!-- the version of maven's project object model --> - <pomVersion>3</pomVersion> - - <groupId>lutinlib</groupId> - - <!-- details about the organization that 'owns' the project --> - <organization> - <name>Code Lutin</name> - <url>http://www.codelutin.com/</url> - <logo>http://www.codelutin.com/cl-images/mini-lutin.png</logo> - </organization> - - <!-- the project home page --> - <url>http://labs.libre-entreprise.org/${pom.artifactId}</url> - - <issueTrackingUrl>http://labs.libre-entreprise.org/tracker/</issueTrackingUrl> - - <siteAddress>labs.libre-entreprise.org</siteAddress> - <siteDirectory>/home/groups/${pom.artifactId}/htdocs/</siteDirectory> - - <distributionSite>labs.libre-entreprise.org</distributionSite> - <distributionDirectory>/home/groups/lutinbuilder/htdocs/maven</distributionDirectory> - - <!-- the version control repository and http url for online access - the connection element has the form: - scm:<system>:<system specific connection string> --> - <repository> - <connection>scm:cvs:pserver:anonymous@cvs.labs.libre-entreprise.org:/cvsroot/${pom.artifactId}:${pom.artifactId}</connection> - <url>http://cvs.labs.libre-entreprise.org/cgi-bin/cvsweb.cgi/?cvsroot=${pom.artifactId}</url> - </repository> - - <!-- any mailing lists for the project --> - <mailingLists> - <mailingList> - <name>${pom.artifactId}-devel</name> - <subscribe>http://lists.labs.libre-entreprise.org/mailman/listinfo/${pom.artifactId}-devel</subscribe> - <unsubscribe>http://lists.labs.libre-entreprise.org/mailman/listinfo/${pom.artifactId}-devel</unsubscribe> - <archive>http://lists.labs.libre-entreprise.org/pipermail/${pom.artifactId}-devel/</archive> - </mailingList> - <mailingList> - <name>${pom.artifactId}-user</name> - <subscribe>http://lists.labs.libre-entreprise.org/mailman/listinfo/${pom.artifactId}-user</subscribe> - <unsubscribe>http://lists.labs.libre-entreprise.org/mailman/listinfo/${pom.artifactId}-user</unsubscribe> - <archive>http://lists.labs.libre-entreprise.org/pipermail/${pom.artifactId}-user/</archive> - </mailingList> - </mailingLists> - - <licenses> - <license> - <name>GPL</name> - <url>http://www.gnu.org/copyleft/gpl.html</url> - <distribution>repo</distribution> - </license> - </licenses> - - <!-- who the developers are for the project --> - <developers> - <developer> - <name>Benjamin Poussin</name> - <id>bpoussin</id> - <email>poussin@codelutin.com</email> - <organization>Code Lutin</organization> - <timezone>+2</timezone> - <roles> - <role>D�veloppeur</role> - <role>Debian packager</role> - </roles> - </developer> - <developer> - <name>C�dric Pineau</name> - <id>pineau</id> - <email>pineau@codelutin.com</email> - <organization>Code Lutin</organization> - <timezone>+2</timezone> - <roles> - <role>D�veloppeur</role> - </roles> - </developer> - </developers> - - - <!-- jar files the project is dependent on --> - <dependencies/> - - <reports> - <report>maven-changelog-plugin</report> - <report>maven-changes-plugin</report> - <report>maven-checkstyle-plugin</report> - <report>maven-developer-activity-plugin</report> - <report>maven-file-activity-plugin</report> - <report>maven-javadoc-plugin</report> - <report>maven-jdepend-plugin</report> - <report>maven-junit-report-plugin</report> - <report>maven-jxr-plugin</report> - <report>maven-license-plugin</report> -<!-- <report>maven-linkcheck-plugin</report> --> - <report>maven-pmd-plugin</report> - <report>maven-statcvs-plugin</report> - <report>maven-simian-plugin</report> - <report>maven-tasklist-plugin</report> - </reports> - - <!-- build information for the project --> - <build> - <nagEmailAddress>poussin+${pom.artifactId}@codelutin.org</nagEmailAddress> - <sourceDirectory>${maven.src.dir}/java</sourceDirectory> - <unitTestSourceDirectory>${maven.src.dir}/test</unitTestSourceDirectory> - - <unitTest> - <includes> - <include>**/*Test.java</include> - </includes> - <excludes> - <exclude>**/NaughtyTest.java</exclude> - </excludes> - </unitTest> - - <resources> - <resource> - <directory>${maven.src.dir}/resources</directory> - <includes> - <include>**/*.jpg</include> - <include>**/*.xml</include> - </includes> - </resource> - </resources> - - </build> - -</project> - Deleted: trunk/lutinmatrix/maven.xml =================================================================== --- trunk/lutinmatrix/maven.xml 2008-09-01 09:22:15 UTC (rev 63) +++ trunk/lutinmatrix/maven.xml 2008-09-01 09:24:33 UTC (rev 64) @@ -1,22 +0,0 @@ -<?xml version="1.0" encoding="ISO-8859-15"?> - -<project default="jar:jar" - xmlns:j="jelly:core" - xmlns:ant="jelly:ant" - xmlns:u="jelly:util"> - - <preGoal name="java:compile"> - <attainGoal name="topia:build"/> - </preGoal> - - <preGoal name="site"> - <attainGoal name="topia:docs"/> - </preGoal> - - <postGoal name="jar:jar"> - <ant:signjar keystore="../CodeLutinKeystore" alias="CodeLutin" storepass="codelutin"> - <ant:fileset dir="target" includes="lutin*-*.jar"/> - </ant:signjar> - </postGoal> - -</project> Deleted: trunk/lutinmatrix/profiles.xml =================================================================== --- trunk/lutinmatrix/profiles.xml 2008-09-01 09:22:15 UTC (rev 63) +++ trunk/lutinmatrix/profiles.xml 2008-09-01 09:24:33 UTC (rev 64) @@ -1,24 +0,0 @@ -<?xml version="1.0" encoding="ISO-8859-1"?> -<settings> - <profiles> - <profile> - <id>project</id> - - <activation> - <activeByDefault>true</activeByDefault> - </activation> - - <properties> - <!--Source base dir--> - <maven.src.dir>${basedir}/src</maven.src.dir> - - <!--Compile with ?--> - <maven.compile.source>1.5</maven.compile.source> - <maven.compile.target>1.5</maven.compile.target> - - <!--Main class in JAR --> - <maven.jar.main.class>org.codelutin.math.matrix.gui.MatrixPanelEditor</maven.jar.main.class> - </properties> - </profile> - </profiles> -</settings> Deleted: trunk/lutinmatrix/project.properties =================================================================== --- trunk/lutinmatrix/project.properties 2008-09-01 09:22:15 UTC (rev 63) +++ trunk/lutinmatrix/project.properties 2008-09-01 09:24:33 UTC (rev 64) @@ -1,6 +0,0 @@ -maven.src.dir=${basedir}/target/src-build -maven.jar.mainclass=org.codelutin.math.matrix.gui.MatrixPanelEditor - -# Checkstyle Report -maven.checkstyle.header.file=${basedir}/lutinheader.txt -maven.checkstyle.properties=${basedir}/lutincheckstyle.xml Deleted: trunk/lutinmatrix/project.xml =================================================================== --- trunk/lutinmatrix/project.xml 2008-09-01 09:22:15 UTC (rev 63) +++ trunk/lutinmatrix/project.xml 2008-09-01 09:24:33 UTC (rev 64) @@ -1,74 +0,0 @@ -<?xml version="1.0" encoding="ISO-8859-15"?> -<project> - - <extend>${basedir}/lutinproject.xml</extend> - - <!-- a unique name for this project --> - <id>lutinmatrix</id> - - <!-- a short but descriptive name for the project --> - <name>Lutin Matrix</name> - - <!-- The version of the project under development, e.g. - 1.1, 1.2, 2.0-SNAPSHOT --> - <currentVersion>0.12</currentVersion> - - <!-- the year the project started --> - <inceptionYear>2004</inceptionYear> - <package>org.codelutin.math.matrix</package> - <logo>http://www.codelutin.com/cl-images/mini-lutin.png</logo> - <shortDescription>Librairie de matrice multi-dimensions.</shortDescription> - <description>Librairie de matrice multi-dimensions. Cette librairie permet de g�rer les matrices de double.</description> - - <issueTrackingUrl>http://labs.libre-entreprise.org/tracker/?group_id=63</issueTrackingUrl> - - <dependencies> - <dependency> - <groupId>lutinlib</groupId> - <artifactId>lutini18n</artifactId> - <version>0.17</version> - </dependency> - <dependency> - <groupId>lutinlib</groupId> - <artifactId>lutinutil</artifactId> - <version>0.18</version> - </dependency> - <dependency> - <groupId>commons-primitives</groupId> - <artifactId>commons-primitives</artifactId> - <version>1.0</version> - </dependency> - <dependency> - <groupId>commons-logging</groupId> - <artifactId>commons-logging</artifactId> - <version>1.0.4</version> - </dependency> - <dependency> - <groupId>lutinlib</groupId> - <artifactId>lutinxml</artifactId> - <version>0.7</version> - </dependency> - <dependency> - <groupId>dom4j</groupId> - <artifactId>dom4j</artifactId> - <version>1.4</version> - </dependency> - <dependency> - <groupId>lutinlib</groupId> - <artifactId>topia</artifactId> - <version>0.35</version> - </dependency> - <dependency> - <groupId>commons-beanutils</groupId> - <artifactId>commons-beanutils-core</artifactId> - <version>1.7.0</version> - </dependency> - <dependency> - <groupId>commons-lang</groupId> - <artifactId>commons-lang</artifactId> - <version>2.0</version> - </dependency> - </dependencies> - -</project> - Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/AbstractMatrixND.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/AbstractMatrixND.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/AbstractMatrixND.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/AbstractMatrixND.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,940 @@ +/* *##% + * Copyright (C) 2002, 2003, 2004 Code Lutin, Cédric 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. + *##%*/ + +/* * + * AbstractMatrixND.java + * + * Created: 29 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +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; + +public abstract class AbstractMatrixND implements MatrixND { // AbstractMatrixND + + /** to use log facility, just put in your code: log.info(\"...\"); */ + static private Log log = LogFactory.getLog(AbstractMatrixND.class); + + abstract public MatrixIterator iterator(); + abstract public double getValue(int [] coordinates); + abstract public void setValue(int [] coordinates, double d); + + transient protected DimensionHelper dimHelper = new DimensionHelper(); + + transient protected MatrixFactory factory = null; + protected String name = ""; + protected String [] dimNames = null; + protected int [] dim = null; + protected List[] semantics = null; + protected double defaultValue = 0; + + 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 + protected Object clone() throws CloneNotSupportedException { + 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 void setDimensionName(String[] names){ + for(int i=0; names != null && i<names.length; i++){ + setDimensionName(i, names[i]); + } + } + public void setDimensionName(int dim, String name){ + dimNames[dim] = name; + } + public String getDimensionName(int dim){ + return dimNames[dim]; + } + public String [] getDimensionName(){ + return dimNames; + } + public double getMaxOccurence(){ + // on creer un tableau dans cette classe, car on ne sait pas sur quelle + // implantation on s'appuie. Mais dans les sous classes, si on a deja + // 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.isDebugEnabled()) { + log.debug("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.isDebugEnabled()) { + log.debug("sem1("+sem1+")==sem2("+sem2+ ")="+result); + } +// System.out.println("sem1("+sem1+")==sem1("+sem2+ ")="+result); + } + + if (log.isDebugEnabled()) { + log.debug("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, getDimensionName()); + + 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, getDimensionName()); + + 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; + } + + /** + * Separateur CSV par défaut la virgule + */ + public static char CSV_SEPARATOR = ';'; + + /** + * Determine si la matrice supporte l'import et l'export CSV + * @return support du CSV + */ + public boolean isSupportedCSV() { + return getNbDim() <= 2; + } + + Pattern NUMBER = Pattern.compile(" *[+-]?[0-9]*\\.?[0-9]+([eE][+-]?[0-9]+)? *"); + + /** + * 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: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/BasicMatrix.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/BasicMatrix.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/BasicMatrix.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/BasicMatrix.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,323 @@ +/* *##% + * Copyright (C) 2002, 2003, 2004 Code Lutin, Cédric 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. + *##%*/ + +/* * + * BasicMatrix.java + * + * Created: 27 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +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. +*/ +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 + * @throws + */ + 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 + * @param linearFactor le tableau permettant la conversion + * @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", new Integer(i), new Integer(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: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/BasicMatrixIterator.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/BasicMatrixIterator.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/BasicMatrixIterator.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/BasicMatrixIterator.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,63 @@ +/* *##% + * Copyright (C) 2002, 2003, 2004 Code Lutin, Cédric 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. + *##%*/ + +/* * + * BasicMatrixIterator.java + * + * Created: 28 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.codelutin.math.matrix; + +public interface BasicMatrixIterator { // BasicMatrixIterator + + /** + * Retourne vrai s'il existe un suivant + * @return vrai s'il y a un suivant, faux sinon + */ + public boolean hasNext(); + + /** + * Passe à l'élément suivant + */ + public boolean next(); + + /** + * Retourne les coordonnés de l'élément + */ + public int [] getCoordinates(); + + /** + * Retourne la valeur courant pointé par l'iterator + */ + public double getValue(); + + /** + * Modifie la valeur courant pointé par l'iterator + */ + public void setValue(double value); + +} // BasicMatrixIterator + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/DimensionHelper.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/DimensionHelper.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/DimensionHelper.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/DimensionHelper.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,109 @@ +/* *##% + * Copyright (C) 2002, 2003, 2004 Code Lutin, Cédric 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. + *##%*/ + +/* * + * DimensionHelper.java + * + * Created: 29 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.codelutin.math.matrix; + +/** +* Classe permettant de diminuer au maximum l'allocation de tableau de int +* pour les dimensions. Cette classe n'est pas multithread, il faut créer une +* instance par thread. Il faut bien réfléchir lorsque l'on souhaite utiliser +* cette classe, par exemple il ne faut pas l'utiliser dans une méthode qui +* appelle une autre methode réutilisant le meme objet, car il sera alors +* modifier alors qu'il ne le faut pas pour la premiere methode appelée. +*/ +public class DimensionHelper { // DimensionHelper + + protected int [] d1 = new int[1]; + protected int [] d2 = new int[2]; + protected int [] d3 = new int[3]; + protected int [] d4 = new int[4]; + + protected Object [] o1 = new Object[1]; + protected Object [] o2 = new Object[2]; + protected Object [] o3 = new Object[3]; + protected Object [] o4 = new Object[4]; + + public DimensionHelper(){} + + public int [] get(int x){ + d1[0] = x; + return d1; + } + + public int [] get(int x, int y){ + d2[0] = x; + d2[1] = y; + return d2; + } + + public int [] get(int x, int y, int z){ + d3[0] = x; + d3[1] = y; + d3[2] = z; + return d3; + } + + public int [] get(int x, int y, int z, int t){ + d4[0] = x; + d4[1] = y; + d4[2] = z; + d4[3] = t; + return d4; + } + + public Object [] get(Object x){ + o1[0] = x; + return o1; + } + + public Object [] get(Object x, Object y){ + o2[0] = x; + o2[1] = y; + return o2; + } + + public Object [] get(Object x, Object y, Object z){ + o3[0] = x; + o3[1] = y; + o3[2] = z; + return o3; + } + + public Object [] get(Object x, Object y, Object z, Object t){ + o4[0] = x; + o4[1] = y; + o4[2] = z; + o4[3] = t; + return o4; + } + +} // DimensionHelper + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/DoubleBigVector.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/DoubleBigVector.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/DoubleBigVector.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/DoubleBigVector.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,113 @@ +/* *##% + * Copyright (C) 2005 + * Code Lutin, Cédric 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. + *##%*/ + +/* * + * DoubleBigVector.java + * + * Created: 6 octobre 2005 02:54:36 CEST + * + * @author Benjamin POUSSIN <poussin@codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.codelutin.math.matrix; + +import java.util.Arrays; + +public class DoubleBigVector implements Vector { // DoubleBigVector + + protected double data[] = null; + + public DoubleBigVector(int capacity){ + data = new double[capacity]; + } + + public int size() { + return data.length; + } + + public double getMaxOccurence() { + return MatrixHelper.maxOccurence(data); + } + + public double getValue(int pos) { + return data[pos]; + } + + public void setValue(int pos, double value) { + data[pos] = value; + } + + public boolean equals(Object o) { + boolean result = false; + if (o instanceof DoubleBigVector) { + DoubleBigVector other = (DoubleBigVector)o; + result = Arrays.equals(this.data, other.data); + } else if (o instanceof Vector) { + Vector other = (Vector)o; + result = true; + for(int i=0; i<size() && result; i++){ + result = getValue(i) == other.getValue(i); + } + } + return result; + } + + public boolean isImplementedPaste(Vector v) { + return v instanceof DoubleBigVector; + } + public boolean isImplementedAdd(Vector v) { + return v instanceof DoubleBigVector; + } + public boolean isImplementedMinus(Vector v) { + return v instanceof DoubleBigVector; + } + public boolean isImplementedMap() { + return true; + } + + public void paste(Vector v) { + DoubleBigVector fbv = (DoubleBigVector)v; + System.arraycopy(fbv.data, 0, this.data, 0, this.size()); + } + public void add(Vector v) { + DoubleBigVector fbv = (DoubleBigVector)v; + for(int i=0; i<data.length; i++) { + data[i] += fbv.data[i]; + } + } + + public void minus(Vector v) { + DoubleBigVector fbv = (DoubleBigVector)v; + for(int i=0; i<data.length; i++) { + data[i] -= fbv.data[i]; + } + } + + public void map(MapFunction f) { + for(int i=0; i<data.length; i++) { + data[i] = f.apply(data[i]); + } + } + +} // DoubleBigVector + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/DoubleVector.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/DoubleVector.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/DoubleVector.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/DoubleVector.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,300 @@ +/* *##% + * Copyright (C) 2005 + * Code Lutin, Cédric 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. + *##%*/ + +/* * + * FloatVector.java + * + * Created: 6 octobre 2005 01:29:23 CEST + * + * @author Benjamin POUSSIN <poussin@codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.codelutin.math.matrix; + +import java.util.Arrays; + +import org.apache.commons.collections.primitives.ArrayDoubleList; +import org.apache.commons.collections.primitives.ArrayFloatList; + +/** +* Permet de stocker des données à une position lineair et de la redemander +* Cette classe ne gére que les données lineaire. +* L'avantage de cette classe est de ne conserver que les elements differents +* de la valeur par defaut, ce qui minimize la taille du tableau necessaire +* a conserver les données. +*/ +public class DoubleVector implements Vector { // FloatVector + + /** maximum number of element, maximum pos value */ + protected int capacity = 0; + + /** la valeur par defaut */ + protected double defaultValue = 0; + + /** contient la position de l'element, le tableau est trie */ + protected int [] position; + protected int positionSize = 0; + + /** contient la valeur de l'element */ + protected ArrayDoubleList data = new ArrayDoubleList(); + + public DoubleVector(int capacity) { + this.capacity = capacity; + position = new int[8]; + Arrays.fill(position, Integer.MAX_VALUE); + } + + public DoubleVector(int capacity, double defaultValue){ + this(capacity); + this.defaultValue = defaultValue; + } + + public int size() { + return capacity; + } + + // poussin 20060827 TODO: verifier l'implantation, il semble quelle soit fausse et ne puisse pas recherche le nombre max correctement + public double getMaxOccurence() { + double result = defaultValue; + + double [] tmp = data.toArray(); + + // si potentiellement il y a plus d'element identique dans data + // que de valeur par defaut, on recherche la valeur possible + if (this.capacity < 2*tmp.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 + 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; + } + + if(max <= capacity - tmp.length) { + // en fin de compte, il n'y a pas plus d'element identique + // dans data que de defaultValue + result = defaultValue; + } + } + + return result; + } + + protected void checkPos(int pos){ + if(pos < 0 || pos >= capacity) { + throw new IllegalArgumentException("pos " + pos + " is not in [0, "+capacity+"]"); + } + } + + public double getValue(int pos) { + checkPos(pos); + + double result = defaultValue; + int index = findIndex(pos); + if (index >= 0) { + result = data.get(index); + } + return result; + } + + /** + * On ajoute dans l'o + */ + public void setValue(int pos, double value) { + checkPos(pos); + + int index = findIndex(pos); + if (index >= 0) { + if (value == defaultValue) { + // il etait present, on supprime l'element + removeElementAt(index); + data.removeElementAt(index); + } else { + // il etait deja present, on modifie la valeur + data.set(index, value); + } + } else { + // il n'etait pas present + if (value != defaultValue) { + // il faut ajouter dans position et dans data + index = -index -1; + + addElementAt(index, pos); + data.add(index, value); + } + } + } + + public boolean equals(Object o) { + boolean result = false; + if (o instanceof DoubleVector) { + DoubleVector other = (DoubleVector)o; + result = Arrays.equals(this.position, other.position) && data.equals(other.data); + } else if (o instanceof Vector) { + Vector other = (Vector)o; + result = true; + for(int i=0; i<size() && result; i++){ + result = getValue(i) == other.getValue(i); + } + } + return result; + } + + + /** + * retourne la position dans le tableau position de la position lineaire + * @return la position ou < 0 donnant la position de l'element s'il etait + * present + */ + protected int findIndex(int pos) { + return Arrays.binarySearch(position, pos); + } + + protected void ensureCapacity(int mincap) { + if(mincap > position.length) { + int newcap = (position.length * 3) / 2 + 1; + int olddata[] = position; + position = new int[newcap >= mincap ? newcap : mincap]; + System.arraycopy(olddata, 0, position, 0, positionSize); + for(int i=positionSize; i<position.length; i++){ + position[i] = Integer.MAX_VALUE; + } + } + } + + protected void addElementAt(int index, int element) { + ensureCapacity(positionSize + 1); + int numtomove = positionSize - index; + System.arraycopy(position, index, position, index + 1, numtomove); + position[index] = element; + positionSize++; + } + + protected int removeElementAt(int index) { + int oldval = position[index]; + int numtomove = positionSize - index - 1; + if(numtomove > 0) { + System.arraycopy(position, index + 1, position, index, numtomove); + } + positionSize--; + position[positionSize] = Integer.MAX_VALUE; + return oldval; + } + + + public boolean isImplementedPaste(Vector v) { + return v instanceof DoubleVector; + } + public boolean isImplementedAdd(Vector v) { + // FIXME une fois la methode implanter supprimer le false + return false && v instanceof DoubleVector; + } + public boolean isImplementedMinus(Vector v) { + // FIXME une fois la methode implanter supprimer le false + return false && v instanceof DoubleVector; + } + public boolean isImplementedMap() { + return true; + } + + /** + * On recopie tous les attributs pour que le vector ressemble exactement + * a celui passé en argument + */ + public void paste(Vector v) { + DoubleVector fbv = (DoubleVector)v; + this.capacity = fbv.capacity; + this.defaultValue = fbv.defaultValue; + this.positionSize = fbv.positionSize; + this.position = new int[fbv.position.length]; + System.arraycopy(fbv.position, 0, this.position, 0, this.position.length); + this.data.clear(); + this.data.addAll(fbv.data); + } + + // poussin 20060827 FIXME a refaire car v.data et date n'ont pas forcement leur element qui se correspondent, cette implatation est donc fausse + public void add(Vector v) { + DoubleVector fbv = (DoubleVector)v; + for(int i=0; i<data.size(); i++) { + double newValue = data.get(i) + fbv.data.get(i); + data.set(i, newValue); + } + } + + // poussin 20060827 FIXME a refaire car v.data et date n'ont pas forcement leur element qui se correspondent, cette implatation est donc fausse + public void minus(Vector v) { + DoubleVector fbv = (DoubleVector)v; + for(int i=0; i<data.size(); i++) { + double newValue = data.get(i) - fbv.data.get(i); + data.set(i, newValue); + } + } + + /** + * on applique sur chaque donnée existante et sur default + */ + public void map(MapFunction f) { + // on commence toujours par modifier la valeur par defaut + // car les valeurs suivante pourrait prendre cette valeur + // et donc disparaitre des tableaux si besoin + defaultValue = f.apply(defaultValue); + // on fait la boucle a l'envers au cas ou on supprime des valeurs + for(int i=data.size()-1; i>=0; i--) { + double value = f.apply(data.get(i)); + if (value == defaultValue) { + // il etait present, on supprime l'element + removeElementAt(i); + data.removeElementAt(i); + } else { + // il etait deja present, on modifie la valeur + data.set(i, value); + } + } + } +} // FloatVector + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/FloatBigVector.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/FloatBigVector.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/FloatBigVector.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/FloatBigVector.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,113 @@ +/* *##% + * Copyright (C) 2005 + * Code Lutin, Cédric 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. + *##%*/ + +/* * + * FloatBigVector.java + * + * Created: 6 octobre 2005 02:54:36 CEST + * + * @author Benjamin POUSSIN <poussin@codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.codelutin.math.matrix; + +import java.util.Arrays; + +public class FloatBigVector implements Vector { // FloatBigVector + + protected float data[] = null; + + public FloatBigVector(int capacity){ + data = new float[capacity]; + } + + public int size() { + return data.length; + } + + public double getMaxOccurence() { + return MatrixHelper.maxOccurence(data); + } + + public double getValue(int pos) { + return data[pos]; + } + + public void setValue(int pos, double value) { + data[pos] = (float)value; + } + + public boolean equals(Object o) { + boolean result = false; + if (o instanceof FloatBigVector) { + FloatBigVector other = (FloatBigVector)o; + result = Arrays.equals(this.data, other.data); + } else if (o instanceof Vector) { + Vector other = (Vector)o; + result = true; + for(int i=0; i<size() && result; i++){ + result = getValue(i) == other.getValue(i); + } + } + return result; + } + + public boolean isImplementedPaste(Vector v) { + return v instanceof FloatBigVector; + } + public boolean isImplementedAdd(Vector v) { + return v instanceof FloatBigVector; + } + public boolean isImplementedMinus(Vector v) { + return v instanceof FloatBigVector; + } + public boolean isImplementedMap() { + return true; + } + + public void paste(Vector v) { + FloatBigVector fbv = (FloatBigVector)v; + System.arraycopy(fbv.data, 0, this.data, 0, this.size()); + } + public void add(Vector v) { + FloatBigVector fbv = (FloatBigVector)v; + for(int i=0; i<data.length; i++) { + data[i] += fbv.data[i]; + } + } + + public void minus(Vector v) { + FloatBigVector fbv = (FloatBigVector)v; + for(int i=0; i<data.length; i++) { + data[i] -= fbv.data[i]; + } + } + + public void map(MapFunction f) { + for(int i=0; i<data.length; i++) { + data[i] = (float)f.apply(data[i]); + } + } + +} // FloatBigVector + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/FloatVector.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/FloatVector.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/FloatVector.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/FloatVector.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,297 @@ +/* *##% + * Copyright (C) 2005 + * Code Lutin, Cédric 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. + *##%*/ + +/* * + * FloatVector.java + * + * Created: 6 octobre 2005 01:29:23 CEST + * + * @author Benjamin POUSSIN <poussin@codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.codelutin.math.matrix; + +import java.util.Arrays; + +import org.apache.commons.collections.primitives.ArrayFloatList; + +/** +* Permet de stocker des données à une position lineair et de la redemander +* Cette classe ne gére que les données lineaire. +* L'avantage de cette classe est de ne conserver que les elements differents +* de la valeur par defaut, ce qui minimize la taille du tableau necessaire +* a conserver les données. +*/ +public class FloatVector implements Vector { // FloatVector + + /** maximum number of element, maximum pos value */ + protected int capacity = 0; + + /** la valeur par defaut */ + protected float defaultValue = 0; + + /** contient la position de l'element, le tableau est trie */ + protected int [] position; + protected int positionSize = 0; + + /** contient la valeur de l'element */ + protected ArrayFloatList data = new ArrayFloatList(); + + public FloatVector(int capacity) { + this.capacity = capacity; + position = new int[8]; + Arrays.fill(position, Integer.MAX_VALUE); + } + + public FloatVector(int capacity, float defaultValue){ + this(capacity); + this.defaultValue = defaultValue; + } + + public int size() { + return capacity; + } + + public double getMaxOccurence() { + float result = defaultValue; + + float [] tmp = data.toArray(); + + // si potentiellement il y a plus d'element identique dans data + // que de valeur par defaut, on recherche la valeur possible + if (this.capacity < 2*tmp.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 + result = tmp[0]; + // la valeur que l'on vient de traiter précédement + float old = tmp[0]; + // la valeur courante lu dans le tableaux + float 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; + } + + if(max <= capacity - tmp.length) { + // en fin de compte, il n'y a pas plus d'element identique + // dans data que de defaultValue + result = defaultValue; + } + } + + return result; + } + + protected void checkPos(int pos){ + if(pos < 0 || pos >= capacity) { + throw new IllegalArgumentException("pos " + pos + " is not in [0, "+capacity+"]"); + } + } + + public double getValue(int pos) { + checkPos(pos); + + float result = defaultValue; + int index = findIndex(pos); + if (index >= 0) { + result = data.get(index); + } + return result; + } + + /** + * On ajoute dans l'o + */ + public void setValue(int pos, double dValue) { + checkPos(pos); + + float value = (float)dValue; + int index = findIndex(pos); + if (index >= 0) { + if (value == defaultValue) { + // il etait present, on supprime l'element + removeElementAt(index); + data.removeElementAt(index); + } else { + // il etait deja present, on modifie la valeur + data.set(index, value); + } + } else { + // il n'etait pas present + if (value != defaultValue) { + // il faut ajouter dans position et dans data + index = -index -1; + + addElementAt(index, pos); + data.add(index, value); + } + } + } + + public boolean equals(Object o) { + boolean result = false; + if (o instanceof FloatVector) { + FloatVector other = (FloatVector)o; + result = Arrays.equals(this.position, other.position) && data.equals(other.data); + } else if (o instanceof Vector) { + Vector other = (Vector)o; + result = true; + for(int i=0; i<size() && result; i++){ + result = getValue(i) == other.getValue(i); + } + } + return result; + } + + + /** + * retourne la position dans le tableau position de la position lineaire + * @return la position ou < 0 donnant la position de l'element s'il etait + * present + */ + protected int findIndex(int pos) { + return Arrays.binarySearch(position, pos); + } + + protected void ensureCapacity(int mincap) { + if(mincap > position.length) { + int newcap = (position.length * 3) / 2 + 1; + int olddata[] = position; + position = new int[newcap >= mincap ? newcap : mincap]; + System.arraycopy(olddata, 0, position, 0, positionSize); + for(int i=positionSize; i<position.length; i++){ + position[i] = Integer.MAX_VALUE; + } + } + } + + protected void addElementAt(int index, int element) { + ensureCapacity(positionSize + 1); + int numtomove = positionSize - index; + System.arraycopy(position, index, position, index + 1, numtomove); + position[index] = element; + positionSize++; + } + + protected int removeElementAt(int index) { + int oldval = position[index]; + int numtomove = positionSize - index - 1; + if(numtomove > 0) { + System.arraycopy(position, index + 1, position, index, numtomove); + } + positionSize--; + position[positionSize] = Integer.MAX_VALUE; + return oldval; + } + + + public boolean isImplementedPaste(Vector v) { + return v instanceof FloatVector; + } + public boolean isImplementedAdd(Vector v) { + // FIXME une fois la methode implanter supprimer le false + return false && v instanceof FloatVector; + } + public boolean isImplementedMinus(Vector v) { + // FIXME une fois la methode implanter supprimer le false + return false && v instanceof FloatVector; + } + public boolean isImplementedMap() { + return true; + } + + /** + * On recopie tous les attributs pour que le vector ressemble exactement + * a celui passé en argument + */ + public void paste(Vector v) { + FloatVector fbv = (FloatVector)v; + this.capacity = fbv.capacity; + this.defaultValue = fbv.defaultValue; + this.positionSize = fbv.positionSize; + this.position = new int[fbv.position.length]; + System.arraycopy(fbv.position, 0, this.position, 0, this.position.length); + this.data.clear(); + this.data.addAll(fbv.data); + } + + // FIXME a faire + public void add(Vector v) { + FloatVector fbv = (FloatVector)v; + for(int i=0; i<data.size(); i++) { + data.set(i, (float)(data.get(i) + fbv.data.get(i))); + } + } + + // FIXME a faire + public void minus(Vector v) { + FloatVector fbv = (FloatVector)v; + for(int i=0; i<data.size(); i++) { + data.set(i, (float)(data.get(i) - fbv.data.get(i))); + } + } + + /** + * on applique sur chaque donnée existante et sur default + */ + public void map(MapFunction f) { + // on commence toujours par modifier la valeur par defaut + // car les valeurs suivante pourrait prendre cette valeur + // et donc disparaitre des tableaux si besoin + defaultValue = (float)f.apply(defaultValue); + // on fait la boucle a l'envers au cas ou on supprime des valeurs + for(int i=data.size()-1; i>=0; i--) { + double value = f.apply(data.get(i)); + if (value == defaultValue) { + // il etait present, on supprime l'element + removeElementAt(i); + data.removeElementAt(i); + } else { + // il etait deja present, on modifie la valeur + data.set(i, (float)value); + } + } + } +} // FloatVector + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MapFunction.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/MapFunction.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MapFunction.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MapFunction.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,46 @@ +/* *##% + * Copyright (C) 2002, 2003 Code Lutin, Cédric 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. + *##%*/ + +/* * + * MapFunction.java + * + * Created: 27 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.codelutin.math.matrix; + +public interface MapFunction { // MapFunction + + /** + * Permet de faire un traitement sur value et de retourne une nouvelle + * valeur. + * @param la valeur courante sur lequel il faut faire le traitement + * @return la nouvelle valeur à mettre dans la matrice à la place de + * l'ancienne. + */ + public double apply(double value); + +} // MapFunction + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixEncoder.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/MatrixEncoder.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixEncoder.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixEncoder.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,132 @@ +/* *##% + * Copyright (C) 2002, 2003 Code Lutin, Cédric 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. + *##%*/ + +/* * + * MatriceEncoder.java + * + * Created: 21 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.codelutin.math.matrix; + +import java.io.IOException; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class MatrixEncoder { // MatriceEncoder + + protected Writer out = null; + + public MatrixEncoder(Writer out){ + this.out = out; + } + + /** + * Methode qui peut etre surcharge par les enfants + * Elle sert a mettre sous forme XML les objets de semantiques + * Par defaut cette méthode converti en représentation chaine les objets + * Un objet deviendra donc une chaine de caractere lors de la lecture de + * la matrice à partir du XML si cette méthode n'est pas surchargée. + * Le seul objet convenablement supporté sont les représentation objet + * des types primitifs + */ + protected String getSemanticsAsXml(Object o) throws IOException { + if(o == null){ + // on ne fait rien car la valeur par defaut lorsqu'on relit + // la matrice est null + return null; + }else{ + // par defaut si on ne sait pas comment mettre en XML un objet + // on dit qu'il est de type String et on appelle la methode + // toString sur l'objet + // A la relecture l'objet sera donc une string + String type = String.class.getName(); + if(o instanceof Number || o instanceof Boolean){ + type = o.getClass().getName(); + } + return "<object type=\"" + type + "\">" + o.toString() + "</object>"; + } + } + + public void writeMatrice(MatrixND mat) throws IOException { + // l'element que l'on defini comme element par defaut est celui + // que l'on retrouve le plus souvent + double defaultValue = mat.getMaxOccurence(); + + out.write("<matrix defaultValue=\"" + defaultValue + "\" name=\""+mat.getName()+"\" dimensions=\""); + out.write(MatrixHelper.coordinatesToString(mat.getDim())); + out.write("\" type=\""+mat.getClass().getName()+"\">\n"); + + // ecriture des noms des dimensions + for(int i=0; i<mat.getNbDim(); i++){ + String dimName = mat.getDimensionName(i); + // si le nom est non null et non vide on l'ecrit, + // sinon c la valeur par defaut lorsqu'on relit la matrice + // donc ca ne sert a rien de le mettre dans le XML + if(dimName != null && !"".equals(dimName)){ + out.write(" <dimensionName dim=\"" + i + "\">"); + out.write(mat.getDimensionName(i)); + out.write("</dimensionName>\n"); + } + } + + // ecriture de la semantique + for(int i=0; i<mat.getNbDim(); i++){ + List sem = mat.getSemantics(i); + List semAsXml = new ArrayList(); + boolean haveNotNull = false; + for(Iterator e=sem.iterator(); e.hasNext();){ + String xml = getSemanticsAsXml(e.next()); + semAsXml.add(xml); + haveNotNull = haveNotNull || xml != null; + } + if(haveNotNull){ + out.write(" <semantics dim=\"" + i + "\">\n"); + for(int index=0; index<semAsXml.size(); index++){ + String xml = (String)semAsXml.get(index); + if(xml != null){ + out.write(" <sem index=\""+index+"\">"+xml+"</sem>\n"); + } + } + out.write(" </semantics>\n"); + } + } + + // ecriture des valeur de la matrice + for(MatrixIterator i=mat.iterator(); i.next();){ + double val = i.getValue(); + if(val != defaultValue){ + String path = MatrixHelper.coordinatesToString(i.getCoordinates()); + out.write("\t<element path=\""+path+"\" value=\""+val+"\"/>\n"); + } + } + + out.write("</matrix>\n"); + } + +} // MatriceEncoder + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixException.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/MatrixException.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixException.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixException.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,48 @@ +/**##%% +* Copyright (C) 2002, 2003 Code Lutin +* +* 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. +*##%%**/ + + +/** +* MatriceException.java +* +* +* Created: Tue Jun 29 11:46:39 1999 +* +* @author +* @version $Revision$ +* +* Mise a jour: $Date$ +* par : $Author$ +*/ + +package org.codelutin.math.matrix; + +public class MatrixException extends RuntimeException { + + /** */ + private static final long serialVersionUID = 1917420713781767581L; + + public MatrixException(String s) { + super(s); + } + + public MatrixException(String s, Throwable e) { + super(s, e); + } + +} // MatriceException Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixFactory.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/MatrixFactory.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixFactory.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixFactory.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,180 @@ +/* *##% + * Copyright (C) 2005 + * Code Lutin, Cédric 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. + *##%*/ + +/* * + * MatrixFactory.java + * + * Created: 11 octobre 2005 20:15:20 CEST + * + * @author Benjamin POUSSIN <poussin@codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.codelutin.math.matrix; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.List; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** +* Cette classe permet de creer des matrices, toutes les creations de matrice +* doivent etre faite a travers cette classe. +* Cette classe permet de modifier la representation interne des matrices +* de facon simple. +* <p> +* +*/ +public class MatrixFactory { // MatrixFactory + + /** to use log facility, just put in your code: log.info(\"...\"); */ + static private Log log = LogFactory.getLog(MatrixFactory.class); + + static { + // on essai d'enregistrer le converter XML + try { + // Il faut le faire par pur introspection sinon l'exception + // NoClassDefFoundError est levé avant d'entrer dans le constructeur + // static :( + Class converterClass = Class.forName("org.codelutin.math.matrix.MatrixNDXMLConverter"); + Object converter = converterClass.newInstance(); + + Class converterFactoryClass = Class.forName("org.codelutin.xml.XMLConverterFactory"); + Method m = converterFactoryClass.getMethod("addConverter", Class.class, Class.forName("org.codelutin.xml.XMLConverter")); + m.invoke(null, MatrixND.class, converter); + + // org.codelutin.xml.XMLConverterFactory.addConverter(MatrixND.class, + // new MatrixNDXMLConverter()); + log.info("Converter XML pour MatrixND ajoute"); + + // on essai d'enregistrer le converter JDBC + // le JDBC depend du XML + try { + converterClass = Class.forName("org.codelutin.math.matrix.MatrixNDJDBCConverter"); + converter = converterClass.newInstance(); + + converterFactoryClass = Class.forName("org.codelutin.topia.persistence.jdbctransformer.JDBCTransformerFactory"); + m = converterFactoryClass.getMethod("addConverter", Class.class, Class.forName("org.codelutin.topia.persistence.jdbctransformer.JDBCTransformer")); + m.invoke(null, MatrixND.class, converter); + + // Class converterClass = org.codelutin.math.matrix.MatrixNDJDBCConverter(); + // JDBCTransformerFactory + // .addConverter(MatrixND.class, new MatrixNDJDBCConverter()); + log.info("Converter JDBC pour MatrixND ajoute"); + } catch (Throwable eee) { + log.info("librairie topia non presente. Import/Export JDBC impossible"); + log.debug("L'exception etait", eee); + } + + } catch (Throwable eee) { + log.info("librairie lutinxml non presente. Import/Export XML impossible"); + log.debug("L'exception etait", eee); + } + + } + + + /** Valeur par defaut si aucun type de Vector n'est donné */ + static protected Class defaultVectorClass = DoubleBigVector.class; + + protected Class vectorClass = null; + + protected MatrixFactory(Class vectorClass) { + this.vectorClass = vectorClass; + } + + static public void setDefaultVectorClass(Class vectorClass) { + defaultVectorClass = vectorClass; + } + + static public Class getDefaultVectorClass() { + return defaultVectorClass; + } + + /** + * Retourne une factory utilisant vectorClass comme classe de base + * a l'implantation des matrices + */ + static public MatrixFactory getInstance(Class vectorClass) { + return new MatrixFactory(vectorClass); + } + + /** + * Utilise par defaut {@link FloatBigVector} + */ + static public MatrixFactory getInstance() { + return getInstance(defaultVectorClass); + } + + public MatrixND create(int [] dim){ + return new MatrixNDImpl(this, dim); + } + public MatrixND create(List[] semantics){ + return new MatrixNDImpl(this, semantics); + } + + public MatrixND create(String name, int [] dim){ + return new MatrixNDImpl(this, name, dim); + } + + public MatrixND create(String name, int [] dim, String [] dimNames){ + return new MatrixNDImpl(this, name, dim, dimNames); + } + + public MatrixND create(String name, List[] semantics){ + return new MatrixNDImpl(this, name, semantics); + } + + public MatrixND create(String name, List[] semantics, String [] dimNames){ + return new MatrixNDImpl(this, name, semantics, dimNames); + } + + public MatrixND create(MatrixND matrix){ + return new MatrixNDImpl(this, matrix); + } + + /** + * Crée une nouvelle matrice identité. Une matrice identité est une matrice + * à 2 dimensions dont tous les éléments de la diagonal vaut 1 + * @param size la taille de la matrice + * @return une nouvelle matrice identité + */ + public MatrixND matrixId(int size){ + MatrixND result = create(new int[]{size, size}); + for(int i=0; i<size; i++){ + result.setValue(i, i , 1); + } + return result; + } + + protected Vector createVector(int length) { + try { + Constructor c = vectorClass.getConstructor(new Class[]{Integer.TYPE}); + return (Vector)c.newInstance(new Object[]{length}); + } catch (Exception eee){ + throw new RuntimeException("Can't create vector", eee); + } + } + +} // MatrixFactory + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixHelper.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/MatrixHelper.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixHelper.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixHelper.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,346 @@ +/* *##% + * Copyright (C) 2002, 2003, 2004 Code Lutin, C�dric 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. + *##%*/ + +/* * + * MatrixHelper.java + * + * Created: 28 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.codelutin.math.matrix; + +import java.io.IOException; +import java.io.StreamTokenizer; +import java.io.StringReader; +import java.io.StringWriter; +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; + +public class MatrixHelper { + + /** + * Logger for this class + */ + private static final Log log = LogFactory.getLog(MatrixHelper.class); + // MatrixHelper + + /** + * Convert Matrix to identity matrix must have 2 dimensions. If dimension + * haven't same length, then the small dimension is used. + * @param mat + * @return + */ + static public 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 implatantion 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.StrintUtil#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 + */ + static public 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 + */ + static public 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 + */ + static public 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 identique + */ + static public boolean sameDimension(int [] dim1, int [] dim2){ + return Arrays.equals(dim1, dim2); + } + + /** + * Permet de convertir des coordonn�es d�fini par des entiers en coordonn�e + * 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. + */ + static public 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] = new Integer(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 � utilis� pour la conversion + * @param coordonn�es 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'interger est utilis� pour la conversion. + */ + static public 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 + */ + static public 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� retrouve 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 + */ + static public MatrixND fill(MatrixND mat, final double value){ + mat.map(new MapFunction(){ + public double apply(double v){ + return value; + } + }); + return mat; + } + + // /** + // * Cr�e une nouvelle matrice identit�. Une matrice identit� est une matrice + // * � 2 dimensions dont tous les �l�ments de la diagonal vaut 1 + // * @param size la taille de la matrice + // * @return une nouvelle matrice identit� + // */ + // static public MatrixND matrixId(int size){ + // MatrixND result = new MatrixNDImpl(new int[]{size, size}); + // for(int i=0; i<size; i++){ + // result.setValue(i, i , 1); + // } + // return result; + // } + + /** + * Retourne la valeur la plus courrement rencontrer dans un tableau. + * si plusieurs valeurs ont le m�me nombre d'occurence la plus petite + * valeur est retourn�. + * @param tab le tableau de valeur + * @return la valeur la plus nombreuse dans le tableau + */ + static public double maxOccurence(double [] tab){ + double [] tmp = new double[tab.length]; + System.arraycopy(tab, 0, tmp, 0, tab.length); + return maxOccurence1(tmp); + } + + static public 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� + */ + static protected 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; + } + +// static public String encodeToXML(MatrixND mat){ +// StringWriter out = new StringWriter(); +// XMLEncoderDecoder.getInstance().encode(out, mat); +// return out.toString(); +// } +// +// static public MatrixND decodeFromXML(String xml){ +// try{ +// return (MatrixND)XMLEncoderDecoder.getInstance().decode(new StringReader(xml)); +// }catch(Exception eee){ +// throw new MatrixException("Erreur durant le decodage de la matrice", eee); +// } +// } + +} // MatrixHelper + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixIterator.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/MatrixIterator.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixIterator.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixIterator.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,43 @@ +/* *##% + * Copyright (C) 2002, 2003, 2004 Code Lutin, Cédric 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. + *##%*/ + +/* * + * MatrixIterator.java + * + * Created: 28 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.codelutin.math.matrix; + +public interface MatrixIterator extends BasicMatrixIterator { // MatrixIterator + + /** + * Retourne les coordonnés de l'élément, en sémantique. + * Si la matrice n'a pas de sémantique alors retourne null + */ + public Object [] getSemanticsCoordinates(); + +} // MatrixIterator + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixIteratorImpl.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/MatrixIteratorImpl.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixIteratorImpl.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixIteratorImpl.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,84 @@ +/* *##% + * Copyright (C) 2002, 2003, 2004 Code Lutin, Cédric 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. + *##%*/ + +/* * + * MatrixIteratorImpl.java + * + * Created: 28 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.codelutin.math.matrix; + +import java.util.List; + +public class MatrixIteratorImpl implements MatrixIterator { // MatrixIteratorImpl + + protected BasicMatrixIterator iterator = null; + protected List [] semantics = null; + protected int pos = 0; + + /** + * @param matrix la matrice sur lequel l'iterator doit travailler + * @param semantics la semantique de matrix, si matrix n'a pas de semantique + * alors il faut passer null + */ + public MatrixIteratorImpl(BasicMatrixIterator iterator, List [] semantics){ + this.iterator = iterator; + this.semantics = semantics; + pos = 0; + } + + public boolean hasNext(){ + return iterator.hasNext(); + } + + public boolean next(){ + return iterator.next(); + } + + public int [] getCoordinates(){ + return iterator.getCoordinates(); + } + + public double getValue(){ + return iterator.getValue(); + } + + public void setValue(double value){ + iterator.setValue(value); + } + + public Object [] getSemanticsCoordinates(){ + if(semantics == null){ + return null; + }else{ + int [] coordinates = getCoordinates(); + Object [] result = MatrixHelper.dimensionToSemantics(semantics, coordinates); + return result; + } + } + +} // MatrixIteratorImpl + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixND.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/MatrixND.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixND.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixND.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,570 @@ +/* *##% +* Copyright (C) 2002, 2003, 2004 Code Lutin, Cédric 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. +*##%*/ + +/* * +* MatrixND.java +* +* Created: 29 oct. 2004 +* +* @author Benjamin Poussin <poussin@codelutin.com> +* @version $Revision$ +* +* Mise a jour: $Date$ +* par : $Author$ +*/ + +package org.codelutin.math.matrix; + +import java.io.IOException; +import java.io.Reader; +import java.io.Serializable; +import java.io.Writer; +import java.util.List; + +public interface MatrixND extends Serializable, Cloneable { // MatrixND + + /** + * Retourne la factory qui a permit de creer la matrice + */ + public MatrixFactory getFactory(); + + /** + * Donne toutes les semantiques de la matrice + * Si la matrice n'a pas de semantique retourne null + */ + public List[] getSemantics(); + + /** + * Retourne la semantique pour une dimension + * @param dim la dimension pour lequel on veut la semantique + * @return la semantique de la dimension on null s'il n'y a pas de semantique + */ + public List getSemantics(int dim); + + /** + * Modifie la semantique d'une dimension + */ + public void setSemantics(int dim, List sem); + + /** + * Permet de donner un nom à la matrice. + */ + public void setName(String name); + + /** + * Retourne le nom de la matrice + * @return le nom de la matrice ou la chaine vide si pas de nom. + */ + public String getName(); + + /** + * Permet de mettre des noms aux différentes dimension. + */ + public void setDimensionName(String[] names); + + /** + * Permet de mettre un nom à une dimension. + * @param dim la dimension dont on veut changer le nom + * @param name le nom à donner à la dimension + */ + public void setDimensionName(int dim, String name); + + /** + * Retourne le nom de la dimension demandé. + * @param dim la dimension dont on veut le nom + * @return le nom de la dimension ou la chaine vide si la dimension n'a + * pas de nom + * @ si la dimension demandé n'est pas valide + */ + public String getDimensionName(int dim); + public String [] getDimensionName(); + + /** + * Retourne la valeur la plus courrement rencontrer dans un tableau. + * si plusieurs valeurs ont le même nombre d'occurence la plus petite + * valeur est retourné. + * @param tab le tableau de valeur + * @return la valeur la plus nombreuse dans le tableau + */ + public double getMaxOccurence(); + + /** + * Retourne le nombre de dimensions de la matrice. + */ + public int getNbDim(); + + /** + * Retourne les dimensions de la matrice. + */ + public int[] getDim(); + + /** + * Retourne la dimension de la matrice dans la dimension d + */ + public int getDim(int d); + + /** + * Retourne un iterator sur toute la matrice + */ + public MatrixIterator iterator(); + + /** + * Applique une fonction sur chaque valeur de la matrice + */ + public MatrixND map(MapFunction f); + +// /** +// * Retourne la sous matrice demandée en fonction des dimensions +// * passé en paramètre.<br> +// * +// * Exemple: Si on a un matrice 3D.<br> +// * get([1,1,1]) retourne un element de la matrice.<br> +// * get([0,0]) retourne une matrice 1D.<br> +// * get([3]) retourne une matrice 2D.<br> +// * get([-1,1]) retourne une matrice 2D.<br> +// * get([-1,-1,1]) retourne une matrice 2D.<br> +// * +// * @param dimensions les différentes dimension à extraire. +// * +// * @return une MatrixND. +// */ +// public MatrixND get(int [] dimensions); +// public MatrixND get(int x); +// public MatrixND get(int x, int y); +// public MatrixND get(int x, int y, int z); +// public MatrixND get(int x, int y, int z, int t); + + /** + * Renvoie un element de la matrice demandée en fonction des dimensions + * passé en paramètre.<br> + * + * Exemple: Si on a un matrice 3D.<br> + * getValue(1,1,1) retourne un element de la matrice.<br> + * + * @param dimensions les différentes dimension à extraire. Le + * tableau doit contenir toutes les dimensions de la matrice, et + * seulement des nombres positif + * + * @return un entier double. + */ + public double getValue(int [] dim); + public double getValue(int x); + public double getValue(int x, int y); + public double getValue(int x, int y, int z); + public double getValue(int x, int y, int z, int t); + + public double getValue(Object [] coordinates); + public double getValue(Object x); + public double getValue(Object x, Object y); + public double getValue(Object x, Object y, Object z); + public double getValue(Object x, Object y, Object z, Object t); + +// /** +// * Modifie la sous matrice demandée en fonction des dimensions +// * passé en paramètre.<br> +// * +// * Exemple: Si on a un matrice 3D.<br> +// * set([1,1,1], m) modifie un element de la matrice.<br> +// * set([0,0], m) modifie une matrice 1D.<br> +// * set([3], m) modifie une matrice 2D.<br> +// * set([-1,1], m) modifie une matrice 2D.<br> +// * set([-1,-1,1], m) modifie une matrice 2D.<br> +// * +// * @param dimensions les différentes dimension à extraire. +// * +// * @param m la matrice qui doit remplacer la sous matrice spécifié +// * par l'argument dimensions +// */ +// public void set(int [] dimensions, MatrixND m); +// public void set(int x, MatrixND m); +// public void set(int x, int y, MatrixND m); +// public void set(int x, int y, int z, MatrixND m); +// public void set(int x, int y, int z, int t, MatrixND m); + + + /** + * Modifie un element de la matrice en fonction des dimensions + * passé en paramètre.<br> + * + * Exemple: Si on a un matrice 3D.<br> + * set([1,1,1], m) modifie un element de la matrice.<br> + * + * @param dimensions les différentes dimension à extraire. + * + * @param d l'entier double qui doit remplacer l'entier double spécifié + * par l'argument dimensions + */ + public void setValue(int [] dimensions, double d); + public void setValue(int x, double d); + public void setValue(int x, int y, double d); + public void setValue(int x, int y, int z, double d); + public void setValue(int x, int y, int z, int t, double d); + + public void setValue(Object [] coordinates, double d); + public void setValue(Object x, double d); + public void setValue(Object x, Object y, double d); + public void setValue(Object x, Object y, Object z, double d); + public void setValue(Object x, Object y, Object z, Object t, double d); + + /** + * Copy la matrice pour pouvoir la modifier sans perdre les + * donnees initiales. + */ + public MatrixND copy(); + +// public String toString(); + +// /** +// * Verifie si les 2 matrices sont egal +// */ +// public boolean equals(Object o); + +// /** +// * Verifie si les dimensions sont valide pour cette matrice +// * @return vrai si dim a la même taille que le tableau de dimensions de la +// * matrice et si chaque valeur de dim est comprise entre 0 (inclus) et +// * la taille de la dimension (exclus). +// */ +// public boolean dimValid(int [] dim); + + /** + * Somme toutes les valeurs de la matrice + */ + public double sumAll(); + + /** + * Somme la matrice sur une dimension donnée. La matrice résultat à le + * même nombre de dimension, pas la dimension sommer, ne contient qu'une + * ligne. + * <p> + * par exemple pour la matrice suivante si on somme sur la dimension 1 + * cela donnera + * <pre> + * 1 2 3 + * 2 3 4 + * 3 4 5 + * </pre> + * <pre> + * 6 9 12 + * </pre> + * @param dim la dimension sur lequel il faut faire la somme + */ + public MatrixND sumOverDim(int dim); + + /** + * Somme la matrice mais la matrice reste de la même dimension. + * la somme permet juste de regrouper dans une dimension un certain + * nombre de valeur. + * <p> + * pour la matrice suivant + * <pre> + * 1 2 3 4 + * 2 3 4 5 + * 3 4 5 6 + * 4 5 6 7 + * </pre> + * la somme sur la dimension 1 avec un pas de 2 donnera + * <pre> + * 4 6 8 10 + * 6 8 10 12 + * </pre> + * c'est à dire que la ligne 0 et la ligne 2 sont sommées. + * ainsi que la ligne 1 avec la ligne 3. + * @param dim la dimension sur lequel il faut faire les sommes + * @param step le pas qu'il faut utiliser pour regrouper les elements. + * Si le pas est inférieur à 0, le pas se comporte comme si on avait + * passé en argument la taille de la dimension. Un pas de 0 ou 1, retourne + * juste une copie de la matrice actuelle. + * si la division du pas avec la taille de la dimension ne donne pas un + * nombre entier, les elements restants ne sont pas pris en compte. Par + * exemple si la dimension a 10 élements et que l'on donne un pas de 3, + * dans la matrice resultat la dimension aura 3 elements qui seront la + * somme par 3 des 9 premiers element de la matrice courante. Le 10eme + * element sera perdu. + * @return une nouvelle matrice avec le meme nombre de dimension mais + * dont la dimension passé en paramètre aura comme taille, le resultat + * de la division entier de la taille actuelle par le step + */ + public MatrixND sumOverDim(int dim, int step); + + public MatrixND sumOverDim(int dim, int start, int nb ); + + /** + * Permet de supprimer des éléments de la matrice. + * par exemple pour la matrice + * <pre> + * 1 2 3 4 + * 2 3 4 5 + * 3 4 5 6 + * 4 5 6 7 + * </pre> + * un cut(1, [0,2]) donnera + * <pre> + * 2 4 + * 3 5 + * 4 6 + * 5 7 + * </pre> + * @param dim la dimension dans lequel il faut supprimer des éléments + * @param toCut les éléments à supprimer + * @return une nouvelle matrice, la matrice actuelle n'est pas modifiée + */ + public MatrixND cut(int dim, int[] toCut); + + /** + * Copie une matrice dans la matrice actuelle. La matrice à copier à le + * même nombre de dimension. Si la matrice à copier est trop grande + * seul les éléments pouvant être copier le seront. + * @param mat la matrice à copier + * @return return la matrice courante. + */ + public MatrixND paste(MatrixND mat); + + /** + * Copie une matrice dans la matrice actuelle. La matrice à copier à le + * même nombre de dimension. Si la matrice à copier est trop grande + * seul les éléments pouvant être copier le seront. + * @param origin le point à partir duquel il faut faire la copie + * @param mat la matrice à copier + * @return return la matrice courante. + */ + public MatrixND paste(int [] origin, MatrixND mat); + + /** + * 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); + + +// /** +// * Permet de prendre une sous matrice dans la matrice. +// * par exemple pour la matrice suivante +// * <pre> +// * 1 2 3 4 5 +// * 2 3 4 5 6 +// * 3 4 5 6 7 +// * 4 5 6 7 8 +// * 5 6 7 8 9 +// * </pre> +// * un getSubMatrix([1,2], [-1, -1], [2,-1]) donnera +// * <pre> +// * 4 5 +// * 5 6 +// * 6 7 +// * </pre> +// * @param origine point à partir duquel on souhaite extraire la matrice +// * toutes les valeurs de ce tableau doivent être renseigné par des nombres +// * positif et inferieur au maximum de chaque dimension respective +// * @param toExtract permet d'indiquer les dimensions que l'on souhaite +// * extraire. Les dimensions que l'on souhaite sont marqué par un -1. Si +// * une dimension n'a pas de -1 alors on ne prend qu'une ligne dans cette +// * dimension. Le nombre de -1 indique la taille de la matrice resultante +// * S'il y a 3 -1 dans le tableau, la matrice aura 3 dimensions +// * @param nbToExtract permet de limite le nombre d'élément à prendre dans +// * une dimension. Si le tableau contient -1 alors toutes les valeurs de +// * origin à la fin seront prise, si le tableau contient une valeur positive +// * alors seul le nombre indique sera pris à partir d'origin. Une valeur +// * différente de -1 n'a de sens que pour les dimensions qui ont une valeur +// * -1 dans le paramètre toExtract +// * @return une sous matrice de la matrice +// */ +// public MatrixND getSubMatrix(int [] origin, int [] toExtract, int [] nbToExtract); + + /** + * Permet de prendre une sous matrice dans la matrice courante. La sous + * matrice a le même nombre de dimensions mais sur une des dimensions + * on ne prend que certain élément. + * @param dim la dimension dans lequel on veut une sous matrice + * si dim est négatif alors la dimension est prise à partir de la fin + * par exemple si l'on veut la derniere dimension il faut passer -1 pour + * dim + * @param start la position dans dim d'ou il faut partir pour prendre + * la sous matrice. + * @param nb le nombre d'élément à prendre dans la dimension. si nb est + * inférieur ou égal à 0 alors cela indique qu'il faut prendre tous les + * éléments jusqu'à la fin de la dimension. + */ + public MatrixND getSubMatrix(int dim, Object start, int nb); + + /** + * Permet de prendre une sous matrice dans la matrice courante. La sous + * matrice a le même nombre de dimensions mais sur une des dimensions + * on ne prend que certain élément. + * @param dim la dimension dans lequel on veut une sous matrice + * @param start la position dans dim d'ou il faut partir pour prendre + * la sous matrice. 0 <= start < dim.size + * si start est négatif alors la position de départ est calculé par rapport + * à la fin de la dimension, pour avoir le dernier élément il faut passer + * -1 + * @param nb le nombre d'élément à prendre dans la dimension si nb est + * inférieur ou égal à 0 alors cela indique qu'il faut prendre tous les + * éléments jusqu'à la fin de la dimension. + */ + public MatrixND getSubMatrix(int dim, int start, int nb); + + /** + * Permet de prendre une sous matrice dans la matrice courante. La sous + * matrice a le même nombre de dimensions mais sur une des dimensions + * on ne prend que certain élément. + * @param dim la dimension dans lequel on veut une sous matrice + * @param elem les éléments dans la dimension à conserver + */ + public MatrixND getSubMatrix(int dim, Object ... elem); + + /** + * Permet de prendre une sous matrice dans la matrice courante. La sous + * matrice a le même nombre de dimensions mais sur une des dimensions + * on ne prend que certain élément. + * @param dim la dimension dans lequel on veut une sous matrice + * @param elem les éléments dans la dimension à conserver + */ + public MatrixND getSubMatrix(int dim, int [] elem); + + + /** + * Addition la matrice courante avec la matrice passe en parametre et + * ce retourne elle meme + */ + public MatrixND add(MatrixND m); + /** + * Soustrai la matrice courante avec la matrice passe en parametre et + * ce retourne elle meme + */ + public MatrixND minus(MatrixND m); + + /** + * retourne le transpose de la matrice + */ + public MatrixND transpose(); + + /** + * Reduit la matrice de sorte que toutes les dimensions qui n'ont qu'un + * élement soit supprimée. Au pire cette méthode retourne une matrice + * à une seule dimension à un seul élément. + * @return une nouvelle matrice plus petite que la matrice actuelle + * ou egal s'il n'y a aucune dimension à supprimer + */ + public MatrixND reduce(); + + /** + * Reduit la matrice de sorte que toutes les dimensions qui n'ont qu'un + * élement soit supprimée. Au pire cette méthode retourne une matrice + * à une seule dimension à un seul élément. + * @param minNbDim le nombre minimum de dimension que l'on souhaite pour + * la matrice résultat + * @return une nouvelle matrice plus petite que la matrice actuelle + * ou egal s'il n'y a aucune dimension à supprimer + */ + public MatrixND reduce(int minNbDim); + + /** + * Reduit le matrice seulement sur les dimensions passées en argument. Si + * une des dimensions passées en arguement n'a pas un seul élément, cette + * dimension n'est pas prise en compte. + * @param dims les dimensions sur lequel il faut faire la reduction + * @return une nouvelle matrice + */ + public MatrixND reduceDims(int ... dims); + + /** + * Multiplication normal de 2 matrices 2D. Retourne une nouvelle matrice + */ + public MatrixND mult(MatrixND m); + +// /** +// * multiplication terme a terme de la matrice courante avec la +// * matrice passe en parametre et ce retourne elle meme +// */ +// public MatrixND multm(MatrixND m); + /** + * Multiplication d'une matrice par un scalaire + */ + public MatrixND mults(final double d); + /** + * Multiplication d'une matrice par un scalaire + */ + public MatrixND divs(final double d); + + /** + * Donne la matrice sous forme de List de list ... de double + * @return + */ + public List toList(); + + /** + * Permet de charger une matrice a partir d'une representation List + * @param list la matrice sous forme de List de list ... de double + */ + public void fromList(List list); + + /** + * Determine si la matrice supporte l'import et l'export CSV + * @return support du CSV + */ + public boolean isSupportedCSV(); + + /** + * 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 + */ + public void importCSV(Reader reader, int[] origin) throws IOException; + + /** + * 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; + + /** + * Verifie si les matrices sont egales en ne regardant que les valeurs + * et pas les semantiques + * + * @param mat + * @return + */ + public boolean equalsValues(MatrixND mat); + +// /** +// * Multiplication d'une vecteur [i] avec une matrice [i,j], +// * le resultat est result[i,j]=matrice[i,j]*vecteur[i] +// */ +// public MatrixND multv(MatrixND v); +// /** +// * Multiplication d'une vecteur [i] avec une matrice [g,h,i,j,k,..], +// * le resultat est result[g,h,i,j,k,..]=matrice[g,h,i,j,k,l,...]*vecteur[i] +// * @param v le vecteur +// * @param dim la position de la dimension avec lequel il faut multiplier +// * le vecteur. +// */ +// public MatrixND multv(MatrixND v, int dim); +// /** +// * Addition d'un vecteur [i] avec une matrice [g,h,i,j,k,..], +// * le resultat est result[g,h,i,j,k,..]=matrice[g,h,i,j,k,l,...]+vecteur[i] +// * @param v le vecteur +// * @param dim la dimension ou on doit mettre le vecteur doit etre egal a -1 +// * [0, -1, 3 ] ajoutera le vecteur dans la dimension 2 +// */ +// public MatrixND addv(MatrixND v, int [] dim); + +} // MatrixND + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixNDImpl.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/MatrixNDImpl.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixNDImpl.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/MatrixNDImpl.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,158 @@ +/* *##% +* Copyright (C) 2002, 2003, 2004 Code Lutin, Cédric 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. +*##%*/ + +/* * +* MatrixNDImpl.java +* +* Created: 29 oct. 2004 +* +* @author Benjamin Poussin <poussin@codelutin.com> +* @version $Revision$ +* +* Mise a jour: $Date$ +* par : $Author$ +*/ + +package org.codelutin.math.matrix; + +import java.util.Arrays; +import java.util.List; + +public class MatrixNDImpl extends AbstractMatrixND { // MatrixNDImpl + + /** */ + private static final long serialVersionUID = 1L; + + protected BasicMatrix matrix = null; + + protected MatrixNDImpl(MatrixFactory factory, int [] dim){ + super(factory, dim); + matrix = new BasicMatrix(factory, dim); + } + protected MatrixNDImpl(MatrixFactory factory, List[] semantics){ + super(factory, semantics); + matrix = new BasicMatrix(factory, dim); + } + + protected MatrixNDImpl(MatrixFactory factory, String name, int [] dim){ + super(factory, name, dim); + matrix = new BasicMatrix(factory, dim); + } + + protected MatrixNDImpl(MatrixFactory factory, String name, int [] dim, String [] dimNames){ + super(factory, name, dim, dimNames); + matrix = new BasicMatrix(factory, dim); + } + + protected MatrixNDImpl(MatrixFactory factory, String name, List[] semantics){ + super(factory, name, semantics); + matrix = new BasicMatrix(factory, dim); + } + + protected MatrixNDImpl(MatrixFactory factory, String name, List[] semantics, String [] dimNames){ + super(factory, name, semantics, dimNames); + matrix = new BasicMatrix(factory, dim); + } + + protected MatrixNDImpl(MatrixFactory factory, MatrixND matrix){ + super(factory, matrix.getName(), matrix.getSemantics(), matrix.getDimensionName()); + this.matrix = new BasicMatrix(factory, dim); + this.paste(matrix); + } + + public MatrixIterator iterator(){ + return new MatrixIteratorImpl(matrix.iterator(), getSemantics()); + } + public double getValue(int [] coordinates){ + return matrix.getValue(coordinates); + } + public void setValue(int [] coordinates, double d){ + matrix.setValue(coordinates, d); + } + + public double getMaxOccurence(){ + return matrix.getMaxOccurence(); + } + + public String toString(){ + return getName() + " " + matrix.toString(); + } + + // Un peu d'optimisation pour les matrices entieres (pas de sub matrix) + /** + * Si le vector utilise par la BasicMatix supporte la method map, + * on l'utilise pour gagner du temps + */ + @Override + public MatrixND map(MapFunction f){ + if (matrix.data.isImplementedMap()) { + matrix.data.map(f); + } else { + super.map(f); + } + return this; + } + + /** + * Si on peut on utilise le paste du vector de BasicMatix, sinon + * on utilise la methode de AbstractMatrixND. + */ + public MatrixND paste(int [] origin, MatrixND mat){ + // permet de savoir si l'origin est bien le point 0 de la matrice + boolean origin0 = true; + for (int i=0; i<origin.length && origin0; i++) { + origin0 = origin0 && origin[i] == 0; + } + if (origin0 && mat instanceof MatrixNDImpl && + Arrays.equals(mat.getDim(), this.getDim()) && + matrix.data.isImplementedPaste(((MatrixNDImpl)mat).matrix.data)){ + matrix.data.paste(((MatrixNDImpl)mat).matrix.data); + } else { + super.paste(origin, mat); + } + return this; + } + + public MatrixND add(MatrixND m){ + if (m instanceof MatrixNDImpl && + matrix.data.isImplementedAdd(((MatrixNDImpl)m).matrix.data)){ + matrix.data.add(((MatrixNDImpl)m).matrix.data); + } else { + super.add(m); + } + 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){ + if (m instanceof MatrixNDImpl && + matrix.data.isImplementedMinus(((MatrixNDImpl)m).matrix.data)){ + matrix.data.minus(((MatrixNDImpl)m).matrix.data); + } else { + super.minus(m); + } + return this; + } +} // MatrixNDImpl + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/SemanticList.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/SemanticList.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/SemanticList.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/SemanticList.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,102 @@ +/* *##% + * Copyright (C) 2006 + * Code Lutin, Cédric 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. + *##%*/ + +/* * + * SemanticList.java + * + * Created: 6 sept. 06 17:18:23 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.codelutin.math.matrix; + +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.RandomAccess; + + +/** + * @author poussin + * + */ + +public class SemanticList<T> extends AbstractList<T> implements RandomAccess { + + protected ArrayList<T> datas = null; + protected Map<Object, Integer> index = null; + + public SemanticList(Collection<T> c) { + datas = new ArrayList<T>(c); + } + + /* (non-Javadoc) + * @see java.util.AbstractList#get(int) + */ + @Override + public T get(int index) { + T result = datas.get(index); + return result; + } + + /* (non-Javadoc) + * @see java.util.AbstractCollection#size() + */ + @Override + public int size() { + int result = datas.size(); + return result; + } + + /* (non-Javadoc) + * @see java.util.AbstractList#indexOf(java.lang.Object) + */ + @Override + public int indexOf(Object o) { + Map index = getIndex(); + Integer result = (Integer)index.get(o); + if (result == null) { + return -1; + } else { + return result.intValue(); + } + } + + /** + * @return + */ + private Map getIndex() { + if (index == null) { + index = new HashMap<Object, Integer>(); + for (int i=0; i<datas.size(); i++) { + index.put(datas.get(i), Integer.valueOf(i)); + } + } + return index; + } +} + + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/SubMatrix.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/SubMatrix.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/SubMatrix.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/SubMatrix.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,206 @@ +/* *##% + * Copyright (C) 2002, 2003, 2004 Code Lutin, Cédric 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. + *##%*/ + +/* * + * SubMatrix.java + * + * Created: 29 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.codelutin.math.matrix; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.NoSuchElementException; + +/** +* Pour l'instant une sous matrice a obligatoirement le meme nombre +* de dimension que la matrice qu'elle contient. +* Elle permet juste de reduire le nombre d'element d'une dimension. +*/ +public class SubMatrix extends AbstractMatrixND { // SubMatrix + + /** */ + private static final long serialVersionUID = 1L; + + protected MatrixND matrix = null; + protected DimensionConverter converter = null; + + public SubMatrix(MatrixND matrix, int dim, int start, int nb){ + super(matrix.getFactory(), matrix.getName(), matrix.getSemantics(), matrix.getDimensionName()); + this.matrix = matrix; + + converter = new ShiftConverter(dim, start, nb); + setSemantics(dim, getSemantics(dim).subList(start, start + nb)); + getDim()[dim] = nb; + } + + public SubMatrix(MatrixND matrix, int dim, int [] elem){ + super(matrix.getFactory(), matrix.getName(), matrix.getSemantics(), matrix.getDimensionName()); + this.matrix = matrix; + + converter = new MappingConverter(dim, elem); + + List oldSemantic = getSemantics(dim); + List newSemantic = new LinkedList(); + for(int i=0; i<elem.length; i++){ + newSemantic.add(oldSemantic.get(elem[i])); + } + setSemantics(dim, newSemantic); + getDim()[dim] = elem.length; + } + + public MatrixIterator iterator(){ + return new SubMatrixIteratorImpl(this); + } + + public double getValue(int [] coordinates){ + return matrix.getValue(converter.convertCoordinates(coordinates)); + } + + public void setValue(int [] coordinates, double d){ + matrix.setValue(converter.convertCoordinates(coordinates), d); + } + + protected class SubMatrixIteratorImpl implements MatrixIterator { + + protected SubMatrix subMatrix = null; + protected int [] cpt = null; + protected int [] last = null; + + public SubMatrixIteratorImpl(SubMatrix subMatrix){ + this.subMatrix = subMatrix; + cpt = new int[subMatrix.getNbDim()]; + cpt[cpt.length-1] = -1; + + last = new int[subMatrix.getNbDim()]; + for(int i=0; i<last.length; i++){ + last[i] = subMatrix.getDim(i) - 1; + } + + } + + public boolean hasNext(){ + return !Arrays.equals(cpt, last); + } + + public boolean next(){ + boolean result = hasNext(); + int ret = 1; + int [] dim = getDim(); + for(int i=cpt.length-1; i>=0; i--){ + cpt[i] = cpt[i] + ret; + ret = cpt[i] / dim[i]; + cpt[i] = cpt[i] % dim[i]; + } + return result; + } + + public int [] getCoordinates(){ + return cpt; + } + + public Object [] getSemanticsCoordinates(){ + int [] coordinates = getCoordinates(); + Object [] result = MatrixHelper.dimensionToSemantics(subMatrix.getSemantics(), coordinates); + return result; + } + + public double getValue(){ + return subMatrix.getValue(getCoordinates()); + } + + public void setValue(double value){ + subMatrix.setValue(getCoordinates(), value); + } + + } + + + /** + * Permet de faire une conversion de la dimension demandé dans la sous + * matrice avec la position reel de la matrice sous jacente. + */ + protected interface DimensionConverter extends Serializable { + public int [] convertCoordinates(int [] coordinates); + } + + /** + * La conversion est juste un decalage d'indice + */ + protected class ShiftConverter implements DimensionConverter { + /** */ + private static final long serialVersionUID = 1L; + + protected int dim; + protected int start; + protected int nb; + public ShiftConverter(int dim, int start, int nb){ + this.dim = dim; + this.start = start; + this.nb = nb; + } + public int [] convertCoordinates(int [] coordinates){ + if(coordinates[dim] < nb){ + int [] result = new int[coordinates.length]; + System.arraycopy(coordinates, 0, result, 0, result.length); + result[dim] = result[dim] + start; + return result; + }else{ + throw new NoSuchElementException("L'indice est supérieur au nombre d'élement de la sous matrice pour cette dimension."); + } + } + } + + /** + * La conversion est le mapping d'un element vers un autre element + */ + protected class MappingConverter implements DimensionConverter { + /** */ + private static final long serialVersionUID = 1L; + + protected int dim; + protected int [] elem = null; + public MappingConverter(int dim, int [] elem){ + this.dim = dim; + this.elem = new int[elem.length]; + System.arraycopy(elem, 0, this.elem, 0, elem.length); + } + public int [] convertCoordinates(int [] coordinates){ + if(coordinates[dim] < elem.length){ + int [] result = new int[coordinates.length]; + System.arraycopy(coordinates, 0, result, 0, result.length); + result[dim] = elem[coordinates[dim]]; + return result; + }else{ + throw new NoSuchElementException("L'indice est supérieur au nombre d'élement de la sous matrice pour cette dimension."); + } + } + } + +} // SubMatrix + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/Vector.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/Vector.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/Vector.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/Vector.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,76 @@ +/* *##% + * Copyright (C) 2005 + * Code Lutin, Cédric 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. + *##%*/ + +/* * + * Vector.java + * + * Created: 6 octobre 2005 02:51:12 CEST + * + * @author Benjamin POUSSIN <poussin@codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.codelutin.math.matrix; + +public interface Vector { // Vector + + public double getMaxOccurence(); + public double getValue(int pos); + public void setValue(int pos, double value); + public int size(); + + /** + * Permet de savoir si paste est implanté par ce vector + */ + public boolean isImplementedPaste(Vector v); + /** + * Permet de savoir si add est implanté par ce vector + */ + public boolean isImplementedAdd(Vector v); + /** + * Permet de savoir si minus est implanté par ce vector + */ + public boolean isImplementedMinus(Vector v); + /** + * Permet de savoir si map est implanté par ce vector + */ + public boolean isImplementedMap(); + + /** + * Copie les valeurs du vector passé en argument dans ce vector + */ + public void paste(Vector v); + /** + * Ajoute les valeurs du vector passé en argument a ce vector + */ + public void add(Vector v); + /** + * soustrai les valeurs du vector passé en argument a ce vector + */ + public void minus(Vector v); + /** + * applique a chaque valeur du vector la MapFunction + */ + public void map(MapFunction f); + +} // Vector + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixPanelEditor.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/gui/MatrixPanelEditor.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixPanelEditor.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixPanelEditor.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,446 @@ +/* + * *##% Copyright (C) 2002, 2003, 2004 Code Lutin, Cédric 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. ##% + */ + +/******************************************************************************* + * MatrixPanelEditor.java + * + * Created: 4 nov. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * + * @version $Revision$ + * + * Mise a jour: $Date$ par : $Author$ + */ + +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 + */ +public class MatrixPanelEditor extends JPanel implements TableModelListener { // MatrixPanelEditor + + /** */ + 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 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(); + } + + JButton bEdit = null; + + protected 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); + 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(); + } + + /** + * @deprecated use setMatrix + */ + public void setMatrice(MatrixND m) throws MatrixException { + setMatrix(m); + } + + public MatrixND getMatrix() { +// if (m == null) { + return m; +// } else if (m.getNbDim() <= 2) { +// return m; +// } else { +// return MatrixHelper.decodeFromXML(text.getText()); +// } + } + /** + * @deprecated use setMatrix + */ + public MatrixND getMatrice() { + return getMatrix(); + } + + /** + * Enable the matrix to be edited. By default, the matrix is editable. + */ + public void setEnabled(boolean enabled) { + if (tableModel != null) { + tableModel.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; + } + + /* (non-Javadoc) + * @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: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixPanelEvent.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/gui/MatrixPanelEvent.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixPanelEvent.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixPanelEvent.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,59 @@ +/* *##% + * Copyright (C) 2006 + * Code Lutin, Cédric 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. + *##%*/ + +/* * + * MatrixPanelEvent.java + * + * Created: 21 mars 2006 14:53:25 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.codelutin.math.matrix.gui; + +import java.util.EventObject; + +import org.codelutin.math.matrix.MatrixND; + + +/** + * @author poussin + * + */ + +public class MatrixPanelEvent extends EventObject { + + /** + * @param source + */ + public MatrixPanelEvent(MatrixPanelEditor source) { + super(source); + } + + public MatrixND getMatrix() { + MatrixND result = ((MatrixPanelEditor)getSource()).getMatrix(); + return result; + } +} + + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixPanelListener.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/gui/MatrixPanelListener.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixPanelListener.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixPanelListener.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,51 @@ +/* *##% + * Copyright (C) 2006 + * Code Lutin, Cédric 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. + *##%*/ + +/* * + * MatrixPanelListener.java + * + * Created: 21 mars 2006 14:54:05 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.codelutin.math.matrix.gui; + + +/** + * @author poussin + * + */ + +public interface MatrixPanelListener { + + /** + * called when matrix change + * + * @param e + */ + public void matrixChanged(MatrixPanelEvent e); + +} + + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixPopupMenu.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/gui/MatrixPopupMenu.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixPopupMenu.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixPopupMenu.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,543 @@ +/* *##% + * Copyright (C) 2006 + * Code Lutin, Cédric 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. + *##%*/ + +/* * + * MatrixPopupMenu.java + * + * Created: 22 mars 2006 12:11:46 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +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 + * + * @author ruchaud + * + */ +public class MatrixPopupMenu extends JPopupMenu { + + private MatrixPanelEditor 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(MatrixPanelEditor 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(); + 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(); + 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(); + 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(); + 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: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixTableModel.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/gui/MatrixTableModel.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixTableModel.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixTableModel.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,53 @@ +/* *##% + * Copyright (C) 2006 + * Code Lutin, Cédric 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. + *##%*/ + +/* * + * MatrixTableModel.java + * + * Created: 22 mars 2006 12:53:22 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.codelutin.math.matrix.gui; + +import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableModel; + +import org.codelutin.math.matrix.MatrixND; + + +/** + * @author poussin + * + */ + +public interface MatrixTableModel extends TableModel { + + public void setMatrix(MatrixND m); + public void setEnabled(boolean enabled); + public TableCellRenderer getMatrixCellRenderer(); + +} + + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixTableModelLinear.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/gui/MatrixTableModelLinear.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixTableModelLinear.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixTableModelLinear.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,275 @@ +/* *##% + * Copyright (C) 2006 + * Code Lutin, Cédric 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. + *##%*/ + +/* * + * MatrixTableModelLinear.java + * + * Created: 22 mars 2006 12:11:46 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.codelutin.math.matrix.gui; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Font; +import java.util.ArrayList; +import java.util.List; + +import javax.swing.JTable; +import javax.swing.UIManager; +import javax.swing.border.Border; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableCellRenderer; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.codelutin.math.matrix.MatrixIterator; +import org.codelutin.math.matrix.MatrixND; + + +/** + * @author poussin + * + */ + +public class MatrixTableModelLinear extends AbstractTableModel implements MatrixTableModel { + + /** + * Logger for this class + */ + private static final Log log = LogFactory + .getLog(MatrixTableModelLinear.class); + + protected boolean enabled = true; + protected MatrixND m = null; + protected boolean showDefault = false; + protected double defaultValue = 0; + protected List<Object[]> mappingRowSems = new ArrayList<Object[]>(); + protected TableCellRenderer renderer = null; + + public MatrixTableModelLinear(MatrixND m, boolean showDefault) { + this.showDefault = showDefault; + setMatrix(m); + } + + public void setMatrix(MatrixND m) { + this.m = m; + computeMapping(); + fireTableStructureChanged(); + } + + protected void computeMapping() { + mappingRowSems.clear(); + for (MatrixIterator i=m.iterator(); i.next();) { + Object [] sems = i.getSemanticsCoordinates(); + double value = i.getValue(); + if (showDefault || value != defaultValue) { + mappingRowSems.add(sems); + } + } + } + + /** + * @return Returns the enabled. + */ + public boolean isEnabled() { + return this.enabled; + } + + /** + * @param enabled The enabled to set. + */ + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + /** + * @return Returns the showDefault. + */ + public boolean isShowDefault() { + return this.showDefault; + } + + /** + * @param showDefault The showDefault to set. + */ + public void setShowDefault(boolean showDefault) { + this.showDefault = showDefault; + computeMapping(); + fireTableDataChanged(); + } + + /** + * @return Returns the defaultValue. + */ + public double getDefaultValue() { + return this.defaultValue; + } + + /** + * @param defaultValue The defaultValue to set. + */ + public void setDefaultValue(double defaultValue) { + this.defaultValue = defaultValue; + computeMapping(); + fireTableDataChanged(); + } + + /* (non-Javadoc) + * @see javax.swing.table.TableModel#getRowCount() + */ + public int getRowCount() { + return mappingRowSems.size(); + } + + /* (non-Javadoc) + * @see javax.swing.table.TableModel#getColumnCount() + */ + public int getColumnCount() { + return m.getNbDim() + 1; + } + + /* (non-Javadoc) + * @see javax.swing.table.TableModel#getValueAt(int, int) + */ + public Object getValueAt(int rowIndex, int columnIndex) { + Object result = null; + if (columnIndex < m.getNbDim()) { + result = mappingRowSems.get(rowIndex)[columnIndex]; + } else { + result = m.getValue(mappingRowSems.get(rowIndex)); + } + return result; + } + + /* (non-Javadoc) + * @see javax.swing.table.AbstractTableModel#isCellEditable(int, int) + */ + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + return isEnabled() && columnIndex == m.getNbDim(); + } + + /* (non-Javadoc) + * @see javax.swing.table.AbstractTableModel#setValueAt(java.lang.Object, int, int) + */ + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + try { + double val = Double.parseDouble((String) aValue); + Object [] sems = mappingRowSems.get(rowIndex); + m.setValue(sems, val); + fireTableDataChanged(); + } catch (Exception eee) { + log.debug("La nouvelle valeur n'est pas convertible en double: " + + aValue, eee); + } + + } + + /* (non-Javadoc) + * @see javax.swing.table.AbstractTableModel#getColumnName(int) + */ + @Override + public String getColumnName(int column) { + String result = null; + if (column < m.getNbDim()) { + result = m.getDimensionName(column); + } else { + result = ""; + } + return result; + } + + /** + * Par defaut, la classe de la colonne est du type Function.class + */ + public Class getColumnClass(int column) { + return String.class; + } + + /** + * @return + */ + public TableCellRenderer getMatrixCellRenderer() { + if (renderer == null) { + renderer = new MatrixCellRenderer(this); + } + return renderer; + } + + + class MatrixCellRenderer extends DefaultTableCellRenderer { + + protected MatrixTableModelLinear model = null; + protected Color bg = null; + protected Color fg = null; + protected Font font = null; + protected Border border = null; + + public MatrixCellRenderer(MatrixTableModelLinear model) { + this.model = model; + bg = getBackground(); + fg = getForeground(); + font = getFont(); + border = getBorder(); + } + + /** */ + private static final long serialVersionUID = 6537813058357761914L; + + public Component getTableCellRendererComponent(JTable table, Object value, + boolean isSelected, boolean hasFocus, int row, int column) { + super.getTableCellRendererComponent(table, value, isSelected, hasFocus, + row, column); + setToolTipText(getText()); + + if (column < model.m.getNbDim()) { + if (table != null) { + JTableHeader header = table.getTableHeader(); + if (header != null) { + setForeground(header.getForeground()); + setBackground(header.getBackground()); + setFont(header.getFont()); + } + } + + setBorder(UIManager.getBorder("TableHeader.cellBorder")); + } else { + setBackground(bg); + setForeground(fg); + setFont(font); + setBorder(border); + } + + return this; + } + } + +} + + Copied: trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixTableModelND.java (from rev 61, trunk/lutinmatrix/src/java/org/codelutin/math/matrix/gui/MatrixTableModelND.java) =================================================================== --- trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixTableModelND.java (rev 0) +++ trunk/lutinmatrix/src/main/java/org/codelutin/math/matrix/gui/MatrixTableModelND.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,369 @@ +/* *##% + * Copyright (C) 2006 + * Code Lutin, Cédric 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. + *##%*/ + +/* * + * MatrixTableModel.java + * + * Created: 21 mars 2006 19:01:27 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.codelutin.math.matrix.gui; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Font; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.swing.JTable; +import javax.swing.UIManager; +import javax.swing.border.Border; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableCellRenderer; + +import org.codelutin.math.matrix.MatrixException; +import org.codelutin.math.matrix.MatrixND; + + +/** + * @author poussin + * + */ + +public /** + * Extension de AbstractTableModel pour definir un TableModel avec une MatrixND + * comme support d'information. + * + * @todo changer les 'matrice' en 'matrix', s'il y a des methodes public avec + * les nom 'matice' les laisser mais les mettres depreciées + */ +class MatrixTableModelND extends AbstractTableModel implements MatrixTableModel { + + /** */ + private static final long serialVersionUID = 983978774901981167L; + + protected MatrixND m; + + /** nombre de ligne ajouté */ + protected int addRow = 0; + /** nombre de colone ajouté */ + protected int addCol = 0; + + protected int [] multRowCol = null; + + /** par defaut, la matrice est editable. */ + protected boolean enabled = true; + + protected TableCellRenderer renderer = null; + + /** + * TableModel basee sur une MatrixND a une ou deux dimensions. Pour le + * moment les matrices de plus de 3 dimensions ne sont pas geree. + * <p> + * Pour les matrices 1D : + * <p> + * La premiere dimension represente les colonnes. + * <p> + * Pour les matrices 2D : + * <p> + * La premiere dimension represente les lignes. + * <p> + * La deuxieme dimension represente les colonnes. + * <p> + * Pour les matrices 3D : + * <p> + * La premiere dimension represente les lignes. + * <p> + * La deuxieme dimension represente les colonnes. + * <p> + * La troisieme dimension represente les lignes (dim1 x dim3). + * + * @param m Matrice a afficher dans la table + */ + public MatrixTableModelND(MatrixND m) throws MatrixException { + setMatrix(m); + } + + public void setMatrix(MatrixND m) { + this.m = m; + addRow = m.getNbDim() / 2; + addCol = (m.getNbDim() + 1) / 2; + + // calcule les coefficients multiplicateur pour la correspondance table/matrice + multRowCol = new int[m.getNbDim()]; + for (int i=multRowCol.length-1; i>=0; i--) { + if (i >= multRowCol.length - 2) { + multRowCol[i] = 1; + } else { + multRowCol[i] = multRowCol[i+2] * m.getDim(i+2); + } + } + } + + /** + * converti les coordonnées de la table en coordonnées pour la matrice + * + * @param row la ligne dans la table + * @param col la colonne dans la table + * @return les coordonnées equivalentes dans la matrice + */ + protected int [] tableToMatrix(int row, int col) { + int [] result = new int[m.getNbDim()]; + for (int i=0; i<result.length; i++) { + int val = row; + if (i%2 == 1) { // si impaire alors la valeur vient de la colonne + val = col; + } + result[i] = tableToMatrixCell(i, val); + } + return result; + } + + protected int tableToMatrixCell(int dim, int tableValue) { + int b = 0; + int val = tableValue; + if (dim % 2 == 1) { // si impaire alors la valeur vient de la colonne + b = 1; // les colonnes represente toutes les dim impaires + } + while (b < dim) { + val = val % multRowCol[b]; + b += 2; + } + int result = val / multRowCol[b]; + return result; + } + + protected Object getValue(int row, int col) { + Object result = null; + if (row < addRow && col < addCol) { + if (row == addRow - 1 && col == addCol - 1) { + result = m.getDimensionName(col * 2) + "\\" + m.getDimensionName(row * 2 + 1); + } else if (row == addRow - 1) { + result = m.getDimensionName(col * 2); + } else if (col == addCol - 1) { + result = m.getDimensionName(row * 2 + 1); + } else { + result = ""; + } + } else if (row < addRow) { + result = getSemantic(row * 2 + 1, tableToMatrixCell(row * 2 + 1, col - addCol)); + } else if (col < addCol) { + result = getSemantic(col * 2, tableToMatrixCell(col * 2, row - addRow)); + } else { + result = m.getValue(tableToMatrix(row - addRow, col - addCol)); + } + return result; + } + + /** + * Retourne une representation String de la semantique de l'element elem de + * la dimension dim + * + * @param dim la dimension dans lequel on recherche l'element + * @param elem l'element de la dimension a prendre + * @return une chaine representant l'element. Si l'element est null, la + * chaine vide est retourné + */ + protected String getSemantic(int dim, int elem) { + + Object o = m.getSemantics(dim).get(elem); + return (o == null) ? "" : o.toString(); + } + + public String getColumnName(int column) { + return null; +// String result = null; +// if (m.getNbDim() != 1) { +// result = getValue(0, column).toString(); +// } else { +// result = getValue(column, 0).toString(); +// } +// return result; + } + + /** + * @return Le nombre de lignes de la table. + */ + public int getRowCount() { + int result = 0; + if (m.getNbDim() != 1) { +// result = multRowCol[0] * m.getDim(0) + addRow - 1; // -1 pour le header + result = multRowCol[0] * m.getDim(0) + addRow; + } else { + result = 2; + } + return result; + } + + /** + * @return Le nombre de colonnes de la table. + */ + public int getColumnCount() { + int result = 0; + if (m.getNbDim() != 1) { + result = multRowCol[1] * m.getDim(1) + addCol; + } else { + result = m.getDim(0); + } + return result; + } + + /** + * @param row La ligne + * @param column La colonnes + * @return L'Object correspondant dans la matrice. + */ + public Object getValueAt(int row, int column) { + Object result = null; + if (m.getNbDim() != 1) { +// // on fait row + 1 a cause du header +// result = getValue(row + 1, column); + result = getValue(row, column); + } else { + result = getValue(column, row); + } + return result; + } + + /** + * @param obj L'objet a inserer dans la matrice. + * @param row La ligne + * @param column La colonnes + */ + public void setValueAt(Object obj, int row, int column) { + if ((m.getNbDim() != 1 && row >= addRow && column >= addCol) + || (m.getNbDim() == 1 && row >= 1) ) { + try { + double val = Double.parseDouble((String) obj); + int [] coord = null; + if (m.getNbDim() != 1) { +// coord = tableToMatrix(row - addRow + 1, column - addCol); // +1 pour le header + coord = tableToMatrix(row - addRow, column - addCol); + } else { + coord = new int[]{column}; + } + m.setValue(coord, val); + fireTableDataChanged(); + } catch (Exception eee) { + Logger.getLogger(getClass().getName() + ".setValueAt").log( + Level.FINE, + "La nouvelle valeur n'est pas convertible en double: " + + obj, eee); + } + } + } + + /** + * Le modele est rendu editable. + */ + public boolean isCellEditable(int row, int column) { + if (m.getNbDim() != 1 && (row < addRow || column < addCol)) { + return false; + } else if (m.getNbDim() == 1 && row < 1) { + return false; + } + return enabled; + } + + /** + * Permet de rendre la table editable ou non . + */ + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + /** + * Par defaut, la classe de la colonne est du type Function.class + */ + public Class getColumnClass(int column) { + return String.class; + } + + /** + * @return + */ + public TableCellRenderer getMatrixCellRenderer() { + if (renderer == null) { + renderer = new MatrixCellRenderer(this); + } + return renderer; + } + + + class MatrixCellRenderer extends DefaultTableCellRenderer { + + protected MatrixTableModelND model = null; + protected Color bg = null; + protected Color fg = null; + protected Font font = null; + protected Border border = null; + + public MatrixCellRenderer(MatrixTableModelND model) { + this.model = model; + bg = getBackground(); + fg = getForeground(); + font = getFont(); + border = getBorder(); + } + + /** */ + private static final long serialVersionUID = 6537813058357761914L; + + public Component getTableCellRendererComponent(JTable table, Object value, + boolean isSelected, boolean hasFocus, int row, int column) { + super.getTableCellRendererComponent(table, value, isSelected, hasFocus, + row, column); + setToolTipText(getText()); + + if ((model.m.getNbDim() != 1 && (row < model.addRow || column < model.addCol)) + || (model.m.getNbDim() == 1 && row < 1)) { + if (table != null) { + JTableHeader header = table.getTableHeader(); + if (header != null) { + setForeground(header.getForeground()); + setBackground(header.getBackground()); + setFont(header.getFont()); + } + } + + setBorder(UIManager.getBorder("TableHeader.cellBorder")); + } else { + setBackground(bg); + setForeground(fg); + setFont(font); + setBorder(border); + return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, + row, column); + } + + return this; + } + } + +} + + Copied: trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/BasicMatrixBigTest.java (from rev 61, trunk/lutinmatrix/src/test/org/codelutin/math/matrix/BasicMatrixBigTest.java) =================================================================== --- trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/BasicMatrixBigTest.java (rev 0) +++ trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/BasicMatrixBigTest.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,42 @@ +/* *##% + * Copyright (C) 2002, 2003 Code Lutin, Cédric 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. + *##%*/ + +/* * + * MatriceTest.java + * + * Created: 27 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.codelutin.math.matrix; + + +public class BasicMatrixBigTest extends BasicMatrixTest { // BasicMatrixTest + + public MatrixFactory getFactory() throws Exception { + return MatrixFactory.getInstance(FloatBigVector.class); + } + +} // BasicMatrixTest + Copied: trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/BasicMatrixTest.java (from rev 61, trunk/lutinmatrix/src/test/org/codelutin/math/matrix/BasicMatrixTest.java) =================================================================== --- trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/BasicMatrixTest.java (rev 0) +++ trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/BasicMatrixTest.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,313 @@ +/* *##% + * Copyright (C) 2002, 2003 Code Lutin, Cédric 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. + *##%*/ + +/* * + * MatriceTest.java + * + * Created: 27 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.codelutin.math.matrix; + +import java.util.Arrays; +import java.util.NoSuchElementException; + +import org.apache.commons.lang.time.DurationFormatUtils; + +import junit.framework.TestCase; + +public class BasicMatrixTest extends TestCase { // BasicMatrixTest + + public MatrixFactory getFactory() throws Exception { + return MatrixFactory.getInstance(); + } + + public void testNew() throws Exception { + BasicMatrix mat = null; + try{ + mat = new BasicMatrix(getFactory(), null); + assertFalse(true); // on ne doit pas etre ici + }catch(NullPointerException eee){ + assertTrue(true); // mais on doit etre la + } + + try{ + mat = new BasicMatrix(getFactory(), new int[]{0}); + assertFalse(true); // on ne doit pas etre ici + }catch(IllegalArgumentException eee){ + assertTrue(true); // mais on doit etre la + } + + mat = new BasicMatrix(getFactory(), new int[]{100}); + mat = new BasicMatrix(getFactory(), new int[]{10,1}); + assertEquals(0.0, mat.getMaxOccurence()); + mat = new BasicMatrix(getFactory(), new int[]{10,10,10,10}); + try{ + mat = new BasicMatrix(getFactory(), new int[]{-10}); + assertFalse(true); // on ne doit pas etre ici + }catch(IllegalArgumentException eee){ + assertTrue(true); // mais on doit etre la + } + try{ + mat = new BasicMatrix(getFactory(), new int[]{10, 20, -10, 20}); + assertFalse(true); // on ne doit pas etre ici + }catch(IllegalArgumentException eee){ + assertTrue(true); // mais on doit etre la + } + } + + public void testDimension()throws Exception { + BasicMatrix mat = null; + mat = new BasicMatrix(getFactory(), new int[]{1,10,30,5}); + + assertEquals(4, mat.getNbDim()); + assertEquals(1, mat.getDim(0)); + assertEquals(10, mat.getDim(1)); + assertEquals(30, mat.getDim(2)); + assertEquals(5, mat.getDim(3)); + + try{ + mat.getDim(-3); + assertFalse(true); // on ne doit pas etre ici + }catch(IndexOutOfBoundsException eee){ + assertTrue(true); // mais on doit etre la + } + try{ + mat.getDim(4); + assertFalse(true); // on ne doit pas etre ici + }catch(IndexOutOfBoundsException eee){ + assertTrue(true); // mais on doit etre la + } + } + + public void testGetSet() throws Exception { + BasicMatrix mat = null; + + // test avec la plus petit BasicMatrix possible + mat = new BasicMatrix(getFactory(), new int[]{1}); + // test la valeur par defaut doit etre 0 + assertEquals(0, mat.getValue(new int[]{0}), 0); + mat.setValue(new int[]{0}, 30); + assertEquals(30, mat.getValue(new int[]{0}), 0); + + // acces a un element qui n'existe pas + try{ + mat.getValue(new int[]{1}); + assertFalse(true); // on ne doit pas etre ici + }catch(NoSuchElementException eee){ + assertTrue(true); // mais on doit etre la + } + + mat = new BasicMatrix(getFactory(), new int[]{1, 10, 5}); + mat.setValue(new int[]{0, 0, 0}, 0); + mat.setValue(new int[]{0, 0, 1}, 1); + mat.setValue(new int[]{0, 0, 2}, 2); + mat.setValue(new int[]{0, 0, 3}, 3); + mat.setValue(new int[]{0, 0, 4}, 4); + mat.setValue(new int[]{0, 1, 0}, 10); + mat.setValue(new int[]{0, 1, 1}, 11); + mat.setValue(new int[]{0, 1, 2}, 12); + mat.setValue(new int[]{0, 1, 3}, 13); + mat.setValue(new int[]{0, 1, 4}, 14); + mat.setValue(new int[]{0, 2, 0}, 20); + mat.setValue(new int[]{0, 2, 1}, 21); + mat.setValue(new int[]{0, 2, 2}, 22); + mat.setValue(new int[]{0, 9, 4}, 98); + mat.setValue(new int[]{0, 4, 2}, 97); + assertEquals(0, mat.getValue(new int[]{0, 0, 0}), 0); + assertEquals(98, mat.getValue(new int[]{0, 9, 4}), 0); + assertEquals(97, mat.getValue(new int[]{0, 4, 2}), 0); + + //System.out.println(mat.toString()); + + // acces a un element qui n'existe pas + try{ + mat.setValue(new int[]{0, 9, 5}, 44); + assertFalse(true); // on ne doit pas etre ici + }catch(NoSuchElementException eee){ + assertTrue(true); // mais on doit etre la + } + + } + + public void testEquals() throws Exception { + BasicMatrix m1 = new BasicMatrix(getFactory(), new int[]{3,3,3,3}); + BasicMatrix m2 = new BasicMatrix(getFactory(), new int[]{3,3,3,3}); + + assertEquals(m1, m2); + + m1.setValue(new int[]{1,2,1,2}, 123); + m2.setValue(new int[]{1,2,1,2}, 123); + + assertEquals(m1, m2); + + m1.setValue(new int[]{1,0,1,0}, 321); + assertFalse(m1.equals(m2)); + } + + public void testIterator() throws Exception { + + int [][] val27 = new int[][]{ + {0,0,0}, + {0,0,1}, + {0,0,2}, + {0,1,0}, + {0,1,1}, + {0,1,2}, + {0,2,0}, + {0,2,1}, + {0,2,2}, + {1,0,0}, + {1,0,1}, + {1,0,2}, + {1,1,0}, + {1,1,1}, + {1,1,2}, + {1,2,0}, + {1,2,1}, + {1,2,2}, + {2,0,0}, + {2,0,1}, + {2,0,2}, + {2,1,0}, + {2,1,1}, + {2,1,2}, + {2,2,0}, + {2,2,1}, + {2,2,2}, + }; + int [][] val1 = new int[][]{{0}}; + + BasicMatrix m1 = new BasicMatrix(getFactory(), new int[]{3,3,3}); +// System.out.println("Matrice a 27 valeurs"); + int cpt = 0; + for(BasicMatrixIterator iter = m1.iterator(); iter.next();){ + Arrays.equals(val27[cpt], iter.getCoordinates()); + cpt ++; + } + + assertEquals(27, cpt); + + cpt = 0; + BasicMatrix m2 = new BasicMatrix(getFactory(), new int[]{1}); +// System.out.println("Matrice a 1 valeurs"); + for(BasicMatrixIterator iter = m2.iterator(); iter.next();){ + Arrays.equals(val1[cpt], iter.getCoordinates()); + cpt ++; + } + + assertEquals(1, cpt); + } + + MapFunction f = new MapFunction(){ + public double apply(double value){ + return value + 2; + } + }; + + public void testPerfLineaire() throws Exception { + long time = System.nanoTime(); + BasicMatrix m1 = new BasicMatrix(getFactory(), new int[]{30,30,30,30}); + m1.map(f); + long time1 = System.nanoTime(); + System.out.println("testPerfLineaire: " + DurationFormatUtils.formatDuration((time1 - time)/1000000, "s'.'S")); + } + + public void testPerfCoordonnee() throws Exception { + long time = System.nanoTime(); + BasicMatrix m2 = new BasicMatrix(getFactory(), new int[]{30,30,30,30}); + + BasicMatrixIterator inc = m2.iterator(); + while(inc.next()){ + inc.setValue(inc.getValue() + 2); + } + long time1 = System.nanoTime(); + System.out.println("testPerfCoordonnee iter: " + DurationFormatUtils.formatDuration((time1 - time)/1000000, "s'.'S")); + + inc = m2.iterator(); + while(inc.next()){ + inc.setValue(inc.getValue() + 2); + } + long time2 = System.nanoTime(); + System.out.println("testPerfCoordonnee iter: " + DurationFormatUtils.formatDuration((time2 - time1)/1000000, "s'.'S")); + + m2.map(f); + long time3 = System.nanoTime(); + System.out.println("testPerfLineaire map: " + DurationFormatUtils.formatDuration((time3 - time2)/1000000, "s'.'S")); + + } + + public void testPerfCoordonnee2() throws Exception { + long time = System.nanoTime(); + BasicMatrix m2 = new BasicMatrix(getFactory(), new int[]{30,30,30,30}); + + BasicMatrixIterator inc = m2.iterator(); + while(inc.next() && inc.next()){ + inc.setValue(inc.getValue() + 2); + } + long time1 = System.nanoTime(); + System.out.println("testPerfCoordonnee2: " + DurationFormatUtils.formatDuration((time1 - time)/1000000, "s'.'S")); + + inc = m2.iterator(); + while(inc.next() && inc.next()){ + inc.setValue(inc.getValue() + 2); + } + long time2 = System.nanoTime(); + System.out.println("testPerfCoordonnee2 re: " + DurationFormatUtils.formatDuration((time2 - time1)/1000000, "s'.'S")); + + + m2.map(f); + long time3 = System.nanoTime(); + System.out.println("testPerfLineaire2: " + DurationFormatUtils.formatDuration((time3 - time2)/1000000, "s'.'S")); + + } + + public void testPerfCoordonnee4() throws Exception { + long time = System.nanoTime(); + BasicMatrix m2 = new BasicMatrix(getFactory(), new int[]{30,30,30,30}); + + BasicMatrixIterator inc = m2.iterator(); + while(inc.next() && inc.next() && inc.next() && inc.next()){ + inc.setValue(inc.getValue() + 2); + } + long time1 = System.nanoTime(); + System.out.println("testPerfCoordonnee4: " + DurationFormatUtils.formatDuration((time1 - time)/1000000, "s'.'S")); + + inc = m2.iterator(); + while(inc.next() && inc.next() && inc.next() && inc.next()){ + inc.setValue(inc.getValue() + 2); + } + long time2 = System.nanoTime(); + System.out.println("testPerfCoordonnee4 re: " + DurationFormatUtils.formatDuration((time2 - time1)/1000000, "s'.'S")); + + + m2.map(f); + long time3 = System.nanoTime(); + System.out.println("testPerfLineaire4: " + DurationFormatUtils.formatDuration((time3 - time2)/1000000, "s'.'S")); + + } + +} // BasicMatrixTest + Copied: trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/FloatVectorTest.java (from rev 61, trunk/lutinmatrix/src/test/org/codelutin/math/matrix/FloatVectorTest.java) =================================================================== --- trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/FloatVectorTest.java (rev 0) +++ trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/FloatVectorTest.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,83 @@ +/* *##% + * Copyright (C) 2005 + * Code Lutin, Cédric 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. + *##%*/ + +/* * + * FloatVectorTest.java + * + * Created: 6 octobre 2005 01:54:49 CEST + * + * @author Benjamin POUSSIN <poussin@codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.codelutin.math.matrix; + +import junit.framework.TestCase; + +public class FloatVectorTest extends TestCase { // FloatVectorTest + + public void testAll() throws Exception { + FloatVector v = new FloatVector(16); + assertEquals(0.0, v.getMaxOccurence()); + + v.setValue(0, 1); + assertEquals(1.0, v.getValue(0)); + + v.setValue(15, 16); + assertEquals(16.0, v.getValue(15)); + + assertEquals(2, v.positionSize); + v.setValue(0, 0); + assertEquals(0.0, v.getValue(0)); + assertEquals(1, v.positionSize); + + v.setValue(0, 4); + v.setValue(1, 4); + v.setValue(2, 4); + v.setValue(3, 4); + v.setValue(4, 4); + v.setValue(5, 4); + v.setValue(6, 4); + assertEquals(0.0, v.getMaxOccurence()); + v.setValue(8, 4); + assertEquals(4.0, v.getMaxOccurence()); + v.setValue(0, 0); + assertEquals(0.0, v.getMaxOccurence()); + + try { + v.getValue(-1); + assertTrue(false); + } catch (IllegalArgumentException eee) { + assertTrue(true); + } + + try { + v.getValue(20); + assertTrue(false); + } catch (IllegalArgumentException eee) { + assertTrue(true); + } + + } + +} // FloatVectorTest + Copied: trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/ImportExportMatrixTest.java (from rev 61, trunk/lutinmatrix/src/test/org/codelutin/math/matrix/ImportExportMatrixTest.java) =================================================================== --- trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/ImportExportMatrixTest.java (rev 0) +++ trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/ImportExportMatrixTest.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,121 @@ +/* + * *##% Copyright (C) 2002, 2003, 2004 Code Lutin, Cédric 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. ##% + */ +package org.codelutin.math.matrix; + +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.Arrays; +import java.util.List; + +import junit.framework.TestCase; + +/** + * Test de l'import et export CSV + * + * @author ruchaud + * + */ +public class ImportExportMatrixTest extends TestCase { + + private MatrixND mat1D; + private MatrixND mat2D; + private MatrixND mat2DSemantics; + + public MatrixFactory getFactory() throws Exception { + return MatrixFactory.getInstance(DoubleVector.class); + } + + @Override + protected void setUp() throws Exception { + mat1D = new MatrixNDImpl(getFactory(), new int[]{10}); + mat1D.setValue(new int[]{0}, 0); + mat1D.setValue(new int[]{1}, 1); + mat1D.setValue(new int[]{2}, 2); + mat1D.setValue(new int[]{3}, 3); + mat1D.setValue(new int[]{4}, -4.0E-7); + + mat2D = new MatrixNDImpl(getFactory(), new int[]{20,10}); + mat2D.setValue(new int[]{0, 0}, 0); + mat2D.setValue(new int[]{0, 1}, 1); + mat2D.setValue(new int[]{0, 2}, 2); + mat2D.setValue(new int[]{0, 3}, 3); + mat2D.setValue(new int[]{0, 4}, 4); + mat2D.setValue(new int[]{0, 5}, 4); + mat2D.setValue(new int[]{0, 6}, 4); + mat2D.setValue(new int[]{0, 7}, 4); + mat2D.setValue(new int[]{1, 8}, 4); + mat2D.setValue(new int[]{2, 9}, -4.0E-7); + + List sem1 = Arrays.asList(new String[] { "toto", "titi", "tutu", "trtr" }); + List sem2 = Arrays.asList(new String[] { "tata", "tete", "tyty" }); + mat2DSemantics = new MatrixNDImpl(getFactory(), "name", + new List[] { sem1, sem2 }, new String[]{"dim1", "dim2"}); + } + + public void testImport() throws IOException { + String test = "5.0E-7;1.0;2.0;3.0;4.0;4.0;4.0;4.0;0.3;0.0\n" + + "0.0;0.0;7.0;0.0;0.0;2.0;0.0;0.0;4.0;0.0\n" + + "0.0;0.0;8.0;1.0;0.0;0.0;0.0;0.0;0.0;4.0\n"; + StringReader reader = new StringReader(test); + + mat2D.importCSV(reader, new int[]{0,0}); + assertEquals(mat2D.getValue(0,0), 5.0E-7); + assertEquals(mat2D.getValue(1,2), 7.0); + assertEquals(mat2D.getValue(2,2), 8.0); + assertEquals(mat2D.getValue(1,8), 4.0); + + reader = new StringReader(test); + mat2D.importCSV(reader, new int[]{1,1}); + assertEquals(mat2D.getValue(1,1), 5.0E-7); + assertEquals(mat2D.getValue(2,3), 7.0); + assertEquals(mat2D.getValue(3,3), 8.0); + assertEquals(mat2D.getValue(2,9), 4.0); + } + + public void testExport() throws IOException { + testExport(mat1D, false); + testExport(mat2D, false); + + testExport(mat1D, true); + testExport(mat2D, true); + + testExport(mat2DSemantics, false); + testExport(mat2DSemantics, true); + } + + private void testExport(MatrixND matrixND, boolean withSemantics) throws IOException { + StringWriter writer = new StringWriter(); + matrixND.exportCSV(writer, withSemantics); + + StringReader writerToReader = new StringReader(writer.toString()); + matrixND.importCSV(writerToReader, new int[]{0,0}); + + StringWriter readerToWriter = new StringWriter(); + matrixND.exportCSV(readerToWriter, withSemantics); + + assertEquals(writer.toString(), readerToWriter.toString()); + } + + public void testSupport() throws Exception { + assertEquals(true, new MatrixNDImpl(getFactory(), new int[]{1}).isSupportedCSV()); + assertEquals(true, new MatrixNDImpl(getFactory(), new int[]{2,2}).isSupportedCSV()); + assertEquals(false, new MatrixNDImpl(getFactory(), new int[]{3,3,3}).isSupportedCSV()); + } +} Copied: trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/MatrixEncoderDecoderTest.java (from rev 61, trunk/lutinmatrix/src/test/org/codelutin/math/matrix/MatrixEncoderDecoderTest.java) =================================================================== --- trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/MatrixEncoderDecoderTest.java (rev 0) +++ trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/MatrixEncoderDecoderTest.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,80 @@ +/* *##% + * Copyright (C) 2002, 2003, 2004 Code Lutin, Cédric 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. + *##%*/ + +/* * + * MatrixEncoderDecoderTest.java + * + * Created: 31 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.codelutin.math.matrix; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import junit.framework.TestCase; + +public class MatrixEncoderDecoderTest extends TestCase { // MatrixEncoderDecoderTest + + public MatrixFactory getFactory() throws Exception { + return MatrixFactory.getInstance(); + } + + protected void subtestEncoderDecoder(MatrixND mat) throws Exception { + // encodage en XML + String xml = MatrixHelper.encodeToXML(mat); + // decodage depuis le XML + MatrixND mat2 = MatrixHelper.decodeFromXML(xml); + // reencodage de la matrice resultat + String xml2 = MatrixHelper.encodeToXML(mat2); + // on verifie que les 2 matrices sont egals et leur representation + // XML aussi + assertEquals(mat, mat2); + assertEquals(xml, xml2); + } + + public void testEncoderDecoder() throws Exception { + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat = null; + + mat = getFactory().create("Ma mat", new int[]{3,3,3}); + subtestEncoderDecoder(mat); + + mat = getFactory().create("Ma mat", new List[]{s1, s2, s3}); + subtestEncoderDecoder(mat); + + // on modifie S1 pour avoir un null au milieu + s1.set(1, null); + mat = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + mat.setSemantics(1, Collections.nCopies(3, null)); + subtestEncoderDecoder(mat); + } + +} // MatrixEncoderDecoderTest + Copied: trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/MatrixHelperTest.java (from rev 61, trunk/lutinmatrix/src/test/org/codelutin/math/matrix/MatrixHelperTest.java) =================================================================== --- trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/MatrixHelperTest.java (rev 0) +++ trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/MatrixHelperTest.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,147 @@ +/* *##% + * Copyright (C) 2002, 2003, 2004 Code Lutin, Cédric 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. + *##%*/ + +/* * + * MatrixHelperTest.java + * + * Created: 29 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.codelutin.math.matrix; + +import java.util.List; + +import junit.framework.TestCase; + +public class MatrixHelperTest extends TestCase { // MatrixHelperTest + + public MatrixFactory getFactory() throws Exception { + return MatrixFactory.getInstance(); + } + + public void testCoordinatesToString() throws Exception { + assertEquals("1", MatrixHelper.coordinatesToString(new int[]{1})); + assertEquals("2,3,4,5", MatrixHelper.coordinatesToString(new int[]{2,3,4,5})); + assertEquals("2,3,4,5,234", MatrixHelper.coordinatesToString(new int[]{2,3,4,5,234})); + + assertEquals("a", MatrixHelper.coordinatesToString(new String[]{"a"})); + assertEquals("a,b,n,m", MatrixHelper.coordinatesToString(new String[]{"a","b","n","m"})); + assertEquals("a,b,f,e,aze", MatrixHelper.coordinatesToString(new String[]{"a","b","f","e","aze"})); + } + + public void testSameDimension()throws Exception { + assertTrue(MatrixHelper.sameDimension(new int[]{1}, new int[]{1})); + assertTrue(MatrixHelper.sameDimension(new int[]{1,2}, new int[]{1,2})); + assertTrue(MatrixHelper.sameDimension(new int[]{1,324,3}, new int[]{1,324,3})); + } + + public void testDimensionToSemantics()throws Exception { + // TODO faire un test pour dimensionToSemantics + } + + public void testSemanticsToDimension()throws Exception { + // TODO faire un test pour semanticsToDimension + } + + public void testFill() throws Exception { + MatrixND mat = getFactory().create(new int[]{3, 3}); + MatrixHelper.fill(mat, 4); + + assertEquals(4, mat.getValue(1,1), 0); + } + + public void testMatrixId() throws Exception { + MatrixND mat = getFactory().matrixId(4); + assertTrue(MatrixHelper.sameDimension(new int[]{4,4}, mat.getDim())); + assertEquals(0, mat.getValue(1,2), 0); + assertEquals(1, mat.getValue(0,0), 0); + assertEquals(1, mat.getValue(1,1), 0); + assertEquals(1, mat.getValue(2,2), 0); + assertEquals(1, mat.getValue(3,3), 0); + } + + public void testToList() throws Exception { + MatrixND mat1 = getFactory().create(new int[]{3, 2, 1}); + mat1.setValue(0, 0, 0, -1.0E-7); + mat1.setValue(1, 1, 0, 2); + mat1.setValue(2, 1, 0, 5.0E-7); + + List l = mat1.toList(); + String s = String.valueOf(l); + List l2 = MatrixHelper.convertStringToList(s); + + System.out.println(l); + System.out.println(l2); + + assertEquals(l, l2); + + } + + public void testMaxOccurence() throws Exception { + double [] val = new double[5]; + + assertEquals(0, MatrixHelper.maxOccurence(val), 0); + + val[2] = -1; + assertEquals(0, MatrixHelper.maxOccurence(val), 0); + val[0] = -1; + assertEquals(0, MatrixHelper.maxOccurence(val), 0); + val[1] = -1; + assertEquals(-1, MatrixHelper.maxOccurence(val), 0); + val[4] = -3; + assertEquals(-1, MatrixHelper.maxOccurence(val), 0); + val[3] = 3; + assertEquals(-1, MatrixHelper.maxOccurence(val), 0); + + val = new double[6]; + + assertEquals(0, MatrixHelper.maxOccurence(val), 0); + + val[2] = -1; + assertEquals(0, MatrixHelper.maxOccurence(val), 0); + val[0] = -1; + assertEquals(0, MatrixHelper.maxOccurence(val), 0); + val[1] = -1; + assertEquals(-1, MatrixHelper.maxOccurence(val), 0); + val[4] = -3; + assertEquals(-1, MatrixHelper.maxOccurence(val), 0); + val[3] = -3; + assertEquals(-1, MatrixHelper.maxOccurence(val), 0); + val[5] = -3; + assertEquals(-3, MatrixHelper.maxOccurence(val), 0); + + + val = new double[0]; + try{ + MatrixHelper.maxOccurence(val); + assertFalse(true); // on ne passe pas ici + }catch(IllegalArgumentException eee){ + assertTrue(true); // on passe ici + } + + } + +} // MatrixHelperTest + Copied: trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/MatrixNDTest.java (from rev 61, trunk/lutinmatrix/src/test/org/codelutin/math/matrix/MatrixNDTest.java) =================================================================== --- trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/MatrixNDTest.java (rev 0) +++ trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/MatrixNDTest.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,782 @@ +/* *##% +* Copyright (C) 2002, 2003 Code Lutin +* +* 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. +*##%*/ + +/* * +* AppTestCase.java +* +* Created: 10 mai 2004 +* +* @version $Revision$ +* +* Mise a jour: $Date$ +* par : $Author$ +*/ + +package org.codelutin.math.matrix; + +import java.io.IOException; +import java.io.StreamTokenizer; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Stack; + +import org.apache.commons.lang.time.DurationFormatUtils; +import org.codelutin.util.StringUtil; + +import junit.framework.TestCase; + +public class MatrixNDTest extends TestCase { + + public MatrixFactory getFactory() throws Exception { + return MatrixFactory.getInstance(DoubleVector.class); + } + + public void testNew() throws Exception { + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat = null; + + mat = getFactory().create("Ma mat", new int[]{3,3,3}); + + mat = getFactory().create("Ma mat", new List[]{s1, s2, s3}); + + mat = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + assertEquals(0.0, mat.getMaxOccurence()); + + } + + public void testSemantique() throws Exception { + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat = null; + + mat = getFactory().create(new int[]{3,3,3}); + + assertTrue(null == mat.getSemantics(1).get(1)); + + mat = getFactory().create("Ma mat", new List[]{s1, s2, s3}); + + // la matrice doit avoir ca propre copie des semantiques + s2.set(1, "pas bon"); + assertEquals("f", mat.getSemantics(1).get(1)); + + mat.setSemantics(1, s1); + assertEquals("b", mat.getSemantics(1).get(1)); + } + + public void testName() throws Exception { + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat = null; + + mat = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + + assertEquals("Ma mat", mat.getName()); + mat.setName("Renamed"); + assertEquals("Renamed", mat.getName()); + + assertEquals("dim abc", mat.getDimensionName(0)); + mat.setDimensionName(0, "dim renamed"); + assertEquals("dim renamed", mat.getDimensionName(0)); + } + + public void testGetSet() throws Exception { + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat = null; + + mat = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + + mat.setValue(1,1,1, 34); + assertEquals(34, mat.getValue("b", "f", "l"), 0); + + mat.setValue("a", "f", "m", 22); + assertEquals(22, mat.getValue(0, 1, 2), 0); + } + + public void testIterator() throws Exception { + int [][] val27 = new int[][]{ + {0,0,0}, + {0,0,1}, + {0,0,2}, + {0,1,0}, + {0,1,1}, + {0,1,2}, + {0,2,0}, + {0,2,1}, + {0,2,2}, + {1,0,0}, + {1,0,1}, + {1,0,2}, + {1,1,0}, + {1,1,1}, + {1,1,2}, + {1,2,0}, + {1,2,1}, + {1,2,2}, + {2,0,0}, + {2,0,1}, + {2,0,2}, + {2,1,0}, + {2,1,1}, + {2,1,2}, + {2,2,0}, + {2,2,1}, + {2,2,2}, + }; + + String [][] vals27 = new String[][]{ + {"a","e","k"}, + {"a","e","l"}, + {"a","e","m"}, + {"a","f","k"}, + {"a","f","l"}, + {"a","f","m"}, + {"a","g","k"}, + {"a","g","l"}, + {"a","g","m"}, + {"b","e","k"}, + {"b","e","l"}, + {"b","e","m"}, + {"b","f","k"}, + {"b","f","l"}, + {"b","f","m"}, + {"b","g","k"}, + {"b","g","l"}, + {"b","g","m"}, + {"c","e","k"}, + {"c","e","l"}, + {"c","e","m"}, + {"c","f","k"}, + {"c","f","l"}, + {"c","f","m"}, + {"c","g","k"}, + {"c","g","l"}, + {"c","g","m"}, + }; + + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat = null; + + mat = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + + int cpt = 0; + for(MatrixIterator i=mat.iterator(); i.hasNext();){ + i.next(); + assertTrue(Arrays.equals(val27[cpt], i.getCoordinates())); + assertTrue(Arrays.equals(vals27[cpt], i.getSemanticsCoordinates())); + cpt ++; + } + assertEquals(27, cpt); + } + + public void testAdd() throws Exception { + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat1 = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + MatrixND mat2 = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + + MatrixHelper.fill(mat1, 3); + MatrixHelper.fill(mat2, 26); + + mat1.add(mat2); + + assertEquals(29, mat1.getValue(0,0,0), 0); + assertEquals(29, mat1.getValue(1,2,0), 0); + assertEquals(29, mat1.getValue(2,2,2), 0); + } + + public void testMinus() throws Exception { + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat1 = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + MatrixND mat2 = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + + MatrixHelper.fill(mat1, 3); + MatrixHelper.fill(mat2, 26); + + mat1.minus(mat2); + + assertEquals(-23, mat1.getValue(0,0,0), 0); + assertEquals(-23, mat1.getValue(1,2,0), 0); + assertEquals(-23, mat1.getValue(2,2,2), 0); + } + + public void testEquals() throws Exception { + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat1 = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + MatrixND mat2 = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + MatrixND mat3 = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + + MatrixHelper.fill(mat1, 3); + MatrixHelper.fill(mat2, 26); + MatrixHelper.fill(mat3, 29); + + mat1.add(mat2); + + assertEquals(mat1, mat3); + } + + public void testsumOverDim() throws Exception { + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat = null; + + + mat = getFactory().create(new int[]{4,4}); + MatrixND mat2 = mat; + int i=0; + for(MatrixIterator mi=mat.iterator(); mi.next();){ + mi.setValue(++i); + } + + assertEquals(mat, mat2); + mat2 = mat.sumOverDim(1, 0); + assertEquals(mat, mat2); + mat2 = mat.sumOverDim(1, 1); + assertEquals(mat, mat2); + mat2 = mat.sumOverDim(1, 2); + assertEquals(2, mat2.getDim(1)); + assertEquals(3, mat2.getValue(0, 0), 0); + assertEquals(7, mat2.getValue(0, 1), 0); + assertEquals(11, mat2.getValue(1, 0), 0); + assertEquals(15, mat2.getValue(1, 1), 0); + assertEquals(19, mat2.getValue(2, 0), 0); + assertEquals(23, mat2.getValue(2, 1), 0); + assertEquals(27, mat2.getValue(3, 0), 0); + assertEquals(31, mat2.getValue(3, 1), 0); + + mat2 = mat.sumOverDim(1, 3); + assertEquals(1, mat2.getDim(1)); + assertEquals(6, mat2.getValue(0, 0), 0); + assertEquals(18, mat2.getValue(1, 0), 0); + assertEquals(30, mat2.getValue(2, 0), 0); + assertEquals(42, mat2.getValue(3, 0), 0); + + mat2 = mat.sumOverDim(1, 4); + assertEquals(1, mat2.getDim(1)); + assertEquals(10, mat2.getValue(0, 0), 0); + assertEquals(26, mat2.getValue(1, 0), 0); + assertEquals(42, mat2.getValue(2, 0), 0); + assertEquals(58, mat2.getValue(3, 0), 0); + + + mat = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + + MatrixHelper.fill(mat, 3); + mat.setValue(0, 0, 0, 2); + mat.setValue(2, 2, 2, 4); + mat = mat.sumOverDim(1); + assertTrue(MatrixHelper.sameDimension(new int[]{3,1,3}, mat.getDim())); + + assertEquals(8, mat.getValue(0,0,0), 0); + assertEquals(9, mat.getValue(2,0,1), 0); + assertEquals(10, mat.getValue(2,0,2), 0); + + + + mat = getFactory().create(new int[]{6,6,6}); + + MatrixHelper.fill(mat, 3); + mat.setValue(0, 0, 0, 0); + mat.setValue(0, 1, 0, 1); + mat.setValue(0, 2, 0, 2); + mat.setValue(0, 3, 0, 3); + mat.setValue(0, 4, 0, 4); + mat.setValue(0, 5, 0, 5); + + mat = mat.sumOverDim(1, 3); + assertTrue(MatrixHelper.sameDimension(new int[]{6,2,6}, mat.getDim())); + assertEquals(3, mat.getValue(0,0,0), 0); + assertEquals(12, mat.getValue(0,1,0), 0); + assertEquals(9, mat.getValue(1,1,5), 0); + assertEquals(9, mat.getValue(5,0,3), 0); + } + + public void testTranspose() throws Exception { + MatrixND mat = null; + + mat = getFactory().create(new int[]{2,4}); + mat.setValue(1, 3, 56); + mat.setValue(0, 2, 34); + mat.setValue(0, 1, 64); + mat.setValue(1, 0, 46); + + mat = mat.transpose(); + assertEquals(56, mat.getValue(3, 1), 0); + assertEquals(34, mat.getValue(2, 0), 0); + assertEquals(64, mat.getValue(1, 0), 0); + assertEquals(46, mat.getValue(0, 1), 0); + + mat = getFactory().create(new int[]{4}); + mat.setValue(1, 56); + mat.setValue(2, 34); + mat.setValue(3, 64); + mat.setValue(0, 46); + + mat = mat.transpose(); + assertEquals(56, mat.getValue(0, 1), 0); + assertEquals(34, mat.getValue(0, 2), 0); + assertEquals(64, mat.getValue(0, 3), 0); + assertEquals(46, mat.getValue(0, 0), 0); + } + + public void testMults() throws Exception { + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat1 = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + MatrixND mat2 = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + + MatrixHelper.fill(mat1, 3); + MatrixHelper.fill(mat2, 26); + + mat1.mults(3); + mat2.mults(0); + + assertEquals(9, mat1.getValue(0,0,0), 0); + assertEquals(9, mat1.getValue(1,2,0), 0); + assertEquals(0, mat2.getValue(2,2,2), 0); + + MatrixND mat0 = getFactory().create(new int[]{4,4}); + MatrixND matId = getFactory().matrixId(4); + matId.mults(0); + assertEquals(mat0, matId); + } + + public void testDivs() throws Exception { + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat1 = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + MatrixND mat2 = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + + MatrixHelper.fill(mat1, 3); + MatrixHelper.fill(mat2, 26); + + mat1.divs(3); + mat2.divs(4); + + assertEquals(1, mat1.getValue(0,0,0), 0); + assertEquals(6.5, mat2.getValue(1,2,0), 0); + assertEquals(6.5, mat2.getValue(2,2,2), 0); + } + + public void testPaste() throws Exception { + + MatrixND mat1 = getFactory().create(new int[]{6, 7, 8}); + MatrixND mat2 = getFactory().create(new int[]{2, 2, 2}); + + MatrixHelper.fill(mat1, 3); + MatrixHelper.fill(mat2, 26); + + mat1.paste(new int[]{3, 0, 4}, mat2); + + assertEquals(3, mat1.getValue(0,0,0), 0); + assertEquals(26, mat1.getValue(3,0,4), 0); + assertEquals(26, mat1.getValue(4,1,5), 0); + assertEquals(3, mat1.getValue(5,2,6), 0); + } + + public void testSumOverDim() throws Exception { + + MatrixND mat = null; + + mat = getFactory().create(new int[]{6, 7}); + MatrixND result = getFactory().create(new int[]{3, 7}); + + MatrixHelper.fill(mat, 3); + + MatrixND sub = mat.getSubMatrix(0, 0, 1); + result.paste(new int[]{0,0}, sub.sumOverDim(0)); + + sub = mat.getSubMatrix(0, 1, 3); + result.paste(new int[]{1,0}, sub.sumOverDim(0)); + + sub = mat.getSubMatrix(0, 4, 2); + result.paste(new int[]{2,0}, sub.sumOverDim(0)); + + mat = getFactory().create(new int[]{6, 7}); + MatrixHelper.fill(mat, 3); + + + + mat = mat.sumOverDim(0, 0, 1); + mat = mat.sumOverDim(0, 1, 3); + mat = mat.sumOverDim(0, 2, 2); + + assertTrue(result.equalsValues(mat)); + } + + public void testReduce() throws Exception { + + MatrixND mat = null; + + mat = getFactory().create(new int[]{6, 7, 8}); + MatrixHelper.fill(mat, 3); + + mat = mat.sumOverDim(1); + assertEquals(21, mat.getValue(0, 0, 0), 0); + mat = mat.reduce(); + assertEquals(2, mat.getNbDim()); + assertEquals(6, mat.getDim(0)); + assertEquals(8, mat.getDim(1)); + assertEquals(21, mat.getValue(0, 0), 0); + assertEquals(21, mat.getValue(5, 7), 0); + + + mat = getFactory().create(new int[]{2, 2, 2}); + MatrixHelper.fill(mat, 26); + + mat = mat.sumOverDim(1); + mat = mat.sumOverDim(0); + assertEquals(104, mat.getValue(0, 0, 0), 0); + mat = mat.reduce(); + assertEquals(1, mat.getNbDim()); + assertEquals(2, mat.getDim(0)); + assertEquals(104, mat.getValue(0), 0); + assertEquals(104, mat.getValue(1), 0); + + + mat = getFactory().create(new int[]{2, 2, 2}); + MatrixHelper.fill(mat, 6); + + mat = mat.sumOverDim(1); + mat = mat.sumOverDim(2); + mat = mat.sumOverDim(0); + assertEquals(48, mat.getValue(0, 0, 0), 0); + mat = mat.reduce(); + assertEquals(1, mat.getNbDim()); + assertEquals(1, mat.getDim(0)); + assertEquals(48, mat.getValue(0), 0); + + + + mat = getFactory().create(new int[]{6, 7, 8}); + MatrixHelper.fill(mat, 3); + + mat = mat.sumOverDim(1); + assertEquals(21, mat.getValue(0, 0, 0), 0); + mat = mat.reduce(2); + assertEquals(2, mat.getNbDim()); + assertEquals(6, mat.getDim(0)); + assertEquals(8, mat.getDim(1)); + assertEquals(21, mat.getValue(0, 0), 0); + assertEquals(21, mat.getValue(5, 7), 0); + + + mat = getFactory().create(new int[]{2, 2, 2}); + MatrixHelper.fill(mat, 26); + + mat = mat.sumOverDim(1); + mat = mat.sumOverDim(0); + assertEquals(104, mat.getValue(0, 0, 0), 0); + mat = mat.reduce(2); + assertEquals(2, mat.getNbDim()); + assertEquals(1, mat.getDim(0)); + assertEquals(2, mat.getDim(1)); + assertEquals(104, mat.getValue(0, 0), 0); + assertEquals(104, mat.getValue(0, 1), 0); + + + mat = getFactory().create(new int[]{2, 2, 2}); + MatrixHelper.fill(mat, 6); + + mat = mat.sumOverDim(1); + mat = mat.sumOverDim(2); + mat = mat.sumOverDim(0); + assertEquals(48, mat.getValue(0, 0, 0), 0); + mat = mat.reduce(5); + assertEquals(3, mat.getNbDim()); + assertEquals(1, mat.getDim(0)); + assertEquals(1, mat.getDim(1)); + assertEquals(1, mat.getDim(2)); + assertEquals(48, mat.getValue(0, 0, 0), 0); + + + } + + public void testReduceDims() throws Exception { + + MatrixND mat = null; + + mat = getFactory().create(new int[]{6, 7, 8}); + MatrixHelper.fill(mat, 3); + + mat = mat.sumOverDim(1); + assertEquals(21, mat.getValue(0, 0, 0), 0); + mat = mat.reduceDims(1); + assertEquals(2, mat.getNbDim()); + assertEquals(6, mat.getDim(0)); + assertEquals(8, mat.getDim(1)); + assertEquals(21, mat.getValue(0, 0), 0); + assertEquals(21, mat.getValue(5, 7), 0); + + + mat = getFactory().create(new int[]{2, 2, 2}); + MatrixHelper.fill(mat, 26); + + mat = mat.sumOverDim(1); + mat = mat.sumOverDim(0); + assertEquals(104, mat.getValue(0, 0, 0), 0); + mat = mat.reduceDims(1,0); + assertEquals(1, mat.getNbDim()); + assertEquals(2, mat.getDim(0)); + assertEquals(104, mat.getValue(0), 0); + assertEquals(104, mat.getValue(1), 0); + + + mat = getFactory().create(new int[]{2, 2, 2}); + MatrixHelper.fill(mat, 6); + + mat = mat.sumOverDim(1); + mat = mat.sumOverDim(2); + mat = mat.sumOverDim(0); + assertEquals(48, mat.getValue(0, 0, 0), 0); + mat = mat.reduceDims(1,2,0); + assertEquals(1, mat.getNbDim()); + assertEquals(1, mat.getDim(0)); + assertEquals(48, mat.getValue(0), 0); + + + + mat = getFactory().create(new int[]{6, 7, 8}); + MatrixHelper.fill(mat, 3); + + mat = mat.sumOverDim(1); + assertEquals(21, mat.getValue(0, 0, 0), 0); + mat = mat.reduceDims(0); + assertEquals(3, mat.getNbDim()); + assertEquals(6, mat.getDim(0)); + assertEquals(1, mat.getDim(1)); + assertEquals(8, mat.getDim(2)); + assertEquals(21, mat.getValue(0, 0, 0), 0); + assertEquals(21, mat.getValue(5, 0, 7), 0); + + + mat = getFactory().create(new int[]{2, 2, 2}); + MatrixHelper.fill(mat, 26); + + mat = mat.sumOverDim(1); + mat = mat.sumOverDim(0); + assertEquals(104, mat.getValue(0, 0, 0), 0); + mat = mat.reduceDims(1); + assertEquals(2, mat.getNbDim()); + assertEquals(1, mat.getDim(0)); + assertEquals(2, mat.getDim(1)); + assertEquals(104, mat.getValue(0, 0), 0); + assertEquals(104, mat.getValue(0, 1), 0); + + + mat = getFactory().create(new int[]{2, 2, 2}); + MatrixHelper.fill(mat, 6); + + mat = mat.sumOverDim(1); + mat = mat.sumOverDim(2); + mat = mat.sumOverDim(0); + assertEquals(48, mat.getValue(0, 0, 0), 0); + mat = mat.reduceDims(0, 1, 2); + assertEquals(1, mat.getNbDim()); + assertEquals(1, mat.getDim(0)); + assertEquals(48, mat.getValue(0), 0); + + + } + + public void testToList() throws Exception { + MatrixND mat1 = getFactory().create(new int[]{3, 2, 1}); + mat1.setValue(0, 0, 0, 1.0E-7); + mat1.setValue(1, 1, 0, 2); + mat1.setValue(2, 1, 0, 5.0E-7); + List l = mat1.toList(); + System.out.println(l); + + MatrixND mat2 = getFactory().create(new int[]{3, 2, 1}); + mat2.fromList(l); + + System.out.println(mat1); + System.out.println(mat2); + + assertEquals(mat1, mat2); + + String s = String.valueOf(l); + List l2 = convertStringToList2(s); + List l1 = convertStringToList1(s); + List l0 = convertStringToList0(s); + + System.out.println(l); + System.out.println(l2); + System.out.println(l1); + System.out.println(l0); // implatation fausse + + assertEquals(l, l2); + + int MAX = 10000; + int dummy = 0; + { + long timeStart = System.nanoTime(); + for (int i=0; i<MAX; i++) { + List tmp = convertStringToList1(s); + dummy += tmp.size(); + } + long time = System.nanoTime() - timeStart; + time = time / 1000000; + System.out.println(MAX +" call to convertStringToList time: " + DurationFormatUtils.formatDuration(time, "s'.'S")); + } + { + long timeStart = System.nanoTime(); + for (int i=0; i<MAX; i++) { + List tmp = convertStringToList2(s); + dummy += tmp.size(); + } + long time = System.nanoTime() - timeStart; + time = time / 1000000; + System.out.println(MAX +" call to convertStringToList2 time: " + DurationFormatUtils.formatDuration(time, "s'.'S")); + } + System.out.println("dummy: " + dummy); + } + + + + /** + * implantation peut performante + */ + static public List convertStringToList1(String s) { + List result = new ArrayList(); + s = s.trim(); + if (s.startsWith("[") && s.endsWith("]")) { + s = s.substring(1, s.length() -1); + } + String [] las = StringUtil.split(s, ","); + for (String l : las) { + l = l.trim(); + if (l.startsWith("[")) { + // another list, recursive call + result.add(convertStringToList1(l)); + } else { + // if no list, must be number + Double d = Double.valueOf(l); + result.add(d); + } + } + return result; + } + + /** + * implantation utilisé actuellement dans MatrixHelper + */ + static public List convertStringToList2(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; + } + + /** + * implantation fausse pour les nombres 5.0E-7 + */ + static public List convertStringToList0(String s) throws IOException { + List result = null; + Stack<List> stack = new Stack<List>(); + StringBuffer number = new StringBuffer(20); // initial to 20 char + + StreamTokenizer tok = new StreamTokenizer(new StringReader(s)); + int v = tok.nextToken(); + while (v != StreamTokenizer.TT_EOF) { + if (v == '[') { + stack.push(new ArrayList()); + } else if (v == ']'){ + List current = stack.pop(); + if (stack.empty()) { + result = current; + } else { + stack.peek().add(current); + } + } else if (v == StreamTokenizer.TT_NUMBER) { + double value = tok.nval; + stack.peek().add(value); + } + v = tok.nextToken(); + } + return result; + } + + + +} Copied: trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/PerfTest.java (from rev 61, trunk/lutinmatrix/src/test/org/codelutin/math/matrix/PerfTest.java) =================================================================== --- trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/PerfTest.java (rev 0) +++ trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/PerfTest.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,435 @@ +/* *##% + * Copyright (C) 2006 + * Code Lutin, Cédric 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. + *##%*/ + +/* * + * PerfTest.java + * + * Created: 7 sept. 06 02:28:51 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.codelutin.math.matrix; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.commons.lang.time.DurationFormatUtils; + + +/** + * @author poussin + * + */ + +public class PerfTest extends TestCase { + + static char CMAX = 'j'; + static int MAX = 10; + + public void testDoubleVectorIterator() throws Exception { + List sem = new ArrayList(); + for (char c='a'; c<=CMAX; c++) { + for (int i=1; i<=MAX; i++) { + sem.add(c + " " + i); + } + } + + MatrixND mat = null; + + // [ 2600 x 2600 x 2600 ] + long timestart = System.nanoTime(); + mat = MatrixFactory.getInstance(DoubleVector.class).create("Ma mat", new List[]{sem, sem, sem}); + long timeinit = System.nanoTime(); + // parcours avec iterator + long cpt = 1; + for (MatrixIterator i=mat.iterator(); i.hasNext();) { + i.next(); + i.setValue(cpt++); + } + long timeend = System.nanoTime(); + + System.out.println("Iterator DoubleVector init: " + DurationFormatUtils.formatDuration((timeinit-timestart)/1000000, "s'.'S") + + " fill: " + DurationFormatUtils.formatDuration((timeend-timeinit)/1000000, "s'.'S") ); + } + + public void testDoubleVectorIndex() throws Exception { + List sem = new ArrayList(); + for (char c='a'; c<=CMAX; c++) { + for (int i=1; i<=MAX; i++) { + sem.add(c + " " + i); + } + } + int size = sem.size(); + + MatrixND mat = null; + + // [ 2600 x 2600 x 2600 ] + long timestart = System.nanoTime(); + mat = MatrixFactory.getInstance(DoubleVector.class).create("Ma mat", new List[]{sem, sem, sem}); + long timeinit = System.nanoTime(); + // parcours avec iterator + long cpt = 1; + for (int x=0; x<size; x++) { + for (int y=0; y<size; y++) { + for (int z=0; z<size; z++) { + mat.setValue(x,y,z, cpt++); + } + } + } + long timeend = System.nanoTime(); + + System.out.println("Index DoubleVector init: " + DurationFormatUtils.formatDuration((timeinit-timestart)/1000000, "s'.'S") + + " fill: " + DurationFormatUtils.formatDuration((timeend-timeinit)/1000000, "s'.'S") ); + } + + public void testDoubleVectorSemantic() throws Exception { + List<String> sem = new ArrayList<String>(); + for (char c='a'; c<=CMAX; c++) { + for (int i=1; i<=MAX; i++) { + sem.add(c + " " + i); + } + } + int size = sem.size(); + + MatrixND mat = null; + + // [ 2600 x 2600 x 2600 ] + long timestart = System.nanoTime(); + mat = MatrixFactory.getInstance(DoubleVector.class).create("Ma mat", new List[]{sem, sem, sem}); + long timeinit = System.nanoTime(); + // parcours avec iterator + long cpt = 1; + for (int x=0; x<size; x++) { + for (int y=0; y<size; y++) { + for (int z=0; z<size; z++) { + String X = sem.get(x); + String Y = sem.get(y); + String Z = sem.get(z); + mat.setValue(X,Y,Z, cpt++); + } + } + } + long timeend = System.nanoTime(); + + System.out.println("Semantic DoubleVector init: " + DurationFormatUtils.formatDuration((timeinit-timestart)/1000000, "s'.'S") + + " fill: " + DurationFormatUtils.formatDuration((timeend-timeinit)/1000000, "s'.'S") ); + } + + + + + + + public void testDoubleBigVectorIterator() throws Exception { + List sem = new ArrayList(); + for (char c='a'; c<=CMAX; c++) { + for (int i=1; i<=MAX; i++) { + sem.add(c + " " + i); + } + } + + MatrixND mat = null; + + // [ 2600 x 2600 x 2600 ] + long timestart = System.nanoTime(); + mat = MatrixFactory.getInstance(DoubleBigVector.class).create("Ma mat", new List[]{sem, sem, sem}); + long timeinit = System.nanoTime(); + // parcours avec iterator + long cpt = 1; + for (MatrixIterator i=mat.iterator(); i.hasNext();) { + i.next(); + i.setValue(cpt++); + } + long timeend = System.nanoTime(); + + System.out.println("Iterator DoubleBigVector init: " + DurationFormatUtils.formatDuration((timeinit-timestart)/1000000, "s'.'S") + + " fill: " + DurationFormatUtils.formatDuration((timeend-timeinit)/1000000, "s'.'S") ); + } + + public void testDoubleBigVectorIndex() throws Exception { + List sem = new ArrayList(); + for (char c='a'; c<=CMAX; c++) { + for (int i=1; i<=MAX; i++) { + sem.add(c + " " + i); + } + } + int size = sem.size(); + + MatrixND mat = null; + + // [ 2600 x 2600 x 2600 ] + long timestart = System.nanoTime(); + mat = MatrixFactory.getInstance(DoubleBigVector.class).create("Ma mat", new List[]{sem, sem, sem}); + long timeinit = System.nanoTime(); + // parcours avec iterator + long cpt = 1; + for (int x=0; x<size; x++) { + for (int y=0; y<size; y++) { + for (int z=0; z<size; z++) { + mat.setValue(x,y,z, cpt++); + } + } + } + long timeend = System.nanoTime(); + + System.out.println("Index DoubleBigVector init: " + DurationFormatUtils.formatDuration((timeinit-timestart)/1000000, "s'.'S") + + " fill: " + DurationFormatUtils.formatDuration((timeend-timeinit)/1000000, "s'.'S") ); + } + + public void testDoubleBigVectorSemantic() throws Exception { + List<String> sem = new ArrayList<String>(); + for (char c='a'; c<=CMAX; c++) { + for (int i=1; i<=MAX; i++) { + sem.add(c + " " + i); + } + } + int size = sem.size(); + + MatrixND mat = null; + + // [ 2600 x 2600 x 2600 ] + long timestart = System.nanoTime(); + mat = MatrixFactory.getInstance(DoubleBigVector.class).create("Ma mat", new List[]{sem, sem, sem}); + long timeinit = System.nanoTime(); + // parcours avec iterator + long cpt = 1; + for (int x=0; x<size; x++) { + for (int y=0; y<size; y++) { + for (int z=0; z<size; z++) { + String X = sem.get(x); + String Y = sem.get(y); + String Z = sem.get(z); + mat.setValue(X,Y,Z, cpt++); + } + } + } + long timeend = System.nanoTime(); + + System.out.println("Semantic DoubleBigVector init: " + DurationFormatUtils.formatDuration((timeinit-timestart)/1000000, "s'.'S") + + " fill: " + DurationFormatUtils.formatDuration((timeend-timeinit)/1000000, "s'.'S") ); + } + + + + + + + + + + + + + + public void testFloatVectorIterator() throws Exception { + List sem = new ArrayList(); + for (char c='a'; c<=CMAX; c++) { + for (int i=1; i<=MAX; i++) { + sem.add(c + " " + i); + } + } + + MatrixND mat = null; + + // [ 2600 x 2600 x 2600 ] + long timestart = System.nanoTime(); + mat = MatrixFactory.getInstance(FloatVector.class).create("Ma mat", new List[]{sem, sem, sem}); + long timeinit = System.nanoTime(); + // parcours avec iterator + long cpt = 1; + for (MatrixIterator i=mat.iterator(); i.hasNext();) { + i.next(); + i.setValue(cpt++); + } + long timeend = System.nanoTime(); + + System.out.println("Iterator FloatVector init: " + DurationFormatUtils.formatDuration((timeinit-timestart)/1000000, "s'.'S") + + " fill: " + DurationFormatUtils.formatDuration((timeend-timeinit)/1000000, "s'.'S") ); + } + + public void testFloatVectorIndex() throws Exception { + List sem = new ArrayList(); + for (char c='a'; c<=CMAX; c++) { + for (int i=1; i<=MAX; i++) { + sem.add(c + " " + i); + } + } + int size = sem.size(); + + MatrixND mat = null; + + // [ 2600 x 2600 x 2600 ] + long timestart = System.nanoTime(); + mat = MatrixFactory.getInstance(FloatVector.class).create("Ma mat", new List[]{sem, sem, sem}); + long timeinit = System.nanoTime(); + // parcours avec iterator + long cpt = 1; + for (int x=0; x<size; x++) { + for (int y=0; y<size; y++) { + for (int z=0; z<size; z++) { + mat.setValue(x,y,z, cpt++); + } + } + } + long timeend = System.nanoTime(); + + System.out.println("Index FloatVector init: " + DurationFormatUtils.formatDuration((timeinit-timestart)/1000000, "s'.'S") + + " fill: " + DurationFormatUtils.formatDuration((timeend-timeinit)/1000000, "s'.'S") ); + } + + public void testFloatVectorSemantic() throws Exception { + List<String> sem = new ArrayList<String>(); + for (char c='a'; c<=CMAX; c++) { + for (int i=1; i<=MAX; i++) { + sem.add(c + " " + i); + } + } + int size = sem.size(); + + MatrixND mat = null; + + // [ 2600 x 2600 x 2600 ] + long timestart = System.nanoTime(); + mat = MatrixFactory.getInstance(FloatVector.class).create("Ma mat", new List[]{sem, sem, sem}); + long timeinit = System.nanoTime(); + // parcours avec iterator + long cpt = 1; + for (int x=0; x<size; x++) { + for (int y=0; y<size; y++) { + for (int z=0; z<size; z++) { + String X = sem.get(x); + String Y = sem.get(y); + String Z = sem.get(z); + mat.setValue(X,Y,Z, cpt++); + } + } + } + long timeend = System.nanoTime(); + + System.out.println("Semantic FloatVector init: " + DurationFormatUtils.formatDuration((timeinit-timestart)/1000000, "s'.'S") + + " fill: " + DurationFormatUtils.formatDuration((timeend-timeinit)/1000000, "s'.'S") ); + } + + + + + + + public void testFloatBigVectorIterator() throws Exception { + List sem = new ArrayList(); + for (char c='a'; c<=CMAX; c++) { + for (int i=1; i<=MAX; i++) { + sem.add(c + " " + i); + } + } + + MatrixND mat = null; + + // [ 2600 x 2600 x 2600 ] + long timestart = System.nanoTime(); + mat = MatrixFactory.getInstance(FloatBigVector.class).create("Ma mat", new List[]{sem, sem, sem}); + long timeinit = System.nanoTime(); + // parcours avec iterator + long cpt = 1; + for (MatrixIterator i=mat.iterator(); i.hasNext();) { + i.next(); + i.setValue(cpt++); + } + long timeend = System.nanoTime(); + + System.out.println("Iterator FloatBigVector init: " + DurationFormatUtils.formatDuration((timeinit-timestart)/1000000, "s'.'S") + + " fill: " + DurationFormatUtils.formatDuration((timeend-timeinit)/1000000, "s'.'S") ); + } + + public void testFloatBigVectorIndex() throws Exception { + List sem = new ArrayList(); + for (char c='a'; c<=CMAX; c++) { + for (int i=1; i<=MAX; i++) { + sem.add(c + " " + i); + } + } + int size = sem.size(); + + MatrixND mat = null; + + // [ 2600 x 2600 x 2600 ] + long timestart = System.nanoTime(); + mat = MatrixFactory.getInstance(FloatBigVector.class).create("Ma mat", new List[]{sem, sem, sem}); + long timeinit = System.nanoTime(); + // parcours avec iterator + long cpt = 1; + for (int x=0; x<size; x++) { + for (int y=0; y<size; y++) { + for (int z=0; z<size; z++) { + mat.setValue(x,y,z, cpt++); + } + } + } + long timeend = System.nanoTime(); + + System.out.println("Index FloatBigVector init: " + DurationFormatUtils.formatDuration((timeinit-timestart)/1000000, "s'.'S") + + " fill: " + DurationFormatUtils.formatDuration((timeend-timeinit)/1000000, "s'.'S") ); + } + + public void testFloatBigVectorSemantic() throws Exception { + List<String> sem = new ArrayList<String>(); + for (char c='a'; c<=CMAX; c++) { + for (int i=1; i<=MAX; i++) { + sem.add(c + " " + i); + } + } + int size = sem.size(); + + MatrixND mat = null; + + // [ 2600 x 2600 x 2600 ] + long timestart = System.nanoTime(); + mat = MatrixFactory.getInstance(FloatBigVector.class).create("Ma mat", new List[]{sem, sem, sem}); + long timeinit = System.nanoTime(); + // parcours avec iterator + long cpt = 1; + for (int x=0; x<size; x++) { + for (int y=0; y<size; y++) { + for (int z=0; z<size; z++) { + String X = sem.get(x); + String Y = sem.get(y); + String Z = sem.get(z); + mat.setValue(X,Y,Z, cpt++); + } + } + } + long timeend = System.nanoTime(); + + System.out.println("Semantic FloatBigVector init: " + DurationFormatUtils.formatDuration((timeinit-timestart)/1000000, "s'.'S") + + " fill: " + DurationFormatUtils.formatDuration((timeend-timeinit)/1000000, "s'.'S") ); + } + + + + +} + + Copied: trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/SubMatrixTest.java (from rev 61, trunk/lutinmatrix/src/test/org/codelutin/math/matrix/SubMatrixTest.java) =================================================================== --- trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/SubMatrixTest.java (rev 0) +++ trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/SubMatrixTest.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,299 @@ +/* *##% + * Copyright (C) 2002, 2003, 2004 Code Lutin, Cédric 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. + *##%*/ + +/* * + * SubMatrixTest.java + * + * Created: 29 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + + +package org.codelutin.math.matrix; + +import java.util.Arrays; +import java.util.List; +import junit.framework.TestCase; + +public class SubMatrixTest extends TestCase { // SubMatrixTest + + public MatrixFactory getFactory() throws Exception { + return MatrixFactory.getInstance(); + } + + public void testNew() throws Exception { + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat = null; + + mat = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + + MatrixND smat = mat.getSubMatrix(1, 0, 2); + assertTrue(Arrays.equals(new int[]{3,2,3}, smat.getDim())); + } + + public void testIterator() throws Exception { + int [][] val18 = new int[][]{ + {0,0,0}, + {0,0,1}, + {0,0,2}, + {0,1,0}, + {0,1,1}, + {0,1,2}, + {1,0,0}, + {1,0,1}, + {1,0,2}, + {1,1,0}, + {1,1,1}, + {1,1,2}, + {2,0,0}, + {2,0,1}, + {2,0,2}, + {2,1,0}, + {2,1,1}, + {2,1,2}, + }; + + String [][] vals18 = new String[][]{ + {"a","e","k"}, + {"a","e","l"}, + {"a","e","m"}, + {"a","f","k"}, + {"a","f","l"}, + {"a","f","m"}, + {"b","e","k"}, + {"b","e","l"}, + {"b","e","m"}, + {"b","f","k"}, + {"b","f","l"}, + {"b","f","m"}, + {"c","e","k"}, + {"c","e","l"}, + {"c","e","m"}, + {"c","f","k"}, + {"c","f","l"}, + {"c","f","m"}, + }; + + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat = null; + + mat = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + + MatrixND smat = mat.getSubMatrix(1, 0, 2); + +// System.out.println(MatrixHelper.coordinatesToString(smat.getDim())); + + int cpt = 0; + for(MatrixIterator i=smat.iterator(); i.hasNext();){ + i.next(); + +// System.out.println(MatrixHelper.coordinatesToString(i.getCoordinates())); +// System.out.println(MatrixHelper.coordinatesToString(i.getSemanticsCoordinates())); + + assertTrue(Arrays.equals(val18[cpt], i.getCoordinates())); + assertTrue(Arrays.equals(vals18[cpt], i.getSemanticsCoordinates())); + cpt ++; + } + assertEquals(18, cpt); + } + + public void testSubSubMatrix() throws Exception { + int [][] val6 = new int[][]{ + {0,0,0}, + {0,0,1}, + {0,0,2}, + {0,1,0}, + {0,1,1}, + {0,1,2}, + }; + + String [][] vals6 = new String[][]{ + {"c","e","k"}, + {"c","e","l"}, + {"c","e","m"}, + {"c","f","k"}, + {"c","f","l"}, + {"c","f","m"}, + }; + + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat = null; + + mat = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + + MatrixND smat1 = mat.getSubMatrix(1, 0, 2); + MatrixND smat2 = smat1.getSubMatrix(0, 2, 1); + +// System.out.println(" smat2.getDim: "+MatrixHelper.coordinatesToString(smat2.getDim())); + assertTrue(Arrays.equals(new int[]{1, 2, 3}, smat2.getDim())); + +// System.out.println(MatrixHelper.coordinatesToString(smat2.getDim())); + + int cpt = 0; + for(MatrixIterator i=smat2.iterator(); i.hasNext();){ + i.next(); + + assertTrue(Arrays.equals(val6[cpt], i.getCoordinates())); + assertTrue(Arrays.equals(vals6[cpt], i.getSemanticsCoordinates())); + cpt ++; + } + assertEquals(6, cpt); + } + + + public void testSubSubGetSet() throws Exception { + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat = null; + + mat = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + + MatrixND smat1 = mat.getSubMatrix(1, 0, 2); + MatrixND smat2 = smat1.getSubMatrix(0, 2, 1); + + smat2.setValue(0, 0, 0, 34); + assertEquals(34, smat2.getValue("c", "e", "k"), 0); + smat2.setValue("c", "f", "l", 23); + assertEquals(23, smat2.getValue(0, 1, 1), 0); + } + + public void testSubMapping() throws Exception { + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat = null; + + mat = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + + MatrixND smat1 = mat.getSubMatrix(1, new int []{0, 1}); + assertEquals(2, smat1.getDim(1)); + assertEquals(Arrays.asList(new String[]{"e","f"}), smat1.getSemantics(1)); + MatrixND smat2 = smat1.getSubMatrix(0, new Object[]{"c"}); + assertEquals(1, smat2.getDim(0)); + assertEquals(Arrays.asList(new String[]{"c"}), smat2.getSemantics(0)); + + mat.setValue("c", "f", "k", 12); + assertEquals(12, smat1.getValue(2, 1, 0), 0); + assertEquals(12, smat1.getValue("c", "f", "k"), 0); + assertEquals(12, smat2.getValue(0, 1, 0), 0); + assertEquals(12, smat2.getValue("c", "f", "k"), 0); + + smat2.setValue(0, 0, 0, 34); + assertEquals(34, smat2.getValue("c", "e", "k"), 0); + assertEquals(34, mat.getValue(2, 0, 0), 0); + assertEquals(34, mat.getValue("c", "e", "k"), 0); + smat2.setValue("c", "f", "l", 23); + assertEquals(23, smat2.getValue(0, 1, 1), 0); + assertEquals(23, mat.getValue(2, 1, 1), 0); + assertEquals(23, mat.getValue("c", "f", "l"), 0); + } + + public void testSubAdd() throws Exception { + List s1 = Arrays.asList(new String[]{"a", "b", "c"}); + List s2 = Arrays.asList(new String[]{"e", "f", "g"}); + List s3 = Arrays.asList(new String[]{"k", "l", "m"}); + + MatrixND mat1 = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + + MatrixND mat2 = getFactory().create("Ma mat", new List[]{s1, s2, s3}, new String[]{"dim abc", "dim efg", "dim klm"}); + + MatrixHelper.fill(mat1, 5); + MatrixHelper.fill(mat2, 3); + + MatrixND smat1 = mat1.getSubMatrix(1, "e", 1); + MatrixND smat2 = mat2.getSubMatrix(1, "f", 1); + + smat1.add(smat2); + + assertEquals(5, mat1.getValue(0, 1, 0), 0); + assertEquals(5, mat1.getValue(0, 1, 1), 0); + assertEquals(5, mat1.getValue(0, 1, 2), 0); + assertEquals(5, mat1.getValue(1, 1, 0), 0); + assertEquals(5, mat1.getValue(1, 1, 1), 0); + assertEquals(5, mat1.getValue(1, 1, 2), 0); + assertEquals(5, mat1.getValue(2, 1, 0), 0); + assertEquals(5, mat1.getValue(2, 1, 1), 0); + assertEquals(5, mat1.getValue(2, 1, 2), 0); + assertEquals(5, mat1.getValue(0, 2, 0), 0); + assertEquals(5, mat1.getValue(0, 2, 1), 0); + assertEquals(5, mat1.getValue(0, 2, 2), 0); + assertEquals(5, mat1.getValue(1, 2, 0), 0); + assertEquals(5, mat1.getValue(1, 2, 1), 0); + assertEquals(5, mat1.getValue(1, 2, 2), 0); + assertEquals(5, mat1.getValue(2, 2, 0), 0); + assertEquals(5, mat1.getValue(2, 2, 1), 0); + assertEquals(5, mat1.getValue(2, 2, 2), 0); + + assertEquals(8, mat1.getValue(0, 0, 0), 0); + assertEquals(8, mat1.getValue(0, 0, 1), 0); + assertEquals(8, mat1.getValue(0, 0, 2), 0); + assertEquals(8, mat1.getValue(1, 0, 0), 0); + assertEquals(8, mat1.getValue(1, 0, 1), 0); + assertEquals(8, mat1.getValue(1, 0, 2), 0); + assertEquals(8, mat1.getValue(2, 0, 0), 0); + assertEquals(8, mat1.getValue(2, 0, 1), 0); + assertEquals(8, mat1.getValue(2, 0, 2), 0); + + } + + + public void testSubSubMults() throws Exception { + MatrixND mat = null; + + mat = getFactory().create("Ma mat", new int[]{4, 4}); + + MatrixHelper.fill(mat, 4); + + mat = getFactory().create(mat); + + MatrixND smat1 = mat.getSubMatrix(1, 0, 2); + MatrixND smat2 = smat1.getSubMatrix(0, 2, 1); + + System.out.println("mat:" + mat); + System.out.println("smat1:" + smat1); + System.out.println("smat2:" + smat2); + + smat2.mults(4); + + System.out.println("mat:" + mat); + System.out.println("smat1:" + smat1); + System.out.println("smat2:" + smat2); + + } + + +} // SubMatrixTest + Copied: trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/gui/MatrixTableModelTest.java (from rev 61, trunk/lutinmatrix/src/test/org/codelutin/math/matrix/gui/MatrixTableModelTest.java) =================================================================== --- trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/gui/MatrixTableModelTest.java (rev 0) +++ trunk/lutinmatrix/src/test/java/org/codelutin/math/matrix/gui/MatrixTableModelTest.java 2008-09-01 09:24:33 UTC (rev 64) @@ -0,0 +1,158 @@ +/* *##% + * Copyright (C) 2006 + * Code Lutin, Cédric 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. + *##%*/ + +/* * + * MatrixTableModelND.java + * + * Created: 21 mars 2006 19:05:06 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package 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 junit.framework.TestCase; + + +/** + * @author poussin + * + */ + +public class MatrixTableModelTest extends TestCase { + + MatrixTableModelND model = null; + MatrixND mat = null; + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + List 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","dim3-3"}); + List dim4 = Arrays.asList(new String[]{"dim4-0","dim4-1","dim4-2"}); + mat = MatrixFactory.getInstance().create("mat", + new List[]{dim0,dim1,dim2,dim3,dim4}, + new String[]{"dim0","dim1","dim2","dim3","dim4"}); + model = new MatrixTableModelND(mat); + } + + public void testSetMatrix() { + assertEquals(2, model.addRow); + assertEquals(3, model.addCol); + int[] val = model.multRowCol; + assertEquals(true, Arrays.equals(new int[]{6,4,3,1,1}, val)); + } + + /* + * Test method for 'org.codelutin.math.matrix.gui.MatrixTableModelND.isCellEditable(int, int)' + */ + public void testIsCellEditable() { + assertEquals(false, model.isCellEditable(model.addRow - 1, model.addCol - 1)); + assertEquals(true, model.isCellEditable(model.addRow, model.addCol)); + assertEquals(true, model.isCellEditable(model.addRow + 1, model.addCol + 1)); + } + + /* + * Test method for 'org.codelutin.math.matrix.gui.MatrixTableModelND.tableToMatrix(int, int)' + */ + public void testTableToMatrix() { + int[] val = model.tableToMatrix(5, 4); + assertEquals(true, Arrays.equals(new int[]{0, 1, 1, 0, 2}, val)); + val = model.tableToMatrix(0, 0); + assertEquals(true, Arrays.equals(new int[]{0, 0, 0, 0, 0}, val)); + val = model.tableToMatrix(23, 5); + assertEquals(true, Arrays.equals(new int[]{3, 1, 1, 1, 2}, val)); + } + + /* + * Test method for 'org.codelutin.math.matrix.gui.MatrixTableModelND.getValue(int, int)' + */ + public void testGetValue() { + assertEquals("dim0-0", model.getValue(2, 0)); + assertEquals("dim0-0", model.getValue(3, 0)); + assertEquals("dim0-0", model.getValue(4, 0)); + assertEquals("dim0-0", model.getValue(7, 0)); + assertEquals("dim0-1", model.getValue(8, 0)); + + assertEquals("dim2-0", model.getValue(2, 1)); + assertEquals("dim2-0", model.getValue(3, 1)); + assertEquals("dim2-1", model.getValue(5, 1)); + + assertEquals("dim4-0", model.getValue(2, 2)); + assertEquals("dim4-1", model.getValue(3, 2)); + assertEquals("dim4-2", model.getValue(4, 2)); + assertEquals("dim4-0", model.getValue(5, 2)); + + assertEquals("dim1-0", model.getValue(0, 3)); + + assertEquals(0.0, model.getValue(model.addRow, model.addCol)); + assertEquals(0.0, model.getValue(23 + model.addRow, 5 + model.addCol)); + } + + /* + * Test method for 'org.codelutin.math.matrix.gui.MatrixTableModelND.getColumnName(int)' + */ + public void testGetColumnNameInt() { + + } + + /* + * Test method for 'org.codelutin.math.matrix.gui.MatrixTableModelND.getRowCount()' + */ + public void testGetRowCount() { + + } + + /* + * Test method for 'org.codelutin.math.matrix.gui.MatrixTableModelND.getColumnCount()' + */ + public void testGetColumnCount() { + + } + + /* + * Test method for 'org.codelutin.math.matrix.gui.MatrixTableModelND.getValueAt(int, int)' + */ + public void testGetValueAt() { + + } + + /* + * Test method for 'org.codelutin.math.matrix.gui.MatrixTableModelND.setValueAt(Object, int, int)' + */ + public void testSetValueAtObjectIntInt() { + + } + +} + +
participants (1)
-
bpoussin@users.labs.libre-entreprise.org