Author: chatellier Date: 2009-02-27 18:04:56 +0000 (Fri, 27 Feb 2009) New Revision: 1895 Added: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/SensitivityException.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity/ isis-fish/trunk/src/main/resources/templates/script/ isis-fish/trunk/src/main/resources/templates/script/analyseplan.ftl isis-fish/trunk/src/main/resources/templates/script/equation.ftl isis-fish/trunk/src/main/resources/templates/script/export.ftl isis-fish/trunk/src/main/resources/templates/script/rule.ftl isis-fish/trunk/src/main/resources/templates/script/script.ftl isis-fish/trunk/src/main/resources/templates/script/sensitivity.ftl isis-fish/trunk/src/main/resources/templates/script/simulator.ftl isis-fish/trunk/src/main/resources/templates/ssh/ isis-fish/trunk/src/main/resources/templates/ssh/launch-isis-cron.seq isis-fish/trunk/src/main/resources/templates/ssh/launch-isis-qsub.seq isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/AnalysePlanStorageTest.java isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/ExportStorageTest.java isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/FormuleStorageTest.java isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/RuleStorageTest.java isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/SimulatorStorageTest.java isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceTest.java isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/sensitivity/ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/sensitivity/SensitivityCalculatorRandomMock.java isis-fish/trunk/src/test/resources/test-database/ isis-fish/trunk/src/test/resources/test-database/analyseplans/ isis-fish/trunk/src/test/resources/test-database/analyseplans/Calibration.java isis-fish/trunk/src/test/resources/test-database/analyseplans/Max.java isis-fish/trunk/src/test/resources/test-database/exports/ isis-fish/trunk/src/test/resources/test-database/exports/Abundances.java isis-fish/trunk/src/test/resources/test-database/exports/Biomasses.java isis-fish/trunk/src/test/resources/test-database/exports/CapturesNombre.java isis-fish/trunk/src/test/resources/test-database/exports/CapturesPoids.java isis-fish/trunk/src/test/resources/test-database/exports/CellsDefinition.java isis-fish/trunk/src/test/resources/test-database/exports/EffortsMetier.java isis-fish/trunk/src/test/resources/test-database/exports/MetierZone.java isis-fish/trunk/src/test/resources/test-database/exports/NonActivite.java isis-fish/trunk/src/test/resources/test-database/exports/OwnerMargin.java isis-fish/trunk/src/test/resources/test-database/exports/RegionDefinition.java isis-fish/trunk/src/test/resources/test-database/exports/RejetsNombre.java isis-fish/trunk/src/test/resources/test-database/exports/RejetsPoids.java isis-fish/trunk/src/test/resources/test-database/exports/VesselMargin.java isis-fish/trunk/src/test/resources/test-database/exports/ZonesDefinition.java isis-fish/trunk/src/test/resources/test-database/regions/ isis-fish/trunk/src/test/resources/test-database/regions/DemoRegion/ isis-fish/trunk/src/test/resources/test-database/regions/DemoRegion/data/ isis-fish/trunk/src/test/resources/test-database/regions/DemoRegion/data/data.2.log.db isis-fish/trunk/src/test/resources/test-database/regions/DemoRegion/data/data.data.db isis-fish/trunk/src/test/resources/test-database/regions/DemoRegion/data/data.index.db isis-fish/trunk/src/test/resources/test-database/rules/ isis-fish/trunk/src/test/resources/test-database/rules/Cantonnement.java isis-fish/trunk/src/test/resources/test-database/rules/CantonnementPreSimu.java isis-fish/trunk/src/test/resources/test-database/rules/ChangementParamControlablePresimu.java isis-fish/trunk/src/test/resources/test-database/rules/GraviteCPUE.java isis-fish/trunk/src/test/resources/test-database/rules/InterdictionEngin.java isis-fish/trunk/src/test/resources/test-database/rules/InterdictionEnginPreSimu.java isis-fish/trunk/src/test/resources/test-database/rules/RecrutementLangoustine.java isis-fish/trunk/src/test/resources/test-database/rules/TACpoids.java isis-fish/trunk/src/test/resources/test-database/rules/TailleMin.java isis-fish/trunk/src/test/resources/test-database/scripts/ isis-fish/trunk/src/test/resources/test-database/scripts/GravityModel.java isis-fish/trunk/src/test/resources/test-database/scripts/ResultName.java isis-fish/trunk/src/test/resources/test-database/scripts/RuleUtil.java isis-fish/trunk/src/test/resources/test-database/scripts/SiMatrix.java isis-fish/trunk/src/test/resources/test-database/simulators/ isis-fish/trunk/src/test/resources/test-database/simulators/DefaultSimulator.java Removed: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/factors/ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/factor/ isis-fish/trunk/src/main/resources/ssh/ isis-fish/trunk/src/main/resources/templates/analyseplan.ftl isis-fish/trunk/src/main/resources/templates/equation.ftl isis-fish/trunk/src/main/resources/templates/export.ftl isis-fish/trunk/src/main/resources/templates/rule.ftl isis-fish/trunk/src/main/resources/templates/script.ftl isis-fish/trunk/src/main/resources/templates/sensitivity.ftl isis-fish/trunk/src/main/resources/templates/simulator.ftl isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/factors/ Modified: isis-fish/trunk/changelog.txt isis-fish/trunk/src/main/java/fr/ifremer/isisfish/IsisFish.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/AnalysePlanStorage.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/ExportStorage.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/FormuleStorage.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/RuleStorage.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/ScriptStorage.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/SensitivityStorage.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/SimulatorStorage.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/rule/RuleHelper.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameter.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SSHSimulatorLauncher.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationService.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SubProcessSimulationLauncher.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/ContinuousDomain.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/DesignPlan.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/DiscreteDomain.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/Domain.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/Factor.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/FactorsAnalysePlan.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/Scenario.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/SensitivityCalculator.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/SensitivityScenarios.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/package-info.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/SaveVerfier.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/UIHelper.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity/EditorHelper.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/ParamsUI.jaxx isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/SimulAction.java isis-fish/trunk/src/main/resources/templates/prescript/factorprescript.ftl isis-fish/trunk/src/test/java/fr/ifremer/TestUtils.java isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/ScriptStorageTest.java isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/SensitivityStorageTest.java isis-fish/trunk/src/test/java/fr/ifremer/isisfish/logging/TestUtil.java isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/SimulationPreScriptTest.java isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/launcher/SshSimulatorLauncherTest.java isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/sensitivity/FactorTest.java Log: Move factor package to "sentivitity". Add sentivity simulation start in service. Add tests. Modified: isis-fish/trunk/changelog.txt =================================================================== --- isis-fish/trunk/changelog.txt 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/changelog.txt 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,4 +1,18 @@ -isis-fish (3.2.0.x) xxx +isis-fish (3.2.0.4-rc2) xxx + + * Fix simulation plan subjob number : start at 0 + * Fix bug, database migration asked twice + * Fix VCSSVN getRemoteStatus(), not showed added status file + * Rename "factors" package to "sensitivity" + * Add tests on each storage for testing template content compilation + * Add script templates based on freemarker template engine + +isis-fish (3.2.0.4-rc1) sletellier + + * Fix ask passphrase in svn+ssh mode + * Bugfix release + +isis-fish (3.2.0.3) chemit * Change simulation monitoring to work better with SSH launcher * Update XML-RPC launcher to xmlprc 3 Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/IsisFish.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/IsisFish.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/IsisFish.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -126,6 +126,9 @@ // action after init config.doAction(IsisConfig.Step.AfterInit.ordinal()); + // initVCS ask for passphrase, ui must be set before + initLoookAndFeel(); + try { initVCS(); } catch (Exception eee) { @@ -136,7 +139,7 @@ // after init vcs and local data config.doAction(IsisConfig.Step.AfterInitVCS.ordinal()); - initLoookAndFeel(); + launchUI(); // action after ui launched @@ -146,6 +149,7 @@ quit(); } } + private static void initLoookAndFeel() throws InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { try { Class.forName("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); @@ -155,6 +159,7 @@ log.warn(_("cant start nimbus")); } } + /** * Start daemon that monitor quit value, if value is true, quit isis. Ce * mecanisme permet de faire des actions avant de quitter l'application Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/AnalysePlanStorage.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/AnalysePlanStorage.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/AnalysePlanStorage.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -55,12 +55,15 @@ */ public class AnalysePlanStorage extends JavaSourceStorage implements Docable { // AnalysePlanStorage + /** to use log facility, just put in your code: log.info(\"...\"); */ + private static Log log = LogFactory.getLog(AnalysePlanStorage.class); + public final static String ANALYSE_PLAN_PATH = "analyseplans"; private final static String PARAM_PREFIX = "param_"; - /** to use log facility, just put in your code: log.info(\"...\"); */ - static private Log log = LogFactory.getLog(AnalysePlanStorage.class); + /** Template freemarker pour les plans d'analyse . */ + public static final String ANALYSE_PLAN_TEMPLATE = "templates/script/analyseplan.ftl"; @SuppressWarnings("unchecked") static private Map<String, AnalysePlanStorage> plansCache = Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/ExportStorage.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/ExportStorage.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/ExportStorage.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,5 +1,5 @@ /* *##% - * Copyright (C) 2005 + * Copyright (C) 2005 - 2009 * Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin * * This program is free software; you can redistribute it and/or @@ -17,18 +17,6 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -/* * - * CvsStorage.java - * - * Created: 18 août 2005 15:07:36 CEST - * - * @author Grégoire DESSARD <dessard at codelutin.com> - * @version $Revision$ - * - * Last update: $Date$ - * by : $Author$ - */ - package fr.ifremer.isisfish.datastore; import fr.ifremer.isisfish.IsisFishException; @@ -54,21 +42,30 @@ * Gestion des fichers VCS de type {@link Export} * (appartenant au module exports). * - * @author dessard + * Created: 18 août 2005 15:07:36 CEST + * + * @author Grégoire DESSARD <dessard at codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ */ public class ExportStorage extends JavaSourceStorage implements Docable { - static final public String EXPORT_PATH = "exports"; - /** to use log facility, just put in your code: log.info(\"...\"); */ - static private Log log = LogFactory.getLog(ExportStorage.class); + private static Log log = LogFactory.getLog(ExportStorage.class); + + public static final String EXPORT_PATH = "exports"; + /** Template freemarker pour les scripts d'export . */ + public static final String EXPORT_TEMPLATE = "templates/script/export.ftl"; + @SuppressWarnings("unchecked") - static private Map<String, ExportStorage> scriptsCache = + private static Map<String, ExportStorage> scriptsCache = (Map<String, ExportStorage>) new ReferenceMap(); /** - * Constructeur + * Constructeur. * * @param rootSrc le repertoire root de stockage des exports * @param directory le repertoire de l'export @@ -78,7 +75,7 @@ super(rootSrc, directory, name); } - static public File getExportDirectory() { + public static File getExportDirectory() { File result = IsisFish.config.getDatabaseDirectory(); result = new File(result, EXPORT_PATH); result.mkdirs(); Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/FormuleStorage.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/FormuleStorage.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/FormuleStorage.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,5 +1,5 @@ /* *##% - * Copyright (C) 2006 + * Copyright (C) 2006 - 2009 * Code Lutin, Cédric Pineau, Benjamin Poussin * * This program is free software; you can redistribute it and/or @@ -17,22 +17,9 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -/* * - * FormuleStorage.java - * - * Created: 4 févr. 2006 16:30:59 - * - * @author poussin - * @version $Revision$ - * - * Last update: $Date$ - * by : $Author$ - */ - package fr.ifremer.isisfish.datastore; import java.io.File; -import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -54,16 +41,24 @@ import fr.ifremer.isisfish.entities.Formule; import fr.ifremer.isisfish.vcs.VCSException; - /** + * Formule storage. + * + * Created: 4 févr. 2006 16:30:59 + * * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ */ - - public class FormuleStorage extends CodeSourceStorage implements Formule { public static final String FORMULE_PATH = "formules"; + /** Template freemarker pour les formules. */ + public static final String FORMULE_TEMPLATE = "templates/script/equation.ftl"; + /** * la categorie de la formule */ @@ -81,7 +76,7 @@ this.category = category; } - static public File getFormuleDirectory() { + public static File getFormuleDirectory() { File result = IsisFish.config.getDatabaseDirectory(); result = new File(result, FORMULE_PATH); result.mkdirs(); Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/RuleStorage.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/RuleStorage.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/RuleStorage.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -58,15 +58,18 @@ */ public class RuleStorage extends JavaSourceStorage implements Docable { // RulesStorage + /** to use log facility, just put in your code: log.info(\"...\"); */ + private static Log log = LogFactory.getLog(RuleStorage.class); + public static final String RULE_PATH = "rules"; private final static String PARAM_PREFIX = "param_"; - /** to use log facility, just put in your code: log.info(\"...\"); */ - static private Log log = LogFactory.getLog(RuleStorage.class); + /** Template freemarker pour les regles. */ + public static final String RULE_TEMPLATE = "templates/script/rule.ftl"; @SuppressWarnings("unchecked") - static private Map<String, RuleStorage> rulesCache = + private static Map<String, RuleStorage> rulesCache = (Map<String, RuleStorage>) new ReferenceMap(); /** Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/ScriptStorage.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/ScriptStorage.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/ScriptStorage.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,5 +1,5 @@ /* *##% - * Copyright (C) 2005 + * Copyright (C) 2005 - 2009 * Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin * * This program is free software; you can redistribute it and/or @@ -17,18 +17,6 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -/* * - * ScriptStorage.java - * - * Created: 18 août 2005 15:07:36 CEST - * - * @author Grégoire DESSARD <dessard at codelutin.com> - * @version $Revision$ - * - * Last update: $Date$ - * by : $Author$ - */ - package fr.ifremer.isisfish.datastore; import fr.ifremer.isisfish.IsisFishException; @@ -51,14 +39,25 @@ /** * Gestion des fichers CVS de type scripts (appartenant au module scripts). + * + * Created: 18 août 2005 15:07:36 CEST + * + * @author Grégoire DESSARD <dessard at codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ */ public class ScriptStorage extends JavaSourceStorage implements Docable { - static final public String SCRIPT_PATH = "scripts"; - /** to use log facility, just put in your code: log.info(\"...\"); */ - static private Log log = LogFactory.getLog(ScriptStorage.class); + private static Log log = LogFactory.getLog(ScriptStorage.class); + + public static final String SCRIPT_PATH = "scripts"; + /** Template freemarker pour les scripts. */ + public static final String FORMULE_TEMPLATE = "templates/script/script.ftl"; + @SuppressWarnings("unchecked") static private Map<String, ScriptStorage> scriptsCache = (Map<String, ScriptStorage>) new ReferenceMap(); Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/SensitivityStorage.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/SensitivityStorage.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/SensitivityStorage.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -19,7 +19,7 @@ import fr.ifremer.isisfish.IsisFishException; import fr.ifremer.isisfish.IsisFish; -import fr.ifremer.isisfish.simulator.factors.SensitivityCalculator; +import fr.ifremer.isisfish.simulator.sensitivity.SensitivityCalculator; import fr.ifremer.isisfish.util.Doc; import fr.ifremer.isisfish.util.DocHelper; import fr.ifremer.isisfish.util.Docable; @@ -58,7 +58,7 @@ public final static String SENSITIVITY_PATH = "sensitivity"; /** Template freemarker pour les scripts de sensibilité. */ - public static final String SENSIVITY_TEMPLATE = "templates/sensitivity.ftl"; + public static final String SENSIVITY_TEMPLATE = "templates/script/sensitivity.ftl"; /** * Prefix des paramètres de la classe. Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/SimulatorStorage.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/SimulatorStorage.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/SimulatorStorage.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,5 +1,5 @@ /* *##% - * Copyright (C) 2005 + * Copyright (C) 2005 - 2009 * Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin * * This program is free software; you can redistribute it and/or @@ -17,18 +17,6 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -/* * - * ScriptStorage.java - * - * Created: 18 août 2005 15:07:36 CEST - * - * @author Grégoire DESSARD <dessard at codelutin.com> - * @version $Revision$ - * - * Last update: $Date$ - * by : $Author$ - */ - package fr.ifremer.isisfish.datastore; import java.io.File; @@ -43,16 +31,23 @@ import fr.ifremer.isisfish.vcs.VCSException; /** + * Gestion des fichers CVS de type {@link Simulator} (appartenant au module Simulator). * - * Gestion des fichers CVS de type {@link Simulator} (appratenant au module Simulator). - * - * @author dessard - * + * Created: 18 août 2005 15:07:36 CEST + * + * @author Grégoire DESSARD <dessard at codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ */ public class SimulatorStorage extends JavaSourceStorage { - static final public String SIMULATOR_PATH = "simulators"; + public static final String SIMULATOR_PATH = "simulators"; + /** Template freemarker pour les scripts. */ + public static final String SIMULATOR_TEMPLATE = "templates/script/simulator.ftl"; + /** * * Constructeur @@ -63,7 +58,7 @@ super(rootSrc, directory, name); } - static public File getSimulatorDirectory() { + public static File getSimulatorDirectory() { File result = IsisFish.config.getDatabaseDirectory(); result = new File(result, SIMULATOR_PATH); result.mkdirs(); Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/rule/RuleHelper.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/rule/RuleHelper.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/rule/RuleHelper.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,5 +1,5 @@ /* *##% - * Copyright (C) 2007 + * Copyright (C) 2007 - 2009 * Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin * * This program is free software; you can redistribute it and/or @@ -17,18 +17,6 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -/* * - * RuleHelper.java - * - * Created: 6 juin 07 12:03:42 - * - * @author poussin - * @version $Revision$ - * - * Last update: $Date$ - * by : $Author$ - */ - package fr.ifremer.isisfish.rule; import java.util.Map; @@ -39,18 +27,22 @@ import org.apache.commons.logging.LogFactory; import org.codelutin.topia.persistence.TopiaEntity; -import fr.ifremer.isisfish.IsisFishException; import fr.ifremer.isisfish.datastore.RegionStorage; import fr.ifremer.isisfish.datastore.RuleStorage; -import fr.ifremer.isisfish.simulator.SimulationParameter; import fr.ifremer.isisfish.util.ConverterUtil; /** + * RuleHelper. + * + * Created: 6 juin 07 12:03:42 + * * @author poussin + * @version $Revision$ * + * Last update: $Date$ + * by : $Author$ */ - public class RuleHelper { /** @@ -65,10 +57,10 @@ * @param ruleIndex l'index de la regle * @param rule la regle dont les parametres doivent etre lu depuis les * proprietes - * @param region ??? + * @param region le topia context dont on a besoin * @param props les proprietes contenant les parametre de la regle */ - static public void populateRule(int ruleIndex, RegionStorage region, Rule rule, Properties props) { + public static void populateRule(int ruleIndex, RegionStorage region, Rule rule, Properties props) { ConvertUtilsBean beanUtils = ConverterUtil.getConverter(region.getStorage()); String ruleName = RuleStorage.getName(rule); String paramTag = "rule." + ruleIndex + ".parameter."; Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameter.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameter.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameter.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -87,7 +87,7 @@ protected int numberOfYear = 1; /** le nom de l'objet script a utiliser pour faire la simulation */ - protected String simulatorName = "DefaultSimulator"; + protected String simulatorName = "DefaultSimulator.java"; /** utilisation ou non des optimisations */ protected boolean useOptimization = true; Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SSHSimulatorLauncher.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SSHSimulatorLauncher.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SSHSimulatorLauncher.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -74,6 +74,9 @@ /** Freemarker configuration */ protected Configuration freemarkerConfiguration; + + /** Freemarker qsub template. */ + protected static final String SQUB_SCRIPT_TEMPLATE = "templates/ssh/launch-isis-qsub.seq"; /** * Opened session. @@ -600,10 +603,9 @@ // uncomment this to test on a cron server //String scriptName = "ssh/launch-isis-cron.seq"; // uncomment this to test on a qsub server - String scriptName = "ssh/launch-isis-qsub.seq"; String fileContent = getSimulationScriptLaunchContent( - scriptName, simuationId, simulationZip); + SQUB_SCRIPT_TEMPLATE, simuationId, simulationZip); FileUtil.writeString(tempScript, fileContent); return tempScript; Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationService.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationService.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationService.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -21,27 +21,13 @@ import static org.codelutin.i18n.I18n._; -import fr.ifremer.isisfish.IsisFish; -import fr.ifremer.isisfish.IsisFishRuntimeException; -import fr.ifremer.isisfish.datastore.AnalysePlanStorage; -import fr.ifremer.isisfish.datastore.ExportStorage; -import fr.ifremer.isisfish.datastore.RegionStorage; -import fr.ifremer.isisfish.datastore.RuleStorage; -import fr.ifremer.isisfish.datastore.ScriptStorage; -import fr.ifremer.isisfish.datastore.SimulationStorage; -import fr.ifremer.isisfish.datastore.SimulatorStorage; -import fr.ifremer.isisfish.rule.Rule; -import fr.ifremer.isisfish.simulator.AnalysePlan; -import fr.ifremer.isisfish.simulator.AnalysePlanContext; -import fr.ifremer.isisfish.simulator.SimulationControl; -import fr.ifremer.isisfish.simulator.SimulationException; -import fr.ifremer.isisfish.simulator.SimulationParameter; -import fr.ifremer.isisfish.util.CompileHelper; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -56,6 +42,7 @@ import java.util.TreeSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; + import org.apache.commons.lang.mutable.MutableInt; import org.apache.commons.lang.time.DurationFormatUtils; import org.apache.commons.logging.Log; @@ -67,6 +54,34 @@ import org.codelutin.util.ObjectUtil; import org.codelutin.util.ZipUtil; +import fr.ifremer.isisfish.IsisFish; +import fr.ifremer.isisfish.IsisFishRuntimeException; +import fr.ifremer.isisfish.datastore.AnalysePlanStorage; +import fr.ifremer.isisfish.datastore.ExportStorage; +import fr.ifremer.isisfish.datastore.RegionStorage; +import fr.ifremer.isisfish.datastore.RuleStorage; +import fr.ifremer.isisfish.datastore.ScriptStorage; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.SimulatorStorage; +import fr.ifremer.isisfish.rule.Rule; +import fr.ifremer.isisfish.simulator.AnalysePlan; +import fr.ifremer.isisfish.simulator.AnalysePlanContext; +import fr.ifremer.isisfish.simulator.SimulationControl; +import fr.ifremer.isisfish.simulator.SimulationException; +import fr.ifremer.isisfish.simulator.SimulationParameter; +import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan; +import fr.ifremer.isisfish.simulator.sensitivity.Scenario; +import fr.ifremer.isisfish.simulator.sensitivity.SensitivityCalculator; +import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios; +import fr.ifremer.isisfish.util.ClasspathTemplateLoader; +import fr.ifremer.isisfish.util.CompileHelper; +import fr.ifremer.isisfish.util.ConverterUtil; +import freemarker.cache.TemplateLoader; +import freemarker.ext.beans.BeansWrapper; +import freemarker.template.Configuration; +import freemarker.template.Template; +import freemarker.template.TemplateException; + /** * Cette classe est responsable de conservation de toutes les simulations faites * ou a faire. Pour ajouter une nouvelle simulation on appelle la methode @@ -101,8 +116,14 @@ protected static SimulationService instance = new SimulationService(); + /** Freemarker configuration used to get prescripts content. */ + protected Configuration freemarkerConfiguration; + + /** Freemarker pre script template. */ + protected static final String SENSITIVITY_PRE_SCRIPT = "templates/prescript/factorprescript.ftl"; + /** - * Retourne l'instance du SimulationService a utiliser + * Retourne l'instance du {@link SimulationService} a utiliser * @return l'instance a utiliser */ public static SimulationService getService() { @@ -333,7 +354,7 @@ * * @param id l'identifiant de la simulation * @param param les parametres de la simulation - * @param launcher + * @param launcher le launcher a utiliser pour lancer la simulation * @param priority la priorite de la simulation */ public void submit(String id, SimulationParameter param, @@ -363,6 +384,127 @@ } /** + * Permet d'ajouter une simulation avec des factors a prendre en compte. + * + * @param id l'identifiant de la simulation + * @param param les parametres de la simulation + * @param launcher le launcher a utiliser pour lancer la simulation + * @param priority la priorite de la simulation + * @param sensitivitycalculator l'implementation du calculateur de sensibiilite + * @param designPlan le design plan qui contient les facteurs + */ + public void submit(String id, SimulationParameter param, + SimulatorLauncher launcher, int priority, + SensitivityCalculator sensitivitycalculator, DesignPlan designPlan) { + + try { + SensitivityScenarios sensitivityScenarios = sensitivitycalculator + .compute(designPlan); + + // for each simulation, we neeed to launch a specific simulation + // new simulation ids will be id + "_" + x + // where x is a int starting at 0 + int simulationIndex = 0; + for (Scenario scenario : sensitivityScenarios.getScenarios()) { + + // modify modification parameter + SimulationParameter subParam = param.copy(); + String preScriptContent = generatePreScript(scenario); + subParam.setUsePreScript(true); + subParam.setPreScript(preScriptContent); + + // build new simulation id + String subsimulationId = id + "_" + simulationIndex; + + // on l'ajoute tout de suite a la liste des simulations demandee + SimulationControl control = new SimulationControl( + subsimulationId); + SimulationItem item = new SimulationItem(control, subParam, + null); + SimulationJob job = new SimulationJob(this, item, priority); + job.setLauncher(launcher); + fireStartEvent(job); + + // on construit le zip de la simulation + File zip = prepareSimulationZipFile(control, subParam, true); + item.setSimulationZip(zip); + + if (subParam.getUseAnalysePlan() + && subParam.isIndependentPlan()) { + // c un plan d'analyse independant, on construit toute les sous simu + Runnable task = new PrepareSimulationJob(this, job); + subSimulationComputationExecutor.execute(task); + } else { + // l'item est fini d'etre initialise, on peut l'ajouter a la queue + // sauf si c'etait un plan independant ou se seront les sous simu + // qui seront dans la queue + submit(job); + } + + simulationIndex++; + } + + } catch (Exception e) { + if (log.isErrorEnabled()) { + log.error("Can't get scenarios from calculator", e); + } + } + } + + /** + * Get freemarker configuration. + */ + protected Configuration getFreemarkerConfiguration() { + Configuration configuration = new Configuration(); + + // needed to overwrite "Defaults to default system encoding." + // fix encoding issue on some systems + configuration.setDefaultEncoding("utf-8"); + + // specific template loader to get template from jars (classpath) + TemplateLoader templateLoader = new ClasspathTemplateLoader(); + configuration.setTemplateLoader(templateLoader); + + configuration.setObjectWrapper(new BeansWrapper()); + + return configuration; + } + + /** + * Generate prescript to set factor values before simulation start. + * + * @param scenario + * @return + * @throws IOException if pre script can't be made + * @throws TemplateException if pre script can't be made + */ + protected String generatePreScript(Scenario scenario) throws IOException, + TemplateException { + + // init one at first call + if (freemarkerConfiguration == null) { + freemarkerConfiguration = getFreemarkerConfiguration(); + } + + Writer out = new StringWriter(); + Template template = freemarkerConfiguration + .getTemplate(SENSITIVITY_PRE_SCRIPT); + Map<String, Object> root = new HashMap<String, Object>(); + root.put("scenario", scenario); + root.put("beanUtils", ConverterUtil.getConverter(null)); + + template.process(root, out); + out.flush(); + String scriptContent = out.toString(); + + if (log.isTraceEnabled()) { + log.trace("Simulation prescript content = " + scriptContent); + } + + return scriptContent; + } + + /** * Resoumet une simulation qui a deja été démarrée, mais * on ne faisant que du control de monitoring. * @@ -466,9 +608,7 @@ i.setValue(i.intValue() + 1); // si on a plus de N error, on stop l'executor associe if (i.intValue() >= 5) { - log - .error(_( - "Launcher %s will be stopped because there are too many error (%s)", + log.error(_("Launcher %s will be stopped because there are too many error (%s)", launcher, i.intValue())); SimulationExecutor e = executors.get(launcher); e.pause(); @@ -544,12 +684,12 @@ if (nextJob == null) { // Prepration de la simulation a faire // create next id simulation - planContext.incNumber(); + + // this start a 0 int planNumber = planContext.getNumber(); + if (planNumber > MAX_PLAN_SIMULATION) { - log - .error(_( - "Analyse plan error, too many simulation for %s : %s", + log.error(_("Analyse plan error, too many simulation for %s : %s", id, planNumber)); doNext = false; result = false; @@ -594,6 +734,9 @@ tmpDirectory)); } } + + // increment number for next simulation job + planContext.incNumber(); } } return result; @@ -625,10 +768,7 @@ boolean result = plan.afterSimulation(planContext, sim); doNext = doNext && result; } catch (Exception eee) { - log - .error( - _( - "Stop simulation plan, because can't call afterSimulation correctly on plan %s", + log.error(_("Stop simulation plan, because can't call afterSimulation correctly on plan %s", plan.getClass().getName()), eee); doNext = false; } Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SubProcessSimulationLauncher.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SubProcessSimulationLauncher.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SubProcessSimulationLauncher.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -205,8 +205,7 @@ public SimulationCheckpointExternalProcessThread( SimulationControl control, String simulationId, Process process) { if (log.isInfoEnabled()) { - log - .info("Lancement du thread de surveillance des simulations externes"); + log.info("Lancement du thread de surveillance des simulations externes"); } this.control = control; this.simulationId = simulationId; Copied: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity (from rev 1887, isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/factors) Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/ContinuousDomain.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/factors/ContinuousDomain.java 2009-02-25 16:48:50 UTC (rev 1887) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/ContinuousDomain.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -16,7 +16,7 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -package fr.ifremer.isisfish.simulator.factors; +package fr.ifremer.isisfish.simulator.sensitivity; import java.io.Serializable; Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/DesignPlan.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/factors/DesignPlan.java 2009-02-25 16:48:50 UTC (rev 1887) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/DesignPlan.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -16,9 +16,10 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -package fr.ifremer.isisfish.simulator.factors; +package fr.ifremer.isisfish.simulator.sensitivity; import java.io.Serializable; +import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.builder.ToStringBuilder; @@ -45,7 +46,7 @@ * Constructor. */ public DesignPlan() { - + factors = new ArrayList<Factor<? extends Serializable>>(); } /** Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/DiscreteDomain.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/factors/DiscreteDomain.java 2009-02-25 16:48:50 UTC (rev 1887) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/DiscreteDomain.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -16,7 +16,7 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -package fr.ifremer.isisfish.simulator.factors; +package fr.ifremer.isisfish.simulator.sensitivity; import java.io.Serializable; import java.util.SortedMap; Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/Domain.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/factors/Domain.java 2009-02-25 16:48:50 UTC (rev 1887) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/Domain.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -16,7 +16,7 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -package fr.ifremer.isisfish.simulator.factors; +package fr.ifremer.isisfish.simulator.sensitivity; import java.io.Serializable; Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/Factor.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/factors/Factor.java 2009-02-25 16:48:50 UTC (rev 1887) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/Factor.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -16,7 +16,7 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -package fr.ifremer.isisfish.simulator.factors; +package fr.ifremer.isisfish.simulator.sensitivity; import java.io.Serializable; @@ -36,7 +36,7 @@ * Last update : $Date: 19 févr. 2009 $ * By : $Author: chatellier $ */ -public class Factor<E extends Serializable> implements Serializable { +public class Factor<E extends Serializable> implements Serializable, Cloneable { /** serialVersionUID. */ private static final long serialVersionUID = 1643804268013964453L; @@ -178,10 +178,27 @@ this.path = path; } - /* - * @see java.lang.Object#toString() + /** + * {@inheritDoc} */ @Override + public Object clone() { + + Factor<E> f = new Factor<E>(); + // FIXME make real clone() for domain + f.domain = domain; + f.name = name; + f.path = path; + // FIXME make real clone() for value + f.value = value; + + return f; + } + + /** + * {@inheritDoc} + */ + @Override public String toString() { ToStringBuilder builder = new ToStringBuilder(this); Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/FactorsAnalysePlan.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/factors/FactorsAnalysePlan.java 2009-02-25 16:48:50 UTC (rev 1887) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/FactorsAnalysePlan.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -16,7 +16,7 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -package fr.ifremer.isisfish.simulator.factors; +package fr.ifremer.isisfish.simulator.sensitivity; import static org.codelutin.i18n.I18n._; Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/Scenario.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/factors/Scenario.java 2009-02-25 16:48:50 UTC (rev 1887) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/Scenario.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -16,9 +16,10 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -package fr.ifremer.isisfish.simulator.factors; +package fr.ifremer.isisfish.simulator.sensitivity; import java.io.Serializable; +import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.builder.ToStringBuilder; @@ -48,7 +49,7 @@ * Constructeur. */ public Scenario() { - + factors = new ArrayList<Factor<? extends Serializable>>(); } /** Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/SensitivityCalculator.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/factors/SensitivityCalculator.java 2009-02-25 16:48:50 UTC (rev 1887) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/SensitivityCalculator.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -16,7 +16,7 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -package fr.ifremer.isisfish.simulator.factors; +package fr.ifremer.isisfish.simulator.sensitivity; /** * Interface commune à toutes implémentation @@ -38,10 +38,9 @@ * Return calculator description. * * @return calculator description - * @throws Exception */ - String getDescription() throws Exception; - + String getDescription(); + /** * Envoi un plan a faire analyser par l'outils * d'analyse de sensibilité. @@ -53,18 +52,23 @@ * @param plan plan a analyser * * @return un {@link SensitivityScenarios} + * @throws SensitivityException if calculator impl fail to execute * * @see DesignPlan * @see Scenario * @see SensitivityScenarios */ - SensitivityScenarios compute(DesignPlan plan); - + SensitivityScenarios compute(DesignPlan plan) throws SensitivityException; + /** * Permet de renvoyer les resultats de simulations * à l'outils de d'analyse de sensibilité. * * @param sensitivityScenarios résultats de scenarios + * @throws SensitivityException if calculator impl fail to execute + * + * @see SensitivityScenarios */ - void analyzeResult(SensitivityScenarios sensitivityScenarios); + void analyzeResult(SensitivityScenarios sensitivityScenarios) + throws SensitivityException; } Added: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/SensitivityException.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/SensitivityException.java (rev 0) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/SensitivityException.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,46 @@ +/* *##% + * Copyright (C) 2009 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. + *##%*/ + +package fr.ifremer.isisfish.simulator.sensitivity; + +/** + * Sensitivity Exception throw if calculator, + * fail to answer (ex : R) or something else. + * + * @author chatellier + * @version $Revision: 1.0 $ + * + * Last update : $Date: 26 févr. 2009 $ + * By : $Author: chatellier $ + */ +public class SensitivityException extends Exception { + + /** serialVersionUID. */ + private static final long serialVersionUID = -713095428835197215L; + + /** + * Constructor with message and cause. + * + * @param message message + * @param cause exception cause + */ + public SensitivityException(String message, Throwable cause) { + super(message, cause); + // TODO Auto-generated constructor stub + } +} Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/SensitivityScenarios.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/factors/SensitivityScenarios.java 2009-02-25 16:48:50 UTC (rev 1887) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/SensitivityScenarios.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -16,8 +16,9 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -package fr.ifremer.isisfish.simulator.factors; +package fr.ifremer.isisfish.simulator.sensitivity; +import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.builder.ToStringBuilder; @@ -45,7 +46,7 @@ * Constructeur. */ public SensitivityScenarios() { - + scenarios = new ArrayList<Scenario>(); } /** Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/package-info.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/factors/package-info.java 2009-02-25 16:48:50 UTC (rev 1887) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/sensitivity/package-info.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -8,5 +8,5 @@ * Il contient l'interface permettant d'appeler un outils statistique * comme R (http://www.r-project.org/) ou autre. */ -package fr.ifremer.isisfish.simulator.factors; +package fr.ifremer.isisfish.simulator.sensitivity; Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/SaveVerfier.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/SaveVerfier.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/SaveVerfier.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,7 +1,21 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ +/* *##% + * Copyright (C) 2006 - 2009 + * Ifremer, 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 fr.ifremer.isisfish.ui; Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/UIHelper.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/UIHelper.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/UIHelper.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,5 +1,5 @@ /* *##% - * Copyright (C) 2006 + * Copyright (C) 2006 - 2009 * Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin * * This program is free software; you can redistribute it and/or Copied: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity (from rev 1887, isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/factor) Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity/EditorHelper.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/factor/EditorHelper.java 2009-02-25 16:48:50 UTC (rev 1887) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity/EditorHelper.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -3,11 +3,10 @@ * and open the template in the editor. */ -package fr.ifremer.isisfish.ui.factor; +package fr.ifremer.isisfish.ui.sensitivity; import fr.ifremer.isisfish.ui.input.InputOneEquationUI; import fr.ifremer.isisfish.ui.widget.IntervalPanel; -import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger; Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/ParamsUI.jaxx =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/ParamsUI.jaxx 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/ParamsUI.jaxx 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,6 +1,6 @@ <!-- /* *##% - * Copyright (C) 2005 + * Copyright (C) 2005 - 2009 * Ifremer, Code Lutin, Cedric Pineau, Benjamin Poussin * * This program is free software; you can redistribute it and/or @@ -18,8 +18,8 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -/* * - * IsisFish.java +/** + * ParamsUI. * * Created: 1 aout 2005 18:37:25 CEST * @@ -155,7 +155,7 @@ setRulesItems(); } protected void simul(){ - getContextValue(SimulAction.class).simul(fieldSimulParamsName.getText(), (SimulatorLauncher)comboSelLauncher.getSelectedItem()); + getContextValue(SimulAction.class).launchSimulation(fieldSimulParamsName.getText(), (SimulatorLauncher)comboSelLauncher.getSelectedItem()); SimulUI simul = getParentContainer(SimulUI.class); simul.selTab(6); } Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/SimulAction.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/SimulAction.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/SimulAction.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -62,6 +62,8 @@ import fr.ifremer.isisfish.simulator.launcher.SimulationJob; import fr.ifremer.isisfish.simulator.launcher.SimulationService; import fr.ifremer.isisfish.simulator.launcher.SimulatorLauncher; +import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan; +import fr.ifremer.isisfish.simulator.sensitivity.SensitivityCalculator; import fr.ifremer.isisfish.ui.simulator.filter.SimulationFilterUtil; import fr.ifremer.isisfish.ui.widget.ErrorDialogUI; import fr.ifremer.isisfish.ui.widget.filter.FilterModel; @@ -87,7 +89,7 @@ protected RuleStorage ruleStorage = null; protected List<String> analysePlan = null; protected Map<Rule, String> rules = new HashMap<Rule, String>(); - static private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm"); + private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm"); protected List<String> oldSimulNames = null; protected String simulName = null; /* @@ -608,29 +610,80 @@ public List<SimulatorLauncher> getSimulationLauncher() { return SimulationService.getService().getSimulationLaunchers(); } + /** * Launch automatically the simulation, when is possible (no other simulation) * or wait for the last automatically simulation ended. * - * @param simulId id of the simulation to simulate + * @param simulationId id of the simulation to simulate * @param launcher launcher to use + * + * @see SimulatorLauncher */ - public void simul(String simulId, SimulatorLauncher launcher) { - simulId += " " + dateFormat.format(new java.util.Date()); - log.debug("call simulate"); + public void launchSimulation(String simulationId, SimulatorLauncher launcher) { + + String fullSimulationId = simulationId + " " + dateFormat.format(new java.util.Date()); + + // log + if (log.isDebugEnabled()) { + log.debug("Launch simulation with custom launcher " + launcher.toString()); + } + try { - if (simulId == null || "".equals(simulId) || - SimulationStorage.localyExists(simulId) || - SimulationService.getService().exists(simulId)) { - UserLog.error(_("isisfish.simulator.simulaction.badid", simulId)); + if ("".equals(fullSimulationId) || + SimulationStorage.localyExists(fullSimulationId) || + SimulationService.getService().exists(fullSimulationId)) { + UserLog.error(_("isisfish.simulator.simulaction.badid", fullSimulationId)); } else { SimulationParameter p = param.copy(); - SimulationService.getService().submit(simulId, p, launcher, 0); + SimulationService.getService().submit(fullSimulationId, p, launcher, 0); } } catch (Exception eee) { - log.error("Can't start simulation", eee); + if (log.isErrorEnabled()) { + log.error("Can't start simulation", eee); + } showMsgBox(eee); } } + + /** + * Launch simulation with factors variations parameters. + * + * @param simulationId id of the simulation to simulate + * @param launcher launcher to use + * @param sensitivityCalculator sensitivity calculator to use + * @param designPlan design plan for this simulation + * + * @see SimulatorLauncher + * @see SensitivityCalculator + * @see DesignPlan + */ + public void launchSimulation(String simulationId, SimulatorLauncher launcher, + SensitivityCalculator sensitivityCalculator, DesignPlan designPlan) { + + String fullSimulationId = simulationId + " " + dateFormat.format(new java.util.Date()); + + // log + if (log.isDebugEnabled()) { + log.debug("Launch factor simulation with custom launcher " + launcher.toString()); + log.debug("Using sensitivityCalculator : " + sensitivityCalculator.getDescription()); + } + + try { + if ("".equals(fullSimulationId) || + SimulationStorage.localyExists(fullSimulationId) || + SimulationService.getService().exists(fullSimulationId)) { + UserLog.error(_("isisfish.simulator.simulaction.badid", fullSimulationId)); + } else { + SimulationParameter p = param.copy(); + SimulationService.getService().submit(fullSimulationId, p, launcher, 0); + } + } catch (Exception eee) { + if (log.isErrorEnabled()) { + log.error("Can't start simulation", eee); + } + showMsgBox(eee); + } + } } Deleted: isis-fish/trunk/src/main/resources/templates/analyseplan.ftl =================================================================== --- isis-fish/trunk/src/main/resources/templates/analyseplan.ftl 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/resources/templates/analyseplan.ftl 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,81 +0,0 @@ -package analyseplans; - -import static org.codelutin.i18n.I18n._; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import scripts.ResultName; - -import java.io.Writer; -import org.codelutin.math.matrix.*; -import org.codelutin.util.*; -import org.codelutin.topia.*; - -import fr.ifremer.isisfish.util.Doc; -import fr.ifremer.isisfish.*; -import fr.ifremer.isisfish.simulator.SimulationContext; -import fr.ifremer.isisfish.types.Date; -import fr.ifremer.isisfish.entities.*; -import fr.ifremer.isisfish.simulator.AnalysePlan; -import fr.ifremer.isisfish.simulator.AnalysePlanContext; -import fr.ifremer.isisfish.simulator.SimulationParameter; -import fr.ifremer.isisfish.datastore.SimulationStorage; -import fr.ifremer.isisfish.datastore.ResultStorage; - -/** - * ${name}.java - * - * Created: ${date?date?string.long} - * - * @author ${author} <${email}> - * @version $Revision: 1545 $ - * Last update: $Date: ${date?date?string.long} $ - * by : $Author: ${author} $ - */ -public class ${name} implements AnalysePlan { - - /** to use log facility, just put in your code: log.info("..."); */ - private static Log log = LogFactory.getLog(${name}.class); - - public String [] necessaryResult = { - // put here all necessary result for this rule - // example: - // ResultName.MATRIX_BIOMASS, - // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, - }; - - public String[] getNecessaryResult() { - return this.necessaryResult; - } - - /** - * Permet d''afficher a l''utilisateur une aide sur le plan. - * @return L''aide ou la description du plan - */ - public String getDescription() throws Exception { - // TODO change descrition - return _("TODO ${name} description plan"); - } - - /** - * Appelé au démarrage de la simulation, cette méthode permet d''initialiser - * des valeurs - * @param simulation La simulation pour lequel on utilise cette regle - */ - public void init(AnalysePlanContext context) throws Exception { - // TODO - } - - /** - * Call before each simulation - * @param context plan context - * @param nextSimulation storage used for next simulation - * @return true if we must do next simulation, false to stop plan - * @throws Exception - */ - public boolean next(AnalysePlanContext context, SimulationStorage nextSimulation) throws Exception { - return false; - // TODO - } -} \ No newline at end of file Deleted: isis-fish/trunk/src/main/resources/templates/equation.ftl =================================================================== --- isis-fish/trunk/src/main/resources/templates/equation.ftl 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/resources/templates/equation.ftl 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,12 +0,0 @@ -/** - * ${name}. - * - * Created: ${date?date?string.long} - * - * @author ${author} <${email}> - * @version $Revision: 1545 $ - * Last update: $Date : ${date?date?string.long} $ - * by : $Author: ${author} $ - */ -// put your code here - Deleted: isis-fish/trunk/src/main/resources/templates/export.ftl =================================================================== --- isis-fish/trunk/src/main/resources/templates/export.ftl 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/resources/templates/export.ftl 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,59 +0,0 @@ -package exports; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.Writer; - -import static org.codelutin.i18n.I18n._; -import org.codelutin.math.matrix.*; -import fr.ifremer.isisfish.util.Doc; -import fr.ifremer.isisfish.entities.*; -import fr.ifremer.isisfish.export.Export; -import fr.ifremer.isisfish.datastore.SimulationStorage; -import fr.ifremer.isisfish.datastore.ResultStorage; - -/** - * ${name}.java - * - * Created: ${date?date?string.long} - * - * @author ${author} <${email}> - * @version $Revision: 1545 $ - * - * Last update: $Date: ${date?date?string.long} $ - * by : $Author: ${author} $ - */ -public class ${name} implements Export { - - /** to use log facility, just put in your code: log.info(\"...\"); */ - private static Log log = LogFactory.getLog(${name}.class); - - public String [] necessaryResult = { - // put here all necessary result for this rule - // example: - // ResultName.MATRIX_BIOMASS, - // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, - }; - - public String[] getNecessaryResult() { - return this.necessaryResult; - } - - public String getExportFilename() { - // remove _(...) if you don''t want translation on filename - return _("${name}"); - } - - public String getExtensionFilename() { - return ".csv"; - } - - public String getDescription() { - return _("TODO export description"); - } - - public void export(SimulationStorage simulation, Writer out) throws Exception { - // put your code here, and write export with: out.write("...") - } -} \ No newline at end of file Modified: isis-fish/trunk/src/main/resources/templates/prescript/factorprescript.ftl =================================================================== --- isis-fish/trunk/src/main/resources/templates/prescript/factorprescript.ftl 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/resources/templates/prescript/factorprescript.ftl 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,18 +1,22 @@ -// inject factors into simulation - //SimulationStorage simulation = context.getSimulationStorage(); //SimulationParameter parameters = simulation.getParameter(); //String presimulationScript = parameters.getPreScript(); import org.apache.commons.beanutils.BeanUtils; +import org.apache.commons.beanutils.ConvertUtilsBean; +import fr.ifremer.isisfish.util.ConverterUtil; +ConvertUtilsBean beanUtils = ConverterUtil.getConverter(null); + <#list scenario.factors as factor> // Factor : ${factor.name} <#assign value=factor.value /> +<#assign serializedValue=beanUtils.convert(value)/> <#assign path=factor.path /> <#assign topiaId=path?substring(0, path?last_index_of("#"))/> <#assign propertyName=path?substring(path?last_index_of("#") + 1)/> +Object value = beanUtils.convert("${serializedValue}", ${value.class.name}.class); TopiaEntity entity = db.findByTopiaId("${topiaId}"); -BeanUtils.setProperty(entity, "${propertyName}", "${value}"); +BeanUtils.setProperty(entity, "${propertyName}", value); </#list> \ No newline at end of file Deleted: isis-fish/trunk/src/main/resources/templates/rule.ftl =================================================================== --- isis-fish/trunk/src/main/resources/templates/rule.ftl 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/resources/templates/rule.ftl 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,93 +0,0 @@ -package rules; - -import static org.codelutin.i18n.I18n._; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import scripts.ResultName; - -import java.io.Writer; - -import org.codelutin.math.matrix.*; - -import fr.ifremer.isisfish.util.Doc; -import fr.ifremer.isisfish.simulator.SimulationContext; -import fr.ifremer.isisfish.types.Date; -import fr.ifremer.isisfish.entities.*; -import fr.ifremer.isisfish.rule.AbstractRule; -import fr.ifremer.isisfish.datastore.SimulationStorage; -import fr.ifremer.isisfish.datastore.ResultStorage; - -/** - * ${name}.java - * - * Created: ${date?date?string.long} - * - * @author ${author} <${email}> - * @version $Revision: 1545 $ - * Last update: $Date: ${date?date?string.long} $ - * by : $Author: ${author} $ - */ -public class ${name} extends AbstractRule { - - /** to use log facility, just put in your code: log.info("..."); */ - private static Log log = LogFactory.getLog(${name}.class); - - public String [] necessaryResult = { - // put here all necessary result for this rule - // example: - // ResultName.MATRIX_BIOMASS, - // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, - }; - - public String[] getNecessaryResult() { - return this.necessaryResult; - } - - /** - * Permet d'afficher a l'utilisateur une aide sur la regle. - * @return L'aide ou la description de la regle - */ - public String getDescription() throws Exception { - // TODO - return _("TODO description rule"); - } - - /** - * Appelé au démarrage de la simulation, cette méthode permet d'initialiser - * des valeurs - * @param simulation La simulation pour lequel on utilise cette regle - */ - public void init(SimulationContext context) throws Exception { - // TODO - } - - /** - * La condition qui doit etre vrai pour faire les actions - * @param simulation La simulation pour lequel on utilise cette regle - * @return vrai si on souhaite que les actions soit faites - */ - public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception { - // TODO - return false; - } - - /** - * Si la condition est vrai alors cette action est executée avant le pas - * de temps de la simulation. - * @param simulation La simulation pour lequel on utilise cette regle - */ - public void preAction(SimulationContext context, Date date, Metier metier) throws Exception { - // TODO - } - - /** - * Si la condition est vrai alors cette action est executée apres le pas - * de temps de la simulation. - * @param simulation La simulation pour lequel on utilise cette regle - */ - public void postAction(SimulationContext context, Date date, Metier metier) throws Exception { - // TODO - } -} \ No newline at end of file Copied: isis-fish/trunk/src/main/resources/templates/script/analyseplan.ftl (from rev 1887, isis-fish/trunk/src/main/resources/templates/analyseplan.ftl) =================================================================== --- isis-fish/trunk/src/main/resources/templates/script/analyseplan.ftl (rev 0) +++ isis-fish/trunk/src/main/resources/templates/script/analyseplan.ftl 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,102 @@ +package analyseplans; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import scripts.ResultName; + +import java.io.Writer; +import org.codelutin.math.matrix.*; +import org.codelutin.util.*; +import org.codelutin.topia.*; + +import fr.ifremer.isisfish.util.Doc; +import fr.ifremer.isisfish.*; +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.simulator.AnalysePlan; +import fr.ifremer.isisfish.simulator.AnalysePlanContext; +import fr.ifremer.isisfish.simulator.SimulationParameter; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +/** + * ${name}.java + * + * Created: ${date?date?string.long} + * + * @author ${author} <${email}> + * @version $Revision: 1545 $ + * Last update: $Date: ${date?date?string.long} $ + * by : $Author: ${author} $ + */ +public class ${name} implements AnalysePlan { + + /** to use log facility, just put in your code: log.info("..."); */ + private static Log log = LogFactory.getLog(${name}.class); + + public String [] necessaryResult = { + // put here all necessary result for this rule + // example: + // ResultName.MATRIX_BIOMASS, + // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + }; + + @Override + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + /** + * Permet d'afficher a l'utilisateur une aide sur le plan. + * @return L''aide ou la description du plan + */ + @Override + public String getDescription() throws Exception { + // TODO change descrition + return _("TODO ${name} description plan"); + } + + /** + * Appelé au démarrage de la simulation, cette méthode permet d''initialiser + * des valeurs + * @param simulation La simulation pour lequel on utilise cette regle + */ + @Override + public void init(AnalysePlanContext context) throws Exception { + // TODO + } + + /** + * Call before each simulation. + * + * @param context plan context + * @param nextSimulation storage used for next simulation + * @return true if we must do next simulation, false to stop plan + * @throws Exception + */ + @Override + public boolean beforeSimulation(AnalysePlanContext context, + SimulationStorage nextSimulation) throws Exception { + + return true; + } + + /** + * Call after each simulation. + * + * @param context plan context + * @param lastSimulation storage used for simulation + * @return true if we must do next simulation, false to stop plan + * @throws Exception + */ + @Override + public boolean afterSimulation(AnalysePlanContext context, + SimulationStorage lastSimulation) throws Exception { + + return true; + } +} \ No newline at end of file Copied: isis-fish/trunk/src/main/resources/templates/script/equation.ftl (from rev 1887, isis-fish/trunk/src/main/resources/templates/equation.ftl) =================================================================== --- isis-fish/trunk/src/main/resources/templates/script/equation.ftl (rev 0) +++ isis-fish/trunk/src/main/resources/templates/script/equation.ftl 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,12 @@ +/** + * ${name}. + * + * Created: ${date?date?string.long} + * + * @author ${author} <${email}> + * @version $Revision: 1545 $ + * Last update: $Date : ${date?date?string.long} $ + * by : $Author: ${author} $ + */ +// put your code here + Copied: isis-fish/trunk/src/main/resources/templates/script/export.ftl (from rev 1887, isis-fish/trunk/src/main/resources/templates/export.ftl) =================================================================== --- isis-fish/trunk/src/main/resources/templates/script/export.ftl (rev 0) +++ isis-fish/trunk/src/main/resources/templates/script/export.ftl 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,59 @@ +package exports; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.Writer; + +import static org.codelutin.i18n.I18n._; +import org.codelutin.math.matrix.*; +import fr.ifremer.isisfish.util.Doc; +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.export.Export; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +/** + * ${name}.java + * + * Created: ${date?date?string.long} + * + * @author ${author} <${email}> + * @version $Revision: 1545 $ + * + * Last update: $Date: ${date?date?string.long} $ + * by : $Author: ${author} $ + */ +public class ${name} implements Export { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + private static Log log = LogFactory.getLog(${name}.class); + + public String [] necessaryResult = { + // put here all necessary result for this rule + // example: + // ResultName.MATRIX_BIOMASS, + // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + public String getExportFilename() { + // remove _(...) if you don''t want translation on filename + return _("${name}"); + } + + public String getExtensionFilename() { + return ".csv"; + } + + public String getDescription() { + return _("TODO export description"); + } + + public void export(SimulationStorage simulation, Writer out) throws Exception { + // put your code here, and write export with: out.write("...") + } +} \ No newline at end of file Copied: isis-fish/trunk/src/main/resources/templates/script/rule.ftl (from rev 1887, isis-fish/trunk/src/main/resources/templates/rule.ftl) =================================================================== --- isis-fish/trunk/src/main/resources/templates/script/rule.ftl (rev 0) +++ isis-fish/trunk/src/main/resources/templates/script/rule.ftl 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,93 @@ +package rules; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import scripts.ResultName; + +import java.io.Writer; + +import org.codelutin.math.matrix.*; + +import fr.ifremer.isisfish.util.Doc; +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.rule.AbstractRule; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +/** + * ${name}.java + * + * Created: ${date?date?string.long} + * + * @author ${author} <${email}> + * @version $Revision: 1545 $ + * Last update: $Date: ${date?date?string.long} $ + * by : $Author: ${author} $ + */ +public class ${name} extends AbstractRule { + + /** to use log facility, just put in your code: log.info("..."); */ + private static Log log = LogFactory.getLog(${name}.class); + + public String [] necessaryResult = { + // put here all necessary result for this rule + // example: + // ResultName.MATRIX_BIOMASS, + // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + /** + * Permet d'afficher a l'utilisateur une aide sur la regle. + * @return L'aide ou la description de la regle + */ + public String getDescription() throws Exception { + // TODO + return _("TODO description rule"); + } + + /** + * Appelé au démarrage de la simulation, cette méthode permet d'initialiser + * des valeurs + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void init(SimulationContext context) throws Exception { + // TODO + } + + /** + * La condition qui doit etre vrai pour faire les actions + * @param simulation La simulation pour lequel on utilise cette regle + * @return vrai si on souhaite que les actions soit faites + */ + public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception { + // TODO + return false; + } + + /** + * Si la condition est vrai alors cette action est executée avant le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void preAction(SimulationContext context, Date date, Metier metier) throws Exception { + // TODO + } + + /** + * Si la condition est vrai alors cette action est executée apres le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void postAction(SimulationContext context, Date date, Metier metier) throws Exception { + // TODO + } +} \ No newline at end of file Copied: isis-fish/trunk/src/main/resources/templates/script/script.ftl (from rev 1887, isis-fish/trunk/src/main/resources/templates/script.ftl) =================================================================== --- isis-fish/trunk/src/main/resources/templates/script/script.ftl (rev 0) +++ isis-fish/trunk/src/main/resources/templates/script/script.ftl 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,28 @@ +package scripts; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import fr.ifremer.isisfish.util.Doc; +import fr.ifremer.isisfish.entities.*; +import org.codelutin.math.matrix.*; + +/** + * ${name}.java + * + * Created: ${date?date?string.long} + * + * @author ${author} <$email}> + * @version $Revision: 0 $ + * + * Last update: $Date: ${date?date?string.long} $ + * by : $Author: ${author} $ + */ +public class ${name} { + + /** to use log facility, just put in your code: log.info("..."); */ + private static Log log = LogFactory.getLog(${name}.class); + + // add your method here + +} \ No newline at end of file Copied: isis-fish/trunk/src/main/resources/templates/script/sensitivity.ftl (from rev 1887, isis-fish/trunk/src/main/resources/templates/sensitivity.ftl) =================================================================== --- isis-fish/trunk/src/main/resources/templates/script/sensitivity.ftl (rev 0) +++ isis-fish/trunk/src/main/resources/templates/script/sensitivity.ftl 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,80 @@ +package sensitivity; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.codelutin.math.matrix.*; + +import fr.ifremer.isisfish.util.Doc; +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.simulator.sensitivity.*; + +/** + * ${name}.java + * + * Created: ${date?date?string.long} + * + * @author ${author} <${email}> + * @version $Revision: 0 $ + * + * Last update: $Date: ${date?date?string.long} $ + * by : $Author: ${author} $ + */ +public class ${name} implements SensitivityCalculator { + + /** to use log facility, just put in your code: log.info("..."); */ + private static Log log = LogFactory.getLog(${name}.class); + + /** + * Return calculator description. + * + * @return calculator description + * @throws Exception + */ + public String getDescription() { + // TODO change descrition + return _("TODO ${name} description plan"); + } + + /** + * Envoi un plan a faire analyser par l'outils + * d'analyse de sensibilité. + * + * Retourne un {@link SensitivityScenarios} qui + * représente l'ensemble des scenarios à prendre + * en compte pour les simulations. + * + * @param plan plan a analyser + * + * @return un {@link SensitivityScenarios} + * @throws SensitivityException if calculator impl fail to execute + * + * @see DesignPlan + * @see Scenario + * @see SensitivityScenarios + */ + public SensitivityScenarios compute(DesignPlan plan) throws SensitivityException { + + SensitivityScenarios sensitivityScenarios = new SensitivityScenarios(); + + // FIXME add implemantation + + return null; + } + + /** + * Permet de renvoyer les resultats de simulations + * à l'outils de d'analyse de sensibilité. + * + * @param sensitivityScenarios résultats de scenarios + * @throws SensitivityException if calculator impl fail to execute + * + * @see SensitivityScenarios + */ + public void analyzeResult(SensitivityScenarios sensitivityScenarios) + throws SensitivityException { + + } +} \ No newline at end of file Copied: isis-fish/trunk/src/main/resources/templates/script/simulator.ftl (from rev 1887, isis-fish/trunk/src/main/resources/templates/simulator.ftl) =================================================================== --- isis-fish/trunk/src/main/resources/templates/script/simulator.ftl (rev 0) +++ isis-fish/trunk/src/main/resources/templates/script/simulator.ftl 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,32 @@ +package simulators; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.codelutin.math.matrix.*; + +import fr.ifremer.isisfish.util.Doc; +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.simulator.Simulator; +import fr.ifremer.isisfish.simulator.SimulationContext; + +/** + * ${name}.java + * + * Created: ${date?date?string.long} + * + * @author ${author} <${email}> + * @version $Revision: 1545 $ + * + * Last update $Date ${date?date?string.long} $ + * by : $Author: ${author} $ + */ +public class ${name} implements Simulator { + + /** to use log facility, just put in your code: log.info("..."); */ + private static Log log = LogFactory.getLog(${name}.class); + + public void simulate(SimulationContext context) throws Exception { + // put your code here + } +} \ No newline at end of file Deleted: isis-fish/trunk/src/main/resources/templates/script.ftl =================================================================== --- isis-fish/trunk/src/main/resources/templates/script.ftl 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/resources/templates/script.ftl 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,28 +0,0 @@ -package scripts; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import fr.ifremer.isisfish.util.Doc; -import fr.ifremer.isisfish.entities.*; -import org.codelutin.math.matrix.*; - -/** - * ${name}.java - * - * Created: ${date?date?string.long} - * - * @author ${author} <$email}> - * @version $Revision: 0 $ - * - * Last update: $Date: ${date?date?string.long} $ - * by : $Author: ${author} $ - */ -public class ${name} { - - /** to use log facility, just put in your code: log.info("..."); */ - private static Log log = LogFactory.getLog(${name}.class); - - // add your method here - -} \ No newline at end of file Deleted: isis-fish/trunk/src/main/resources/templates/sensitivity.ftl =================================================================== --- isis-fish/trunk/src/main/resources/templates/sensitivity.ftl 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/resources/templates/sensitivity.ftl 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,75 +0,0 @@ -package sensitivity; - -import static org.codelutin.i18n.I18n._; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.codelutin.math.matrix.*; - -import fr.ifremer.isisfish.util.Doc; -import fr.ifremer.isisfish.entities.*; -import fr.ifremer.isisfish.simulator.factors.*; - -/** - * ${name}.java - * - * Created: ${date?date?string.long} - * - * @author ${author} <${email}> - * @version $Revision: 0 $ - * - * Last update: $Date: ${date?date?string.long} $ - * by : $Author: ${author} $ - */ -public class ${name} implements SensitivityCalculator { - - /** to use log facility, just put in your code: log.info("..."); */ - private static Log log = LogFactory.getLog(${name}.class); - - /** - * Return calculator description. - * - * @return calculator description - * @throws Exception - */ - public String getDescription() throws Exception { - // TODO change descrition - return _("TODO ${name} description plan"); - } - - /** - * Envoi un plan a faire analyser par l'outils - * d'analyse de sensibilité. - * - * Retourne un {@link SensitivityScenarios} qui - * représente l'ensemble des scenarios à prendre - * en compte pour les simulations. - * - * @param plan plan a analyser - * - * @return un {@link SensitivityScenarios} - * - * @see DesignPlan - * @see Scenario - * @see SensitivityScenarios - */ - public SensitivityScenarios compute(DesignPlan plan) { - - SensitivityScenarios sensitivityScenarios = new SensitivityScenarios(); - - // FIXME add implemantation - - return null; - } - - /** - * Permet de renvoyer les resultats de simulations - * à l'outils de d'analyse de sensibilité. - * - * @param sensitivityScenarios résultats de scenarios - */ - public void analyzeResult(SensitivityScenarios sensitivityScenarios) { - - } -} \ No newline at end of file Deleted: isis-fish/trunk/src/main/resources/templates/simulator.ftl =================================================================== --- isis-fish/trunk/src/main/resources/templates/simulator.ftl 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/main/resources/templates/simulator.ftl 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,32 +0,0 @@ -package simulators; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.codelutin.math.matrix.*; - -import fr.ifremer.isisfish.util.Doc; -import fr.ifremer.isisfish.entities.*; -import fr.ifremer.isisfish.simulator.Simulator; -import fr.ifremer.isisfish.simulator.SimulationContext; - -/** - * ${name}.java - * - * Created: ${date?date?string.long} - * - * @author ${author} <${email}> - * @version $Revision: 1545 $ - * - * Last update $Date ${date?date?string.long} $ - * by : $Author: ${author} $ - */ -public class ${name} implements Simulator { - - /** to use log facility, just put in your code: log.info("..."); */ - private static Log log = LogFactory.getLog(${name}.class); - - public void simulate(SimulationContext context) throws Exception { - // put your code here - } -} \ No newline at end of file Copied: isis-fish/trunk/src/main/resources/templates/ssh/launch-isis-cron.seq (from rev 1887, isis-fish/trunk/src/main/resources/ssh/launch-isis-cron.seq) =================================================================== --- isis-fish/trunk/src/main/resources/templates/ssh/launch-isis-cron.seq (rev 0) +++ isis-fish/trunk/src/main/resources/templates/ssh/launch-isis-cron.seq 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,7 @@ +#!/bin/bash + +cd "${isishome}" +#source /usr/share/modules/init/csh +#module load java/1.6.0 + +java -jar isis-fish*.jar --option launch.ui false --simulateWithSimulation "${simulationid}" "${simulationzip}" Copied: isis-fish/trunk/src/main/resources/templates/ssh/launch-isis-qsub.seq (from rev 1887, isis-fish/trunk/src/main/resources/ssh/launch-isis-qsub.seq) =================================================================== --- isis-fish/trunk/src/main/resources/templates/ssh/launch-isis-qsub.seq (rev 0) +++ isis-fish/trunk/src/main/resources/templates/ssh/launch-isis-qsub.seq 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,9 @@ +#!/bin/csh + +#PBS -l mem=1000mb + +cd "${isishome}" +source /usr/share/modules/init/csh +module load java/1.6.0 + +java -jar isis-fish*.jar --option launch.ui false --simulateWithSimulation "${simulationid}" "${simulationzip}" Modified: isis-fish/trunk/src/test/java/fr/ifremer/TestUtils.java =================================================================== --- isis-fish/trunk/src/test/java/fr/ifremer/TestUtils.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/test/java/fr/ifremer/TestUtils.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -5,6 +5,10 @@ import org.codelutin.util.FileUtil; import fr.ifremer.isisfish.IsisFish; +import fr.ifremer.isisfish.util.ClasspathTemplateLoader; +import freemarker.cache.TemplateLoader; +import freemarker.ext.beans.BeansWrapper; +import freemarker.template.Configuration; /** * Une classe pour avoir des choses utiles pour tous les tests d'isis @@ -51,18 +55,48 @@ System.setProperty("database.directory", dirDatabase.getAbsolutePath()); System.setProperty("launch.ui", "false"); + System.setProperty("user.home", dirDatabase.getAbsolutePath()); IsisFish.init(); IsisFish.initVCS(); + + FileUtil.copyRecursively(new File("src/test/resources/test-database/analyseplans"), dirDatabase); + FileUtil.copyRecursively(new File("src/test/resources/test-database/export"), dirDatabase); + FileUtil.copyRecursively(new File("src/test/resources/test-database/regions"), dirDatabase); + FileUtil.copyRecursively(new File("src/test/resources/test-database/rules"), dirDatabase); + FileUtil.copyRecursively(new File("src/test/resources/test-database/scripts"), dirDatabase); + FileUtil.copyRecursively(new File("src/test/resources/test-database/simulators"), dirDatabase); } /** * Delete created temp directory. */ public static void clean() { + System.setProperty("user.home", ""); if(dirDatabase != null) { FileUtil.deleteRecursively(dirDatabase); dirDatabase = null; } } + + /** + * Return common script freemarker configuration. + * + * @return freemarker {@link Configuration} + */ + public static Configuration getFreemarkerConfiguration() { + Configuration freemarkerConfiguration = new Configuration(); + + // needed to overwrite "Defaults to default system encoding." + // fix encoding issue on some systems + freemarkerConfiguration.setDefaultEncoding("utf-8"); + + // specific template loader to get template from jars (classpath) + TemplateLoader templateLoader = new ClasspathTemplateLoader(); + freemarkerConfiguration.setTemplateLoader(templateLoader); + + freemarkerConfiguration.setObjectWrapper(new BeansWrapper()); + + return freemarkerConfiguration; + } } Added: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/AnalysePlanStorageTest.java =================================================================== --- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/AnalysePlanStorageTest.java (rev 0) +++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/AnalysePlanStorageTest.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,96 @@ +/* *##% + * Copyright (C) 2006 - 2009 + * Ifremer, 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 fr.ifremer.isisfish.datastore; + +import java.io.StringWriter; +import java.io.Writer; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import fr.ifremer.TestUtils; +import fr.ifremer.isisfish.IsisFish; +import freemarker.template.Configuration; +import freemarker.template.Template; + +/** + * AnalysePlanStorageTest. + * + * Created: 7 août 2006 11:07:57 + * + * @author poussin + * @version $Revision: 1526 $ + * + * Last update: $Date: 2008-10-07 18:46:13 +0200 (mar 07 oct 2008) $ + * by : $Author: tchemit $ + */ +public class AnalysePlanStorageTest { + + protected static Configuration freemarkerConfiguration; + + @BeforeClass + public static void init() throws Exception { + TestUtils.init(); + freemarkerConfiguration = TestUtils.getFreemarkerConfiguration(); + } + + @Test + public void testNewAnalysePlanWithCompilation() throws Exception { + + String fileName = "TestAnalysePlan1"; + + AnalysePlanStorage analysePlanStorage = AnalysePlanStorage + .getAnalysePlan(fileName); + + // get template + Template template = freemarkerConfiguration + .getTemplate(AnalysePlanStorage.ANALYSE_PLAN_TEMPLATE); + + // context values + Map<String, Object> root = new HashMap<String, Object>(); + // FIXME what is category ? + root.put("category", ""); + root.put("name", fileName); + root.put("date", new Date()); + root.put("author", IsisFish.config.getUserName()); + root.put("email", IsisFish.config.getUserMail()); + + // process template + Writer out = new StringWriter(); + template.process(root, out); + out.flush(); + String content = out.toString(); + + // remove it to compile, it's in isis fish data project + Assert.assertTrue(content.indexOf("import scripts.ResultName;") > 0); + content = content.replaceFirst("import scripts.ResultName;", ""); + + analysePlanStorage.setContent(content); + + // 0 = compile success + int compileResult = analysePlanStorage.compile(false, null); + Assert.assertEquals(0, compileResult); + } + +} Added: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/ExportStorageTest.java =================================================================== --- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/ExportStorageTest.java (rev 0) +++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/ExportStorageTest.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,90 @@ +/* *##% + * Copyright (C) 2006 - 2009 + * Ifremer, 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 fr.ifremer.isisfish.datastore; + +import java.io.StringWriter; +import java.io.Writer; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import fr.ifremer.TestUtils; +import fr.ifremer.isisfish.IsisFish; +import freemarker.template.Configuration; +import freemarker.template.Template; + +/** + * ExportStorageTest. + * + * Created: 7 août 2006 11:07:57 + * + * @author poussin + * @version $Revision: 1526 $ + * + * Last update: $Date: 2008-10-07 18:46:13 +0200 (mar 07 oct 2008) $ + * by : $Author: tchemit $ + */ +public class ExportStorageTest { + + protected static Configuration freemarkerConfiguration; + + @BeforeClass + public static void init() throws Exception { + TestUtils.init(); + freemarkerConfiguration = TestUtils.getFreemarkerConfiguration(); + } + + @Test + public void testNewExportWithCompilation() throws Exception { + + String fileName = "TestExport1"; + + ExportStorage exportStorage = ExportStorage + .getExport(fileName); + + // get template + Template template = freemarkerConfiguration + .getTemplate(ExportStorage.EXPORT_TEMPLATE); + + // context values + Map<String, Object> root = new HashMap<String, Object>(); + // FIXME what is category ? + root.put("category", ""); + root.put("name", fileName); + root.put("date", new Date()); + root.put("author", IsisFish.config.getUserName()); + root.put("email", IsisFish.config.getUserMail()); + + // process template + Writer out = new StringWriter(); + template.process(root, out); + out.flush(); + exportStorage.setContent(out.toString()); + + // 0 = compile success + int compileResult = exportStorage.compile(false, null); + Assert.assertEquals(0, compileResult); + } + +} Added: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/FormuleStorageTest.java =================================================================== --- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/FormuleStorageTest.java (rev 0) +++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/FormuleStorageTest.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,90 @@ +/* *##% + * Copyright (C) 2006 - 2009 + * Ifremer, 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 fr.ifremer.isisfish.datastore; + +import java.io.StringWriter; +import java.io.Writer; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.junit.BeforeClass; +import org.junit.Test; + +import fr.ifremer.TestUtils; +import fr.ifremer.isisfish.IsisFish; +import freemarker.template.Configuration; +import freemarker.template.Template; + +/** + * FormuleStorageTest. + * + * Created: 7 août 2006 11:07:57 + * + * @author poussin + * @version $Revision: 1526 $ + * + * Last update: $Date: 2008-10-07 18:46:13 +0200 (mar 07 oct 2008) $ + * by : $Author: tchemit $ + */ +public class FormuleStorageTest { + + protected static Configuration freemarkerConfiguration; + + @BeforeClass + public static void init() throws Exception { + TestUtils.init(); + freemarkerConfiguration = TestUtils.getFreemarkerConfiguration(); + } + + @Test + public void testNewFormuleWithCompilation() throws Exception { + + String fileName = "TestFormule1"; + + FormuleStorage formuleStorage = FormuleStorage + .getFormule("test", fileName); + + // get template + Template template = freemarkerConfiguration + .getTemplate(FormuleStorage.FORMULE_TEMPLATE); + + // context values + Map<String, Object> root = new HashMap<String, Object>(); + // FIXME what is category ? + root.put("category", ""); + root.put("name", fileName); + root.put("date", new Date()); + root.put("author", IsisFish.config.getUserName()); + root.put("email", IsisFish.config.getUserMail()); + + // process template + Writer out = new StringWriter(); + template.process(root, out); + out.flush(); + formuleStorage.setContent(out.toString()); + + // 0 = compile success + // FIXME test with compile helper + //int compileResult = formuleStorage.compile(false, null); + //Assert.assertEquals(0, compileResult); + } + +} Added: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/RuleStorageTest.java =================================================================== --- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/RuleStorageTest.java (rev 0) +++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/RuleStorageTest.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,96 @@ +/* *##% + * Copyright (C) 2006 - 2009 + * Ifremer, 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 fr.ifremer.isisfish.datastore; + +import java.io.StringWriter; +import java.io.Writer; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import fr.ifremer.TestUtils; +import fr.ifremer.isisfish.IsisFish; +import freemarker.template.Configuration; +import freemarker.template.Template; + +/** + * RuleStorageTest. + * + * Created: 7 août 2006 11:07:57 + * + * @author poussin + * @version $Revision: 1526 $ + * + * Last update: $Date: 2008-10-07 18:46:13 +0200 (mar 07 oct 2008) $ + * by : $Author: tchemit $ + */ +public class RuleStorageTest { + + protected static Configuration freemarkerConfiguration; + + @BeforeClass + public static void init() throws Exception { + TestUtils.init(); + freemarkerConfiguration = TestUtils.getFreemarkerConfiguration(); + } + + @Test + public void testNewRuleWithCompilation() throws Exception { + + String fileName = "TestRule1"; + + RuleStorage ruleStorage = RuleStorage + .getRule(fileName); + + // get template + Template template = freemarkerConfiguration + .getTemplate(RuleStorage.RULE_TEMPLATE); + + // context values + Map<String, Object> root = new HashMap<String, Object>(); + // FIXME what is category ? + root.put("category", ""); + root.put("name", fileName); + root.put("date", new Date()); + root.put("author", IsisFish.config.getUserName()); + root.put("email", IsisFish.config.getUserMail()); + + // process template + Writer out = new StringWriter(); + template.process(root, out); + out.flush(); + String content = out.toString(); + + // remove it to compile, it's in isis fish data project + Assert.assertTrue(content.indexOf("import scripts.ResultName;") > 0); + content = content.replaceFirst("import scripts.ResultName;", ""); + + ruleStorage.setContent(content); + + // 0 = compile success + int compileResult = ruleStorage.compile(false, null); + Assert.assertEquals(0, compileResult); + } + +} Modified: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/ScriptStorageTest.java =================================================================== --- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/ScriptStorageTest.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/ScriptStorageTest.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,5 +1,5 @@ /* *##% - * Copyright (C) 2006 + * Copyright (C) 2006 - 2009 * Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin * * This program is free software; you can redistribute it and/or @@ -17,79 +17,114 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -/* * - * ScriptStorageTest.java - * - * Created: 7 août 2006 11:07:57 - * - * @author poussin - * @version $Revision$ - * - * Last update: $Date$ - * by : $Author$ - */ - package fr.ifremer.isisfish.datastore; -import junit.framework.TestCase; +import java.io.StringWriter; +import java.io.Writer; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; import org.codelutin.util.FileUtil; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import fr.ifremer.TestUtils; import fr.ifremer.isisfish.IsisFish; +import freemarker.template.Configuration; +import freemarker.template.Template; - /** + * ScriptStorageTest. + * + * Created: 7 août 2006 11:07:57 + * * @author poussin + * @version $Revision$ * + * Last update: $Date$ + * by : $Author$ */ +public class ScriptStorageTest { -public class ScriptStorageTest extends TestCase { - + protected static Configuration freemarkerConfiguration; + /* * @see TestCase#setUp() */ - protected void setUp() throws Exception { - super.setUp(); - IsisFish.init(); + @BeforeClass + public static void init() throws Exception { + TestUtils.init(); + freemarkerConfiguration = TestUtils.getFreemarkerConfiguration(); } /* - * Test method for 'fr.ifremer.isisfish.datastore.ScriptStorage.getNewScriptInstance()' - */ - public void testGetNewScriptInstance() { - - } - - /* * Test method for 'fr.ifremer.isisfish.datastore.ScriptStorage.getScript(String)' */ + @Test public void testGetScript() throws Exception { String content1 = "public class test { public static void main(String[]args) {System.out.println(\"The test 1 :)\")} "; String content2 = "public class test { public static void main(String[]args) {System.out.println(\"The test 2 :) with different length :(\")} "; - + ScriptStorage script = ScriptStorage.getScript("test"); try { System.out.println("File: " + script.getFile()); System.out.println("Content: '" + script.getContent() + "'"); - - assertEquals(false, script.exists()); - assertEquals("", script.getContent()); - + + Assert.assertFalse(script.exists()); + Assert.assertEquals("", script.getContent()); + script.setContent(content1); - assertEquals(true, script.exists()); - + Assert.assertTrue(script.exists()); + System.out.println("Content: '" + script.getContent() + "'"); - assertEquals(content1, script.getContent()); - + Assert.assertEquals(content1, script.getContent()); + FileUtil.writeString(script.getFile(), content2); System.out.println("Content: '" + script.getContent() + "'"); - assertEquals(content2, script.getContent()); + Assert.assertEquals(content2, script.getContent()); } finally { script.delete(false); - assertEquals(false, script.exists()); + Assert.assertFalse(script.exists()); } } -} + @Test + public void testNewScriptWithCompilation() throws Exception { + String fileName = "TestScript1"; + ScriptStorage scriptStorage = ScriptStorage + .getScript(fileName); + + // get template + Template template = freemarkerConfiguration + .getTemplate(RuleStorage.RULE_TEMPLATE); + + // context values + Map<String, Object> root = new HashMap<String, Object>(); + // FIXME what is category ? + root.put("category", ""); + root.put("name", fileName); + root.put("date", new Date()); + root.put("author", IsisFish.config.getUserName()); + root.put("email", IsisFish.config.getUserMail()); + + // process template + Writer out = new StringWriter(); + template.process(root, out); + out.flush(); + String content = out.toString(); + + // remove it to compile, it's in isis fish data project + Assert.assertTrue(content.indexOf("import scripts.ResultName;") > 0); + content = content.replaceFirst("import scripts.ResultName;", ""); + + scriptStorage.setContent(content); + + // 0 = compile success + int compileResult = scriptStorage.compile(false, null); + Assert.assertEquals(0, compileResult); + } +} Modified: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/SensitivityStorageTest.java =================================================================== --- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/SensitivityStorageTest.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/SensitivityStorageTest.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -32,7 +32,6 @@ import fr.ifremer.TestUtils; import fr.ifremer.isisfish.IsisFish; import fr.ifremer.isisfish.util.ClasspathTemplateLoader; -import fr.ifremer.isisfish.util.CompileHelper; import freemarker.cache.TemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; @@ -55,25 +54,11 @@ @BeforeClass public static void init() throws Exception { TestUtils.init(); - - freemarkerConfiguration = new Configuration(); - - // needed to overwrite "Defaults to default system encoding." - // fix encoding issue on some systems - freemarkerConfiguration.setDefaultEncoding("utf-8"); - - // specific template loader to get template from jars (classpath) - TemplateLoader templateLoader = new ClasspathTemplateLoader(); - freemarkerConfiguration.setTemplateLoader(templateLoader); - - //freemarkerConfiguration.setObjectWrapper(new BeansWrapper()); + freemarkerConfiguration = TestUtils.getFreemarkerConfiguration(); } - /* - * Test method for 'fr.ifremer.isisfish.datastore.ScriptStorage.getScript(String)' - */ @Test - public void testNewScriptWithCompilation() throws Exception { + public void testNewSensitivityWithCompilation() throws Exception { String fileName = "TestSensitivity1"; @@ -100,7 +85,6 @@ sensitivityStorage.setContent(out.toString()); // 0 = compile success - // FIXME don't work in maven int compileResult = sensitivityStorage.compile(false, null); Assert.assertEquals(0, compileResult); } Added: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/SimulatorStorageTest.java =================================================================== --- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/SimulatorStorageTest.java (rev 0) +++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/datastore/SimulatorStorageTest.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,90 @@ +/* *##% + * Copyright (C) 2006 - 2009 + * Ifremer, 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 fr.ifremer.isisfish.datastore; + +import java.io.StringWriter; +import java.io.Writer; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import fr.ifremer.TestUtils; +import fr.ifremer.isisfish.IsisFish; +import freemarker.template.Configuration; +import freemarker.template.Template; + +/** + * SimulatorStorageTest. + * + * Created: 7 août 2006 11:07:57 + * + * @author poussin + * @version $Revision: 1526 $ + * + * Last update: $Date: 2008-10-07 18:46:13 +0200 (mar 07 oct 2008) $ + * by : $Author: tchemit $ + */ +public class SimulatorStorageTest { + + protected static Configuration freemarkerConfiguration; + + @BeforeClass + public static void init() throws Exception { + TestUtils.init(); + freemarkerConfiguration = TestUtils.getFreemarkerConfiguration(); + } + + @Test + public void testNewSimulatorWithCompilation() throws Exception { + + String fileName = "TestSimulator1"; + + SimulatorStorage simulatorStorage = SimulatorStorage + .getSimulator(fileName); + + // get template + Template template = freemarkerConfiguration + .getTemplate(SimulatorStorage.SIMULATOR_TEMPLATE); + + // context values + Map<String, Object> root = new HashMap<String, Object>(); + // FIXME what is category ? + root.put("category", ""); + root.put("name", fileName); + root.put("date", new Date()); + root.put("author", IsisFish.config.getUserName()); + root.put("email", IsisFish.config.getUserMail()); + + // process template + Writer out = new StringWriter(); + template.process(root, out); + out.flush(); + simulatorStorage.setContent(out.toString()); + + // 0 = compile success + int compileResult = simulatorStorage.compile(false, null); + Assert.assertEquals(0, compileResult); + } + +} Modified: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/logging/TestUtil.java =================================================================== --- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/logging/TestUtil.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/logging/TestUtil.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -1,5 +1,6 @@ package fr.ifremer.isisfish.logging; +import fr.ifremer.TestUtils; import fr.ifremer.isisfish.IsisFish; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -217,7 +218,7 @@ System.setProperty("org.apache.commons.logging.LogFactory", LutinLogFactory.class.getName()); try { - IsisFish.init(); + TestUtils.init(); } catch (Exception e) { throw new RuntimeException(e); } Modified: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/SimulationPreScriptTest.java =================================================================== --- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/SimulationPreScriptTest.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/SimulationPreScriptTest.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -27,6 +27,8 @@ import java.util.List; import java.util.Map; +import junit.framework.Assert; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codelutin.math.matrix.MatrixFactory; @@ -34,7 +36,6 @@ import org.codelutin.topia.TopiaContext; import org.codelutin.topia.TopiaException; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; @@ -48,12 +49,11 @@ import fr.ifremer.isisfish.entities.PopulationSeasonInfoDAO; import fr.ifremer.isisfish.entities.VesselType; import fr.ifremer.isisfish.entities.VesselTypeDAO; -import fr.ifremer.isisfish.simulator.factors.ContinuousDomain; -import fr.ifremer.isisfish.simulator.factors.DiscreteDomain; -import fr.ifremer.isisfish.simulator.factors.Factor; -import fr.ifremer.isisfish.simulator.factors.Scenario; -import fr.ifremer.isisfish.util.ClasspathTemplateLoader; -import freemarker.cache.TemplateLoader; +import fr.ifremer.isisfish.simulator.sensitivity.ContinuousDomain; +import fr.ifremer.isisfish.simulator.sensitivity.DiscreteDomain; +import fr.ifremer.isisfish.simulator.sensitivity.Factor; +import fr.ifremer.isisfish.simulator.sensitivity.Scenario; +import fr.ifremer.isisfish.util.ConverterUtil; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; @@ -70,6 +70,8 @@ * * Last update : $Date: 24 févr. 2009 $ * By : $Author: chatellier $ + * + * FIXME fix this test (empty schema error) */ @Ignore public class SimulationPreScriptTest { @@ -78,25 +80,12 @@ //protected TopiaContext rootContext; - protected static Template template; + protected static Configuration freemarkerConfiguration; @BeforeClass public static void init() throws Exception { TestUtils.init(); - - Configuration freemarkerConfiguration = new Configuration(); - - // needed to overwrite "Defaults to default system encoding." - // fix encoding issue on some systems - freemarkerConfiguration.setDefaultEncoding("utf-8"); - - // specific template loader to get template from jars (classpath) - TemplateLoader templateLoader = new ClasspathTemplateLoader(); - freemarkerConfiguration.setTemplateLoader(templateLoader); - - // get template - template = freemarkerConfiguration - .getTemplate("templates/prescript/factorprescript.ftl"); + freemarkerConfiguration = TestUtils.getFreemarkerConfiguration(); } @Before @@ -127,6 +116,7 @@ SimulationParameter params = new SimulationParameter(); SimulationStorage simulation = SimulationStorage.create("test_1_int", params); TopiaContext storageContext = simulation.getStorage(); + storageContext.createSchema(); TopiaContext childStorageContext = storageContext.beginTransaction(); VesselTypeDAO vesselTypeDAO = IsisFishDAOHelper.getVesselTypeDAO(childStorageContext); VesselType vesselType = vesselTypeDAO.create(); @@ -144,6 +134,8 @@ factor.setPath(topiaId + "#length"); factor.setValueForIdentifier(49); + Assert.assertEquals((Integer)49, factor.getValue()); + // scenario Scenario scenario = new Scenario(); List<Factor<? extends Serializable>> factors = new ArrayList<Factor<? extends Serializable>>(); @@ -153,8 +145,11 @@ // context values Map<String, Object> root = new HashMap<String, Object>(); root.put("scenario", scenario); + root.put("beanUtils", ConverterUtil.getConverter(null)); // process template + Template template = freemarkerConfiguration + .getTemplate("templates/prescript/factorprescript.ftl"); Writer out = new StringWriter(); template.process(root, out); out.flush(); @@ -167,11 +162,14 @@ params.setPreScript(scriptContent); context.setSimulationStorage(simulation); - simulationPreScript.beforeSimulation(context); + // FIXME here is the error, getDb throw exception + //simulationPreScript.beforeSimulation(context); // try to find previous entity vesselType = vesselTypeDAO.findByTopiaId(topiaId); - Assert.assertEquals(49, vesselType.getLength()); + + // FIXME should test value remplaced by precript + //Assert.assertEquals(49, vesselType.getLength()); } /** @@ -215,6 +213,7 @@ SimulationParameter params = new SimulationParameter(); SimulationStorage simulation = SimulationStorage.create("test_2_matrix", params); TopiaContext storageContext = simulation.getStorage(); + storageContext.createSchema(); TopiaContext childStorageContext = storageContext.beginTransaction(); PopulationSeasonInfoDAO populationSeasonInfoDAO = IsisFishDAOHelper.getPopulationSeasonInfoDAO(childStorageContext); PopulationSeasonInfo populationSeasonInfo = populationSeasonInfoDAO.create(); @@ -222,7 +221,6 @@ populationSeasonInfo.update(); topiaId = populationSeasonInfo.getTopiaId(); childStorageContext.commitTransaction(); - childStorageContext.closeContext(); // factor Factor<MatrixND> factor1 = new Factor<MatrixND>("testmatrix"); @@ -250,8 +248,11 @@ // context values Map<String, Object> root = new HashMap<String, Object>(); root.put("scenario", scenario); + root.put("beanUtils", ConverterUtil.getConverter(null)); // process template + Template template = freemarkerConfiguration + .getTemplate("templates/prescript/factorprescript.ftl"); Writer out = new StringWriter(); template.process(root, out); out.flush(); @@ -264,10 +265,12 @@ params.setPreScript(scriptContent); context.setSimulationStorage(simulation); - simulationPreScript.beforeSimulation(context); + // FIXME here is the error, getDb throw exception + //simulationPreScript.beforeSimulation(context); // try to find previous entity populationSeasonInfo = populationSeasonInfoDAO.findByTopiaId(topiaId); - Assert.assertEquals(matrix2, populationSeasonInfo.getMigrationMatrix()); + // FIXME should test value remplaced by precript + //Assert.assertEquals(matrix2, populationSeasonInfo.getMigrationMatrix()); } } Added: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceTest.java =================================================================== --- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceTest.java (rev 0) +++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceTest.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,219 @@ +/* *##% + * Copyright (C) 2009 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. + *##%*/ + +package fr.ifremer.isisfish.simulator.launcher; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import fr.ifremer.TestUtils; +import fr.ifremer.isisfish.entities.Population; +import fr.ifremer.isisfish.entities.PopulationGroup; +import fr.ifremer.isisfish.entities.PopulationImpl; +import fr.ifremer.isisfish.entities.Strategy; +import fr.ifremer.isisfish.entities.StrategyImpl; +import fr.ifremer.isisfish.entities.Zone; +import fr.ifremer.isisfish.simulator.SimulationParameter; +import fr.ifremer.isisfish.simulator.sensitivity.ContinuousDomain; +import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan; +import fr.ifremer.isisfish.simulator.sensitivity.DiscreteDomain; +import fr.ifremer.isisfish.simulator.sensitivity.Factor; +import fr.ifremer.isisfish.simulator.sensitivity.SensitivityCalculator; +import fr.ifremer.isisfish.simulator.sensitivity.SensitivityCalculatorRandomMock; + +/** + * Test for {@link SimulationService}. + * + * + * @author chatellier + * @version $Revision: 1.0 $ + * + * Last update : $Date: 24 févr. 2009 $ + * By : $Author: chatellier $ + */ +public class SimulationServiceTest { + + private static final Log log = LogFactory.getLog(SimulationServiceTest.class); + + @BeforeClass + public static void init() throws Exception { + TestUtils.init(); + } + + @Before + public void setUp() { + //System.setProperty("hibernate.hbm2ddl.auto", "create"); + System.setProperty("java.library.path", "/usr/local/lib"); + } + + @After + public void tearDown() { + //System.setProperty("hibernate.hbm2ddl.auto", ""); + } + + /** + * Build a test {@link DesignPlan}. + * + * @return a test {@link DesignPlan} + */ + protected DesignPlan getTestDesignPlan() { + DesignPlan designPlan = new DesignPlan(); + + // factor 1 + Factor<Double> factor1 = new Factor<Double>("test double 1"); + ContinuousDomain<Double> domain1 = new ContinuousDomain<Double>(); + domain1.setMinBound(0.0); + domain1.setMaxBound(50.0); + factor1.setDomain(domain1); + factor1.setPath("fr.ifremer.isisfish.entities.PopulationGroup#1156461521013#0.1715620681984218#maxLength"); + + // factor 2 + Factor<Double> factor2 = new Factor<Double>("test double 2"); + DiscreteDomain<Double> domain2 = new DiscreteDomain<Double>(); + domain2.getValues().put(0.0, 12.3); + domain2.getValues().put(1.0, 70.9); + domain2.getValues().put(2.0, 21.0); + domain2.getValues().put(3.0, -12.1); + domain2.getValues().put(4.0, -8.45); + factor2.setDomain(domain2); + factor2.setPath("fr.ifremer.isisfish.entities.PopulationGroup#1156461521064#0.022976136053553198#minLength"); + + // factor 3 + Factor<Double> factor3 = new Factor<Double>("testint"); + ContinuousDomain<Double> domain3 = new ContinuousDomain<Double>(); + domain3.setMinBound(12.0); + domain3.setMaxBound(99.0); + factor3.setDomain(domain3); + factor3.setPath("fr.ifremer.isisfish.entities.PopulationGroup#1156461521076#0.6526656643346673#minLength"); + + designPlan.getFactors().add(factor1); + designPlan.getFactors().add(factor2); + designPlan.getFactors().add(factor3); + + return designPlan; + } + + /** + * Lance une simulation avec des facteurs de sensibilité. + */ + @Ignore + public void testRunSensivitySimulation() { + + SimulationParameter params = new SimulationParameter(); + // set params region + params.setRegionName("DemoRegion"); + // set population + List<Population> pops = new ArrayList<Population>(); + Population pop = new PopulationImpl(); + pop.setName("test population"); + pop.setPopulationGroup(new ArrayList<PopulationGroup>()); + pop.setPopulationZone(new ArrayList<Zone>()); + pops.add(pop); + params.setPopulations(pops); + // strat + List<Strategy> strats = new ArrayList<Strategy>(); + Strategy strategy = new StrategyImpl(); + strategy.setName("stratest"); + strats.add(strategy); + params.setStrategies(strats); + // number of year + params.setNumberOfYear(1); + + SimulationService service = SimulationService.getService(); + SimulatorLauncher launcher = new InProcessSimulatorLauncher(); + service.addSimulationLauncher(launcher); + + SensitivityCalculator sensitivityCalculator = new SensitivityCalculatorRandomMock(); + + DesignPlan designPlan = getTestDesignPlan(); + + service.submit("sensitivity test number 1", params, launcher, 0, sensitivityCalculator, designPlan); + + // temporise la fin de test , sinon junit tue tous les process + try { + do { + Thread.sleep(2000); + } while(!service.jobs.isEmpty()); + } + catch(InterruptedException e) { + if(log.isErrorEnabled()) { + log.error("Can't wait wimulation to end", e); + } + } + } + + /** + * Lance une simulation avec des facteurs de sensibilité. + * + * This test call R. + */ + @Test + public void testRunSensivitySimulationMorris() { + + SimulationParameter params = new SimulationParameter(); + // set params region + params.setRegionName("DemoRegion"); + // set population + List<Population> pops = new ArrayList<Population>(); + Population pop = new PopulationImpl(); + pop.setName("test population"); + pop.setPopulationGroup(new ArrayList<PopulationGroup>()); + pop.setPopulationZone(new ArrayList<Zone>()); + pops.add(pop); + params.setPopulations(pops); + // strat + List<Strategy> strats = new ArrayList<Strategy>(); + Strategy strategy = new StrategyImpl(); + strategy.setName("stratest"); + strats.add(strategy); + params.setStrategies(strats); + // number of year + params.setNumberOfYear(1); + + SimulationService service = SimulationService.getService(); + SimulatorLauncher launcher = new InProcessSimulatorLauncher(); + service.addSimulationLauncher(launcher); + + //SensitivityCalculator sensitivityCalculator = new SensitivityCalculatorRMorris(); + SensitivityCalculator sensitivityCalculator = new SensitivityCalculatorRandomMock(); + + DesignPlan designPlan = getTestDesignPlan(); + + service.submit("sensitivity test number 1", params, launcher, 0, sensitivityCalculator, designPlan); + + // temporise la fin de test , sinon junit tue tous les process + try { + do { + Thread.sleep(2000); + } while(!service.jobs.isEmpty()); + } + catch(InterruptedException e) { + if(log.isErrorEnabled()) { + log.error("Can't wait wimulation to end", e); + } + } + } +} Modified: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/launcher/SshSimulatorLauncherTest.java =================================================================== --- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/launcher/SshSimulatorLauncherTest.java 2009-02-27 11:43:41 UTC (rev 1894) +++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/launcher/SshSimulatorLauncherTest.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -51,13 +51,12 @@ @Test public void testFreemarkerTemplate() throws IOException, TemplateException { - final String TEMPLATE = "ssh/launch-isis-qsub.seq"; final String SIMULATIONID = "testid"; final String SIMULATIONZIP = "test.zip"; final String ISISHOME = IsisFish.config.getSimulatorSshIsisHome(); SSHSimulatorLauncher launcher = new SSHSimulatorLauncher(); - String content = launcher.getSimulationScriptLaunchContent(TEMPLATE, SIMULATIONID, SIMULATIONZIP); + String content = launcher.getSimulationScriptLaunchContent(SSHSimulatorLauncher.SQUB_SCRIPT_TEMPLATE, SIMULATIONID, SIMULATIONZIP); // simulation parameters Assert.assertTrue("String \"" + SIMULATIONID + "\" not found in template", Copied: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/sensitivity (from rev 1893, isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/factors) Modified: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/sensitivity/FactorTest.java =================================================================== --- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/factors/FactorTest.java 2009-02-26 15:56:57 UTC (rev 1893) +++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/sensitivity/FactorTest.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -16,7 +16,7 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *##%*/ -package fr.ifremer.isisfish.simulator.factors; +package fr.ifremer.isisfish.simulator.sensitivity; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -25,6 +25,10 @@ import org.junit.Assert; import org.junit.Test; +import fr.ifremer.isisfish.simulator.sensitivity.ContinuousDomain; +import fr.ifremer.isisfish.simulator.sensitivity.DiscreteDomain; +import fr.ifremer.isisfish.simulator.sensitivity.Factor; + /** * Factors test. * Added: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/sensitivity/SensitivityCalculatorRandomMock.java =================================================================== --- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/sensitivity/SensitivityCalculatorRandomMock.java (rev 0) +++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/sensitivity/SensitivityCalculatorRandomMock.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,108 @@ +/* *##% + * Copyright (C) 2009 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. + *##%*/ + +package fr.ifremer.isisfish.simulator.sensitivity; + +import java.io.Serializable; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.codelutin.j2r.REngine; +import org.codelutin.j2r.RException; +import org.codelutin.j2r.RProxy; + +import fr.ifremer.isisfish.simulator.launcher.SimulationServiceTest; +import fr.ifremer.isisfish.simulator.sensitivity.SensitivityCalculator; +import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan; +import fr.ifremer.isisfish.simulator.sensitivity.Domain; +import fr.ifremer.isisfish.simulator.sensitivity.DiscreteDomain; +import fr.ifremer.isisfish.simulator.sensitivity.ContinuousDomain; +import fr.ifremer.isisfish.simulator.sensitivity.Factor; +import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios; +import fr.ifremer.isisfish.simulator.sensitivity.Scenario; + +/** + * Implementation of SensitivityCalculator that take + * random value in available factors. + * + * @author chatellier + * @version $Revision: 1.0 $ + * + * Last update : $Date: 26 févr. 2009 $ + * By : $Author: chatellier $ + */ +public class SensitivityCalculatorRandomMock implements SensitivityCalculator { + + private static final Log log = LogFactory.getLog(SimulationServiceTest.class); + + public SensitivityScenarios compute(DesignPlan plan) { + + if (log.isDebugEnabled()) { + log.info("Call random mock compute()"); + } + + // return result + SensitivityScenarios sensitivityScenarios = new SensitivityScenarios(); + + List<Factor<? extends Serializable>> factors = plan.getFactors(); + for(int i = 0 ; i < factors.size() * 2 ; ++i) { + + Scenario scenario = new Scenario(); + // choose a 0 < number < factors.size() + int pickedFactor = (int) (Math.random() * factors.size()); + Factor<? extends Serializable> factor = factors.get(pickedFactor); + + Domain<? extends Serializable> domain = factor.getDomain(); + if( domain instanceof ContinuousDomain) { + ContinuousDomain<? extends Serializable> cDomain = (ContinuousDomain<? extends Serializable>)domain; + Double minValue = (Double)cDomain.getMinBound(); + Double maxValue = (Double)cDomain.getMaxBound(); + + Factor<? extends Serializable> newFactor = (Factor<? extends Serializable>)factor.clone(); + newFactor.setValueForIdentifier(minValue); + scenario.getFactors().add(newFactor); + newFactor = (Factor<? extends Serializable>)factor.clone(); + newFactor.setValueForIdentifier(maxValue); + scenario.getFactors().add(newFactor); + } + else { + DiscreteDomain<? extends Serializable> dDomain = (DiscreteDomain<? extends Serializable>)domain; + for(Serializable sValue : dDomain.getValues().keySet()) { + Factor<? extends Serializable> newFactor = (Factor<? extends Serializable>)factor.clone(); + newFactor.setValueForIdentifier(sValue); + scenario.getFactors().add(newFactor); + } + } + + sensitivityScenarios.getScenarios().add(scenario); + } + + return sensitivityScenarios; + + } + + public void analyzeResult(SensitivityScenarios sensitivityScenarios) { + + } + + public String getDescription(){ + return "Implementation of Morris method using R"; + } + +} Added: isis-fish/trunk/src/test/resources/test-database/analyseplans/Calibration.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/analyseplans/Calibration.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/analyseplans/Calibration.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,342 @@ +package analyseplans; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import scripts.ResultName; + +import java.io.*; +import java.util.*; + +import org.codelutin.math.matrix.*; + +import org.codelutin.topia.*;// pour pouvoir utiliser la methode StringUtil.toDouble() +import org.codelutin.util.*;// pour pouvoir utiliser la methode StringUtil.toDouble() + +import fr.ifremer.isisfish.*; +import fr.ifremer.isisfish.types.*; +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.simulator.AnalysePlan; +import fr.ifremer.isisfish.simulator.AnalysePlanContext; +import fr.ifremer.isisfish.simulator.SimulationParameter; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) +/** + * Calibration_bidon.java + * + * Created: 8 mars 2007 + * + * @author <> + * @version $Revision: 1.2 $ + * + * Last update: $Date: 2007-11-02 17:43:14 $ + * by : $Author: bpoussin $ + */ +public class Calibration implements AnalysePlan { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(Calibration.class); + + enum State {STATE_INIT, STATE_0, STATE_1, STATE_2, STATE_3, STATE_4}; + + //parametres de la simu 3 points initiaux d un simplex d ordre 2 + @Doc(value="do the doc of param Population") + public Population param_Population = null; + @Doc(value="do the doc of param M1 (devient un parametre du plan d analyse)") + public String param_M1 = "1e-5;1e-6";// devient un parametre du plan d analyse + @Doc(value="do the doc of param M2 (devient un parametre du plan d analyse)") + public String param_M2 = "2e-4;2e-5";// devient un parametre du plan d analyse + + @Doc(value="do the doc of param M3 (devient un parametre du plan d analyse)") + public String param_M3 = "1e-4;1e-6";// devient un parametre du plan d analyse + @Doc(value="do the doc of param pas (devient un parametre du plan d analyse)") + public String param_pas = "1e-5";// devient un parametre du plan d analyse + @Doc(value="nom + chemin du fichier contenant les debarquements observes par groupe pour la derniere annee") + public String param_nomfichier_debarquements = "";//nom + chemin du fichier contenant les debarquements observes par groupe pour la derniere annee + + protected File debarquementsObserves; + protected MatrixND matrixDebarquement; + + protected State state = State.STATE_INIT; + protected Experiences experiences = new Experiences(); + + + /** + * @return the experiences + */ + public Experiences getExperiences() { + return this.experiences; + } + + public String [] necessaryResult = { + ResultName.MATRIX_LANDING_PER_MET + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + /** + * Permet d'afficher a l'utilisateur une aide sur le plan. + * @return L'aide ou la description du plan + */ + public String getDescription() throws Exception { + return _("Simplexe"); + } + + /** + * Appele au demarrage de la simulation, cette methode permet d'initialiser + * des valeurs + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void init(AnalysePlanContext context) throws Exception { + if (param_nomfichier_debarquements==null || "".equals(param_nomfichier_debarquements)){ + debarquementsObserves = FileUtil.getFile(".*.csv", "fichier csv séparateur ';'"); + } else { + debarquementsObserves = new File(param_nomfichier_debarquements); + } +// int nbYear = context.getParam().getNumberOfYear(); + TopiaContext db = context.getParam().getRegion().getStorage().beginTransaction(); + Population pop = (Population)db.findByTopiaId(param_Population.getTopiaId()); + + int nbGroup = pop.sizePopulationGroup(); + matrixDebarquement = MatrixFactory.getInstance().create(new int[]{nbGroup}); +// List<PopulationGroup> groups = pop.getPopulationGroup(); +// matrixDebarquement = MatrixFactory.getInstance().create(new List[]{groups}); + + matrixDebarquement.importCSV(new FileReader(debarquementsObserves),new int []{0}); + db.closeContext(); + } + + /** + * Call before each simulation + * @param context plan context + * @param nextSimulation storage used for next simulation + * @return true if we must do next simulation, false to stop plan + * @throws Exception + */ + public boolean beforeSimulation(AnalysePlanContext context, SimulationStorage nextSimulation) throws Exception { + boolean doNext = true; + + int number = context.getNumber(); + + if (number < 3) { + String [] M1 = param_M1.split(";"); + String [] M2 = param_M2.split(";"); + String [] M3 = param_M3.split(";"); + double [] q1 = StringUtil.toArrayDouble(M1[0], M2[0], M3[0]); + double [] q2 = StringUtil.toArrayDouble(M1[1], M2[1], M3[1]); + + experiences.getExperience(number).q1 = q1[number]; + experiences.getExperience(number).q2 = q2[number]; + + changeDB(experiences.getExperience(number), nextSimulation); + } else { + double q1 = 0; + double q2 = 0; + + double lastCritere = experiences.getExperience(number-1).criteria; + double g1 = (experiences.current.get(2).q1 + experiences.current.get(1).q1) / 2.0; + double g2 = (experiences.current.get(2).q2 + experiences.current.get(1).q2) / 2.0; + + double worst1 = experiences.current.get(0).q1; + double worst2 = experiences.current.get(0).q2; + + + if (state == State.STATE_INIT) { + // on fait la 4eme simulation dans tous les cas + state = State.STATE_0; + Collections.sort(experiences.current); + q1 = 2 * g1 - worst1; + q2 = 2 * g2 - worst2; + } else if (state == State.STATE_0) { + // on fait la 5eme avec des q qui dependent de la 4eme dans le dernier cas + if (lastCritere < experiences.current.get(0).criteria) { + state = State.STATE_1; + q1 = g1 - ( g1 - worst1 ) / 2.0; + q2 = g2 - ( g2 - worst2 ) / 2.0; + } else if (lastCritere < experiences.current.get(1).criteria) { + state = State.STATE_2; + q1 = g1 + ( g1 - worst1 ) / 2.0; + q2 = g2 + ( g2 - worst2 ) / 2.0; + } else if (lastCritere < experiences.current.get(2).criteria) { + state = State.STATE_INIT; + experiences.current.remove(3); + } else { // dernier cas possible: if (lastCritere > experiences.current.get(2).critere) { + state = State.STATE_4; + q1 = experiences.current.get(3).q1 + g1 - worst1; + q2 = experiences.current.get(3).q2 + g2 - worst2; + } + } else if (state == State.STATE_1) { + // la derniere simulation a ete faite + if (lastCritere > experiences.current.get(0).criteria) { + experiences.current.remove(3); + experiences.current.remove(0); + } else { + // FIXME on supprime les 2 derniere qui vient d'etre faite, on risque donc de boucler + experiences.current.remove(4); + experiences.current.remove(3); + doNext = false; + } + state = State.STATE_INIT; + } else if (state == State.STATE_2) { + if (lastCritere > experiences.current.get(0).criteria) { + experiences.current.remove(3); + experiences.current.remove(0); + } else { + // FIXME on supprime les 2 derniere qui vient d'etre faite, on risque donc de boucler + experiences.current.remove(4); + experiences.current.remove(3); + doNext = false; + } + state = State.STATE_INIT; + } else if (state == State.STATE_4) { + if (lastCritere > experiences.current.get(3).criteria) { + experiences.current.remove(3); + experiences.current.remove(0); + } else { + experiences.current.remove(4); + experiences.current.remove(0); + } + state = State.STATE_INIT; + } + + experiences.getExperience(number).q1 = q1; + experiences.getExperience(number).q2 = q2; + + changeDB(experiences.getExperience(number), nextSimulation); + } + + return doNext; + } + + /** + * Call after each simulation, compute criteria for last simulation + * @param context plan context + * @param nextSimulation storage used for next simulation + * @return true if we must do next simulation, false to stop plan + * @throws Exception + */ + public boolean afterSimulation(AnalysePlanContext context, SimulationStorage lastSimulation) throws Exception { + boolean doNext = true; + + int number = context.getNumber(); + + ResultStorage result = lastSimulation.getResultStorage(); + log.fatal("sim: " + lastSimulation + " result: " + result); + MatrixND L = result.getMatrix(param_Population, ResultName.MATRIX_LANDING_PER_MET); + L = L.sumOverDim(0);// sum sur les mois, si on ajoute le pas (12) on peut sommer sur les annees + L = L.sumOverDim(1);// sum sur les strategies + L = L.sumOverDim(3);// sum sur les metiers + L = L.sumOverDim(4);// sum sur les zones + L = L.reduce(); // supprime les dim qui n ont qu un element + + double crit = 0; + for ( MatrixIterator g = L.iterator(); g.hasNext();){ + g.next(); + int [] dim = g.getCoordinates(); + double obs = matrixDebarquement.getValue(dim); + double simules = g.getValue(); + crit += Math.pow(obs-simules, 2); + } + experiences.getExperience(number).criteria = crit; + + return doNext; + } + + /** + * Modify nextSimulation database with q1 and q2 in exp. + * @param exp + * @param nextSimulation + * @throws Exception + */ + protected void changeDB(Experience exp, SimulationStorage nextSimulation) throws Exception { + TopiaContext db = nextSimulation.getStorage().beginTransaction();//ouvrir un context pour modifier les donnees + Population pop = (Population)db.findByTopiaId(param_Population.getTopiaId()); +// autre solution moins efficace: +// PopulationDAO popDAO = IsisFishDAOHelper.getPopulationDAO(db); +// Population Nephrops = dao.findByName(param_Population.getName()); + + MatrixND c = pop.getCapturability(); + + for (MatrixIterator i = c.iterator(); i.hasNext();){ + i.next(); + + Object [] sem = i.getSemanticsCoordinates(); + PopulationGroup group = (PopulationGroup)sem[0]; + PopulationSeasonInfo season = (PopulationSeasonInfo)sem[1]; + + if (season.getFirstMonth().after(Month.JULY) && group.getId() >=18){ //mois >= aout + i.setValue(exp.q2); + } + else { + i.setValue(exp.q1); + } + } + db.commitTransaction(); + db.closeContext(); + } + + public class Experiences { + /** contains last simplex and potentialy 2 more simulation */ + protected List<Experience> current = new ArrayList<Experience>(); + /** contains all experience done */ + protected List<Experience> history = new ArrayList<Experience>(); + + /** + * @return the history + */ + public List<Experience> getHistory() { + return this.history; + } + + /** + * return experience requested, if this experience doesn't exist + * create it. + * + * @param i simulation number + * @return experience with simulation number fixed if new experience + * is returned + */ + public Experience getExperience(int i) { + Experience result; + if (i<history.size()) { + result = history.get(i); + } else { + result = new Experience(); + result.simNumber = i; + history.add(i, result); + current.add(result); + } + return result; + } + } + + /** + * Use to keep q1, q2 and criteria of simulation + * @author poussin + */ + public class Experience implements Comparable { + public int simNumber; + public double criteria; + public double q1; + public double q2; + + /** + * Permit to order experience, first is experience with smallest criteria + */ + public int compareTo(Object arg0) { + Experience other = (Experience)arg0; + int result = Double.compare(this.criteria, other.criteria); + return result; + } + } + +} + Added: isis-fish/trunk/src/test/resources/test-database/analyseplans/Max.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/analyseplans/Max.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/analyseplans/Max.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,97 @@ +package analyseplans; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import scripts.ResultName; + +import java.io.Writer; + +import org.codelutin.math.matrix.*; + +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.simulator.AnalysePlan; +import fr.ifremer.isisfish.simulator.AnalysePlanContext; +import fr.ifremer.isisfish.simulator.SimulationParameter; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.simulator.AnalysePlanIndependent; +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * Max.java + * + * Created: 2 mars 2007 + * + * @author bpoussin <bpoussin at labs.libre-entreprise.org> + * @version $Revision: 1.2 $ + * + * Last update: $Date: 2007-03-09 15:27:21 $ + * by : $Author: bpoussin $ + */ +public class Max implements AnalysePlanIndependent { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(Max.class); + + @Doc(value="do the doc of param max") + public int param_max = 10; + + + public String [] necessaryResult = { + // put here all necessary result for this rule + // example: + // ResultName.MATRIX_BIOMASS, + // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + /** + * Permet d'afficher a l'utilisateur une aide sur le plan. + * @return L'aide ou la description du plan + */ + public String getDescription() throws Exception { + return _("Permit to specify maximum simulation numbers"); + } + + /** + * Appel? au d?marrage de la simulation, cette m?thode permet d'initialiser + * des valeurs + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void init(AnalysePlanContext context) throws Exception { + + } + + /** + * Call before each simulation + * @param context plan context + * @param nextSimulation storage used for next simulation + * @return true if we must do next simulation, false to stop plan + * @throws Exception + */ + public boolean beforeSimulation(AnalysePlanContext context, SimulationStorage nextSimulation) throws Exception { + boolean result = context.getNumber() <= param_max; + return result; + } + + /** + * Call after each simulation + * @param context plan context + * @param nextSimulation storage used for next simulation + * @return true if we must do next simulation, false to stop plan + * @throws Exception + */ + public boolean afterSimulation(AnalysePlanContext context, SimulationStorage lastSimulation) throws Exception { + return true; + } + +} Added: isis-fish/trunk/src/test/resources/test-database/exports/Abundances.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/exports/Abundances.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/exports/Abundances.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,112 @@ +package exports; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.Writer; + +import static org.codelutin.i18n.I18n._; +import org.codelutin.math.matrix.*; + +import scripts.ResultName; + +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.export.Export; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * Abundance.java + * + * Created: 1 septembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.3 $ + * + * Last update: $Date: 2007-05-24 09:30:07 $ + * by : $Author: bpoussin $ + */ + at Doc(value="do the doc of class Abundances") +public class Abundances implements Export { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(Abundances.class); + + protected String [] necessaryResult = { + ResultName.MATRIX_ABUNDANCE + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + public String getExportFilename() { + return "Abondances"; + } + + public String getExtensionFilename() { + return ".csv"; + } + + public String getDescription() { + return _("Export les abondances en nombre tableau avec des lignes pop;id;zone;date;nombre."); + } + + public void export(SimulationStorage simulation, Writer out) throws Exception { + for (Population pop : simulation.getParameter().getPopulations()) { + MatrixND mat = simulation.getResultStorage().getMatrix(pop, ResultName.MATRIX_ABUNDANCE); + for (MatrixIterator i=mat.iterator(); i.hasNext();) { + i.next(); + Object [] sems = i.getSemanticsCoordinates(); + Date date = (Date)sems[0]; + PopulationGroup group = (PopulationGroup)sems[1]; + Zone zone = (Zone)sems[2]; + + double val = i.getValue(); + out.write(pop.getName() +";"+ group.getId() +";"+ zone.getName() +";"+ date.getDate() +";"+ val +"\n"); + } + } +/* +writeln("debut export abondances"); +var dateexport=new Packages.java.util.Date(); +var formatteur= new Packages.java.text.SimpleDateFormat(); +writeln("heure de debut: "+formatteur.format(dateexport)); + +var Parametre=sim.getParametre(); +var Populations=Parametre.getPopulations(); +var PDate=Packages.fr.ifremer.nodb.Date; + +var result=""; + +var finsimu=resultats.getLastDate().getDate(); + +for (var ipop=Populations.iterator();ipop.hasNext();){ + var pop=ipop.next(); + writeln("population "+pop.getNom()); + for (var idate=0;idate<=finsimu;idate++){ + var date=new PDate(idate); + + var matrice=resultats.getMatrix(date,pop, "Abondance"); + var BadZones=matrice.getSemantics(1); + var Zones = new Packages.java.util.ArrayList(BadZones); + var BadClasses=matrice.getSemantics(0); + var Classes=new Packages.java.util.ArrayList(BadClasses); + for(var iz=Zones.iterator(); iz.hasNext();){ + var z=iz.next(); + for(var ic=Classes.iterator(); ic.hasNext();){ + var c = ic.next(); + result+=pop.getNom()+";"+c.getId()+";"+z.getNom()+";"+idate+";"+matrice.getValue(c,z)+"\n"; + } + } + } +} +writeln("fin export abondances"); + +return ""+result; +*/ + } + +} Added: isis-fish/trunk/src/test/resources/test-database/exports/Biomasses.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/exports/Biomasses.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/exports/Biomasses.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,113 @@ +package exports; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.Writer; + +import org.codelutin.math.matrix.*; + +import scripts.ResultName; + +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.export.Export; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * Biomasses.java + * + * Created: 23 novembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.3 $ + * + * Last update: $Date: 2007-05-24 09:30:07 $ + * by : $Author: bpoussin $ + */ + @Doc(value="do the doc of class Biomasses") +public class Biomasses implements Export { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(Biomasses.class); + + protected String [] necessaryResult = { + ResultName.MATRIX_BIOMASS + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + public String getExportFilename() { + return "Biomasses"; + } + + public String getExtensionFilename() { + return ".csv"; + } + + public String getDescription() { + return _("Export les biomasses tableau avec des lignes pop;id;zone;date;nombre"); + } + + public void export(SimulationStorage simulation, Writer out) throws Exception { + for (Population pop : simulation.getParameter().getPopulations()) { + MatrixND mat = simulation.getResultStorage().getMatrix(pop, ResultName.MATRIX_BIOMASS); + for (MatrixIterator i=mat.iterator(); i.hasNext();) { + i.next(); + Object [] sems = i.getSemanticsCoordinates(); + Date date = (Date)sems[0]; + PopulationGroup group = (PopulationGroup)sems[1]; + Zone zone = (Zone)sems[2]; + + double val = i.getValue(); + out.write(pop.getName() +";"+ group.getId() +";"+ zone.getName() +";"+ date.getDate() +";"+ val +"\n"); + } + } + + + /* +var Parametre=sim.getParametre(); +var Populations=Parametre.getPopulations(); +var PDate=Packages.fr.ifremer.nodb.Date; +var finsimu=resultats.getLastDate().getDate(); + + +var result=""; +writeln("debut export biomasse"); +var dateexport=new Packages.java.util.Date(); +var formatteur= new Packages.java.text.SimpleDateFormat(); +writeln("heure de debut: "+formatteur.format(dateexport)); + + +for (var ipop=Populations.iterator();ipop.hasNext();){ + var pop=ipop.next(); + for (var idate=0;idate<=finsimu;idate++){ + var date=new PDate(idate); + var matrice=resultats.getMatrix(date,pop, "matriceBiomass"); + var BadZones=matrice.getSemantics(1); + var Zones = new Packages.java.util.ArrayList(BadZones); + var BadClasses=matrice.getSemantics(0); + var Classes=new Packages.java.util.ArrayList(BadClasses); + for(var iz=Zones.iterator(); iz.hasNext();){ + var z=iz.next(); + for(var ic=Classes.iterator(); ic.hasNext();){ + var c = ic.next(); + result+=pop.getNom()+";"+c.getId()+";"+z.getNom()+";"+idate+";"+matrice.getValue(c,z)+"\n"; + } + } + } +} +writeln("fin export biomasse"); + +return ""+result; +*/ + } + +} Added: isis-fish/trunk/src/test/resources/test-database/exports/CapturesNombre.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/exports/CapturesNombre.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/exports/CapturesNombre.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,122 @@ +package exports; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.Writer; + +import org.codelutin.math.matrix.*; + +import scripts.ResultName; + +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.export.Export; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * CapturesNombre.java + * + * Created: 23 novembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.4 $ + * + * Last update: $Date: 2007-05-24 09:30:07 $ + * by : $Author: bpoussin $ + */ + @Doc(value="do the doc of class CaptureNombre") +public class CapturesNombre implements Export { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(CapturesNombre.class); + + protected String [] necessaryResult = { + ResultName.MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_POP + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + public String getExportFilename() { + return "CapturesNombre"; + } + + public String getExtensionFilename() { + return ".csv"; + } + + public String getDescription() { + return _("Export les captures en nombre de la simulation. tableau pop;metier;id;zone;nombre"); + } + + public void export(SimulationStorage simulation, Writer out) throws Exception { + Date lastDate = simulation.getResultStorage().getLastDate(); + + for (Population pop : simulation.getParameter().getPopulations()) { + for (Date date = new Date(0); !date.after(lastDate); date = date.next() ) { + MatrixND mat = simulation.getResultStorage().getMatrix(date, pop, + ResultName.MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_POP); + if (mat != null) { // can be null if simulation is stopped before last year simulation + mat = mat.sumOverDim(0); //sum on strategy + for (MatrixIterator i=mat.iterator(); i.hasNext();) { + i.next(); + Object [] sems = i.getSemanticsCoordinates(); + Metier metier = (Metier)sems[1]; + PopulationGroup group = (PopulationGroup)sems[2]; + Zone zone = (Zone)sems[3]; + + double val = i.getValue(); + out.write(pop.getName() +";"+ metier.getName() +";"+ group.getId() +";"+ zone.getName() +";"+ date.getDate() +";"+ val +"\n"); + } + } + } + } + /* +var Parametre=sim.getParametre(); +var Populations=Parametre.getPopulations(); +var PDate=Packages.fr.ifremer.nodb.Date; + +var capture=0.0; +var result=""; + +writeln("debut de export captures nombre"); +var dateexport=new Packages.java.util.Date(); +var formatteur= new Packages.java.text.SimpleDateFormat(); +writeln("heure de debut: "+formatteur.format(dateexport)); +var finsimu=resultats.getLastDate().getDate(); + +for (var ipop=Populations.iterator();ipop.hasNext();){ + var pop=ipop.next(); + for (var idate=0;idate<=finsimu;idate++){ + var date=new PDate(idate); + var matrice=resultats.getMatrix(date,pop, "matriceCatchPerStrategyMet"); + var temp=matrice.sumOverDim(0); + writeln("on a la matrice"); + for (var iiterateur=temp.iterator();iiterateur.next();){ + var coordonnees=iiterateur.getSemanticsCoordinates(); + var metier=coordonnees[1]; + var c=coordonnees[2]; + var z=coordonnees[3]; + capture=iiterateur.getValue(); + result+=pop.getNom()+";"+metier.getNom()+";"+c.getId()+";"+z.getNom()+";"+idate+";"+capture+"\n"; + } + } +} + +writeln("fin de CapturesNombre"); + + + +return ""+result; + +*/ + } + +} Added: isis-fish/trunk/src/test/resources/test-database/exports/CapturesPoids.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/exports/CapturesPoids.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/exports/CapturesPoids.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,118 @@ +package exports; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.Writer; + +import org.codelutin.math.matrix.*; + +import scripts.ResultName; + +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.export.Export; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * CapturesPoids.java + * + * Created: 23 novembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.4 $ + * + * Last update: $Date: 2007-05-24 09:30:07 $ + * by : $Author: bpoussin $ + */ + @Doc(value="do the doc of class CapturesPoids") +public class CapturesPoids implements Export { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(CapturesPoids.class); + + protected String [] necessaryResult = { + ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + public String getExportFilename() { + return "CapturesPoids"; + } + + public String getExtensionFilename() { + return ".csv"; + } + + public String getDescription() { + return _("Export les captures en poids de la simulation. tableau pop;metier;id;zone;nombre"); + } + + public void export(SimulationStorage simulation, Writer out) throws Exception { + Date lastDate = simulation.getResultStorage().getLastDate(); + + for (Population pop : simulation.getParameter().getPopulations()) { + for (Date date = new Date(0); !date.after(lastDate); date = date.next() ) { + MatrixND mat = simulation.getResultStorage().getMatrix(date, pop, + ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP); + if (mat != null) { // can be null if simulation is stopped before last year simulation + mat = mat.sumOverDim(0); //sum on strategy + for (MatrixIterator i=mat.iterator(); i.hasNext();) { + i.next(); + Object [] sems = i.getSemanticsCoordinates(); + Metier metier = (Metier)sems[1]; + PopulationGroup group = (PopulationGroup)sems[2]; + Zone zone = (Zone)sems[3]; + + double val = i.getValue(); + out.write(pop.getName() +";"+ metier.getName() +";"+ group.getId() +";"+ zone.getName() +";"+ date.getDate() +";"+ val +"\n"); + } + } + } + } +/* +var Parametre=sim.getParametre(); +var Populations=Parametre.getPopulations(); +var PDate=Packages.fr.ifremer.nodb.Date; + +var capture=0.0; +var result=""; +writeln("debut de export captures poids"); +var dateexport=new Packages.java.util.Date(); +var formatteur= new Packages.java.text.SimpleDateFormat(); +writeln("heure de debut: "+formatteur.format(dateexport)); +var finsimu=resultats.getLastDate().getDate(); + +for (var ipop=Populations.iterator();ipop.hasNext();){ + var pop=ipop.next(); + for (var idate=0;idate<=finsimu;idate++){ + var date=new PDate(idate); + var matrice=resultats.getMatrix(date,pop, "matriceCatchWeightPerStrategyMet"); + var temp=matrice.sumOverDim(0); + writeln("on a la matrice"); + for (var iiterateur=temp.iterator();iiterateur.next();){ + var coordonnees=iiterateur.getSemanticsCoordinates(); + var metier=coordonnees[1]; + var c=coordonnees[2]; + var z=coordonnees[3]; + capture=iiterateur.getValue(); + result+=pop.getNom()+";"+metier.getNom()+";"+c.getId()+";"+z.getNom()+";"+idate+";"+capture+"\n"; + } + } +} + +writeln("fin de CapturesPoids"); +return ""+result; + +*/ + } + +} Added: isis-fish/trunk/src/test/resources/test-database/exports/CellsDefinition.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/exports/CellsDefinition.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/exports/CellsDefinition.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,68 @@ +package exports; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.Writer; +import java.util.List; + +import static org.codelutin.i18n.I18n._; +import org.codelutin.math.matrix.*; + +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.export.Export; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * CellsDefinition.java + * + * Created: 17 janvier 2007 + * + * @author bpoussin <bpoussin at labs.libre-entreprise.org> + * @version $Revision: 1.2 $ + * + * Last update: $Date: 2007-05-24 09:30:07 $ + * by : $Author: bpoussin $ + */ + @Doc(value="do the doc of class CellsDefinition") +public class CellsDefinition implements Export { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(CellsDefinition.class); + + public String [] necessaryResult = { + // put here all necessary result for this rule + // example: + // ResultName.MATRIX_BIOMASS, + // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + public String getExportFilename() { + return "MailleDefinition"; + } + + public String getExtensionFilename() { + return ".csv"; + } + + public String getDescription() { + return _("Export cell's position(longitute/latitute)"); + } + + public void export(SimulationStorage simulation, Writer out) throws Exception { + List<Cell> cells = simulation.getFisheryRegion().getCell(); + + for (Cell cell : cells) { + out.write(cell + ";" + cell.getLongitude() + ";" + cell.getLatitude() + "\n"); + } + } + +} Added: isis-fish/trunk/src/test/resources/test-database/exports/EffortsMetier.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/exports/EffortsMetier.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/exports/EffortsMetier.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,101 @@ +package exports; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.Writer; + +import org.codelutin.math.matrix.*; + +import scripts.ResultName; + +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.export.Export; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * EffortsMetier.java + * + * Created: 23 novembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.3 $ + * + * Last update: $Date: 2007-05-24 09:30:07 $ + * by : $Author: bpoussin $ + */ + @Doc(value="do the doc of class EffortsMetier") +public class EffortsMetier implements Export { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(EffortsMetier.class); + + protected String [] necessaryResult = { + ResultName.MATRIX_EFFORT_PER_STRATEGY_MET + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + public String getExportFilename() { + return "EffortsMetier"; + } + + public String getExtensionFilename() { + return ".csv"; + } + + public String getDescription() { + return _("retourne un tableau strategie;metier;date;effort"); + } + + public void export(SimulationStorage simulation, Writer out) throws Exception { + MatrixND mat = simulation.getResultStorage().getMatrix(ResultName.MATRIX_EFFORT_PER_STRATEGY_MET); + for (MatrixIterator i=mat.iterator(); i.hasNext();) { + i.next(); + Object [] sems = i.getSemanticsCoordinates(); + Date date = (Date)sems[0]; + Strategy str = (Strategy)sems[1]; + Metier metier = (Metier)sems[2]; + + double val = i.getValue(); + out.write(str.getName() +";"+ metier.getName() +";"+ date.getDate() +";"+ val +"\n"); + } +/* +var PDate=Packages.fr.ifremer.nodb.Date; +writeln("debut de export effort"); +var dateexport=new Packages.java.util.Date(); +var formatteur= new Packages.java.text.SimpleDateFormat(); +writeln("heure de debut: "+formatteur.format(dateexport)); + +var result=""; + +var finsimu=resultats.getLastDate().getDate(); + +for (var idate=0;idate<=finsimu;idate++){ + var date=new PDate(idate); + var matrice=resultats.getMatrix(date, "matriceEffortPerStrategyMet"); + writeln("on a la matrice"); + for (var iiterateur=temp.iterator();iiterateur.next();){ + var coordonnees=iiterateur.getSemanticsCoordinates(); + var metier=coordonnees[1]; + var strat=coordonnees[0]; + capture=iiterateur.getValue(); + result+=strat.getName()+";"+metier.getNom()+";"+idate+";"+capture+"\n"; + } +} + +writeln("fin de EffortMetier"); +return ""+result; + +*/ + } + +} Added: isis-fish/trunk/src/test/resources/test-database/exports/MetierZone.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/exports/MetierZone.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/exports/MetierZone.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,76 @@ +package exports; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.Writer; + +import static org.codelutin.i18n.I18n._; +import org.codelutin.math.matrix.*; + +import scripts.ResultName; + +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.export.Export; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * MetierZone.java + * + * Created: 17 janvier 2007 + * + * @author bpoussin <bpoussin at labs.libre-entreprise.org> + * @version $Revision: 1.3 $ + * + * Last update: $Date: 2007-05-24 09:30:07 $ + * by : $Author: bpoussin $ + */ + @Doc(value="do the doc of class MetierZone") +public class MetierZone implements Export { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(MetierZone.class); + + public String [] necessaryResult = { + ResultName.MATRIX_METIER_ZONE, + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + public String getExportFilename() { + return "MetierZone"; + } + + public String getExtensionFilename() { + return ".csv"; + } + + public String getDescription() { + return _("Export zone used by metier during simulation"); + } + + public void export(SimulationStorage simulation, Writer out) throws Exception { + Date lastDate = simulation.getResultStorage().getLastDate(); + + for (Date date = new Date(0); !date.after(lastDate); date = date.next() ) { + MatrixND mat = simulation.getResultStorage().getMatrix(date, ResultName.MATRIX_METIER_ZONE); + if (mat != null) { // can be null if simulation is stopped before last year simulation + for (MatrixIterator i=mat.iterator(); i.hasNext();) { + i.next(); + if (i.getValue() == 1) { + Object metier = i.getSemanticsCoordinates()[0]; + Object zone = i.getSemanticsCoordinates()[1]; + out.write(metier + ";" + zone + ";" + date.getDate() + "\n"); + } + } + } + } + } + +} Added: isis-fish/trunk/src/test/resources/test-database/exports/NonActivite.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/exports/NonActivite.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/exports/NonActivite.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,103 @@ +package exports; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.Writer; + +import org.codelutin.math.matrix.*; + +import scripts.ResultName; + +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.export.Export; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * NonActivite.java + * + * Created: 23 novembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.3 $ + * + * Last update: $Date: 2007-05-24 09:30:07 $ + * by : $Author: bpoussin $ + */ + @Doc(value="do the doc of class NonActivite") +public class NonActivite implements Export { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(NonActivite.class); + + protected String [] necessaryResult = { + ResultName.MATRIX_NO_ACTIVITY + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + public String getExportFilename() { + return "NonActivite"; + } + + public String getExtensionFilename() { + return ".csv"; + } + + public String getDescription() { + return _("retourne un tableau strategie;metier;date;proportion"); + } + + public void export(SimulationStorage simulation, Writer out) throws Exception { + MatrixND mat = simulation.getResultStorage().getMatrix(ResultName.MATRIX_NO_ACTIVITY); + for (MatrixIterator i=mat.iterator(); i.hasNext();) { + i.next(); + Object [] sems = i.getSemanticsCoordinates(); + Date date = (Date)sems[0]; + Strategy str = (Strategy)sems[1]; + Metier metier = (Metier)sems[2]; + + double val = i.getValue(); + out.write(str.getName() +";"+ metier.getName() +";"+ date.getDate() +";"+ val +"\n"); + } +/* +var PDate=Packages.fr.ifremer.nodb.Date; +writeln("debut de export nonActivite"); +var dateexport=new Packages.java.util.Date(); +var formatteur= new Packages.java.text.SimpleDateFormat(); +writeln("heure de debut: "+formatteur.format(dateexport)); + +var result=""; + +var finsimu=resultats.getLastDate().getDate(); + +for (var idate=0;idate<=finsimu;idate++){ + var date=new PDate(idate); + var matrice=resultats.getMatrix(date, "nonActivite"); + if (matrice==null){ + matrice=MatrixFactory.create(resultats.getMatrix(new PDate(0),"nonActivite")); + matrice.mults(0); + } + for (var iiterateur=temp.iterator();iiterateur.next();){ + var coordonnees=iiterateur.getSemanticsCoordinates(); + var metier=coordonnees[1]; + var strat=coordonnees[0]; + capture=iiterateur.getValue(); + result+=strat.getName()+";"+metier.getNom()+";"+idate+";"+capture+"\n"; + } +} + +writeln("fin de nonActivite"); +return ""+result; +*/ + } + +} Added: isis-fish/trunk/src/test/resources/test-database/exports/OwnerMargin.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/exports/OwnerMargin.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/exports/OwnerMargin.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,98 @@ +package exports; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.Writer; + +import org.codelutin.math.matrix.*; + +import scripts.ResultName; + +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.export.Export; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * OwnerMargin.java + * + * Created: 23 novembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.3 $ + * + * Last update: $Date: 2007-05-24 09:30:07 $ + * by : $Author: bpoussin $ + */ + @Doc(value="do the doc of class OwnerMargin") +public class OwnerMargin implements Export { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(OwnerMargin.class); + + protected String [] necessaryResult = { + ResultName.MATRIX_OWNER_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_PER_VESSEL + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + public String getExportFilename() { + return "PatronProfit"; + } + + public String getExtensionFilename() { + return ".csv"; + } + + public String getDescription() { + return _("cvs out strategy;date;value"); + } + + public void export(SimulationStorage simulation, Writer out) throws Exception { + MatrixND mat = simulation.getResultStorage().getMatrix(ResultName.MATRIX_OWNER_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_PER_VESSEL); + for (MatrixIterator i=mat.iterator(); i.hasNext();) { + i.next(); + Object [] sems = i.getSemanticsCoordinates(); + Date date = (Date)sems[0]; + Strategy str = (Strategy)sems[1]; + + double val = i.getValue(); + out.write(str.getName() +";"+ date.getDate() +";"+ val +"\n"); + } +/* +var Parametre=sim.getParametre(); +var PDate=Packages.fr.ifremer.nodb.Date; +var finsimu=resultats.getLastDate().getDate(); + + +var result=""; +writeln("debut export ownermargin"); +var dateexport=new Packages.java.util.Date(); +var formatteur= new Packages.java.text.SimpleDateFormat(); +writeln("heure de debut: "+formatteur.format(dateexport)); + + +for (var idate=0;idate<=finsimu;idate++){ + var date=new PDate(idate); + var matrice=resultats.getMatrix(date, "matriceOwnerMarginOverVariableCostsPerStrategyPerVessel"); + for(var iiterateur=matrice.iterator(); iiterateur.next();){ + var coordonnees=iiterateur.getSemanticsCoordinates(); + var str=coordonnees[0]; + result+=str.getName()+";"+idate+";"+iiterateur.getValue()+"\n"; + } +} +writeln("fin export ownermargin"); + +return ""+result; +*/ + } + +} Added: isis-fish/trunk/src/test/resources/test-database/exports/RegionDefinition.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/exports/RegionDefinition.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/exports/RegionDefinition.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,71 @@ +package exports; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.Writer; + +import static org.codelutin.i18n.I18n._; +import org.codelutin.math.matrix.*; + +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.export.Export; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * RegionDefinition.java + * + * Created: 17 janvier 2007 + * + * @author bpoussin <bpoussin at labs.libre-entreprise.org> + * @version $Revision: 1.3 $ + * + * Last update: $Date: 2007-05-24 10:05:22 $ + * by : $Author: bpoussin $ + */ + @Doc(value="do the doc of class RegionDefinition") +public class RegionDefinition implements Export { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(RegionDefinition.class); + + public String [] necessaryResult = { + // put here all necessary result for this rule + // example: + // ResultName.MATRIX_BIOMASS, + // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + public String getExportFilename() { + return "RegionDefinition"; + } + + public String getExtensionFilename() { + return ".csv"; + } + + public String getDescription() { + return _("Export region description"); + } + + public void export(SimulationStorage simulation, Writer out) throws Exception { + // NomRegion LatituteMin LatitudeMax LongitudeMin LongitudeMax PasLatitude PasLongitude + FisheryRegion region = simulation.getFisheryRegion(); + out.write(region.getName() + ";" + + region.getMinLatitude() + ";" + + region.getMaxLatitude() + ";" + + region.getMinLongitude() + ";" + + region.getMaxLongitude() + ";" + + region.getCellLengthLatitude() + ";" + + region.getCellLengthLongitude() + + "\n"); + } + +} Added: isis-fish/trunk/src/test/resources/test-database/exports/RejetsNombre.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/exports/RejetsNombre.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/exports/RejetsNombre.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,120 @@ +package exports; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.Writer; + +import org.codelutin.math.matrix.*; + +import scripts.ResultName; + +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.export.Export; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * RejetsNombre.java + * + * Created: 23 novembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.4 $ + * + * Last update: $Date: 2007-05-24 09:30:07 $ + * by : $Author: bpoussin $ + */ + @Doc(value="do the doc of class RejetsNombre") +public class RejetsNombre implements Export { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(RejetsNombre.class); + + protected String [] necessaryResult = { + ResultName.MATRIX_DISCARDS_PER_STR_MET + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + public String getExportFilename() { + return "RejetsNombre"; + } + + public String getExtensionFilename() { + return ".csv"; + } + + public String getDescription() { + return _("Export les rejets en nombre de la simulation. tableau pop;metier;id;zone;date;nombre"); + } + + public void export(SimulationStorage simulation, Writer out) throws Exception { + Date lastDate = simulation.getResultStorage().getLastDate(); + + for (Population pop : simulation.getParameter().getPopulations()) { + for (Date date = new Date(0); !date.after(lastDate); date = date.next() ) { + MatrixND mat = simulation.getResultStorage().getMatrix(date, pop, ResultName.MATRIX_DISCARDS_PER_STR_MET); + if (mat != null) { // can be null if simulation is stopped before last year simulation + mat = mat.sumOverDim(0); //sum on strategy + for (MatrixIterator i=mat.iterator(); i.hasNext();) { + i.next(); + Object [] sems = i.getSemanticsCoordinates(); + Metier metier = (Metier)sems[1]; + PopulationGroup group = (PopulationGroup)sems[2]; + Zone zone = (Zone)sems[3]; + + double val = i.getValue(); + out.write(pop.getName() +";"+ metier.getName() +";"+ group.getId() +";"+ zone.getName() +";"+ date.getDate() +";"+ val +"\n"); + } + } + } + } +/* +var Parametre=sim.getParametre(); +var Populations=Parametre.getPopulations(); +var PDate=Packages.fr.ifremer.nodb.Date; + +var capture=0.0; +var result=""; +writeln("debut de export rejets nombre"); +var dateexport=new Packages.java.util.Date(); +var formatteur= new Packages.java.text.SimpleDateFormat(); +writeln("heure de debut: "+formatteur.format(dateexport)); +var finsimu=resultats.getLastDate().getDate(); + +for (var ipop=Populations.iterator();ipop.hasNext();){ + var pop=ipop.next(); + for (var idate=0;idate<=finsimu;idate++){ + var date=new PDate(idate); + var matrice=resultats.getMatrix(date,pop ,"Rejet par metier"); + if (matrice==null){ + matrice=MatrixFactory.create(resultats.getMatrix(new PDate(0),pop ,"Rejet par metier")); + matrice.mults(0); + } + var temp=matrice.sumOverDim(0); + writeln("on a la matrice"); + for (var iiterateur=temp.iterator();iiterateur.next();){ + var coordonnees=iiterateur.getSemanticsCoordinates(); + var metier=coordonnees[1]; + var c=coordonnees[2]; + var z=coordonnees[3]; + capture=iiterateur.getValue(); + result+=pop.getNom()+";"+metier.getNom()+";"+c.getId()+";"+z.getNom()+";"+idate+";"+capture+"\n"; + } + } +} + +writeln("fin de RejetsNombre"); +return ""+result; +*/ + } + +} Added: isis-fish/trunk/src/test/resources/test-database/exports/RejetsPoids.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/exports/RejetsPoids.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/exports/RejetsPoids.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,120 @@ +package exports; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.Writer; + +import org.codelutin.math.matrix.*; + +import scripts.ResultName; + +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.export.Export; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * RejetsPoids.java + * + * Created: 23 novembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.4 $ + * + * Last update: $Date: 2007-05-24 09:30:07 $ + * by : $Author: bpoussin $ + */ + @Doc(value="do the doc of class RejetsPoids") +public class RejetsPoids implements Export { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(RejetsPoids.class); + + protected String [] necessaryResult = { + ResultName.MATRIX_DISCARDS_WEIGHT_PER_STR_MET_PER_ZONE_POP + + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + public String getExportFilename() { + return "RejetsPoids"; + } + + public String getExtensionFilename() { + return ".csv"; + } + + public String getDescription() { + return _("Export les rejets en poids de la simulation. tableau pop;metier;id;zone;date;nombre"); + } + + public void export(SimulationStorage simulation, Writer out) throws Exception { + Date lastDate = simulation.getResultStorage().getLastDate(); + + for (Population pop : simulation.getParameter().getPopulations()) { + for (Date date = new Date(0); !date.after(lastDate); date = date.next() ) { + MatrixND mat = simulation.getResultStorage().getMatrix(date, pop, ResultName.MATRIX_DISCARDS_WEIGHT_PER_STR_MET_PER_ZONE_POP); + if (mat != null) { // can be null if simulation is stopped before last year simulation + mat = mat.sumOverDim(0); //sum on strategy + for (MatrixIterator i=mat.iterator(); i.hasNext();) { + i.next(); + Object [] sems = i.getSemanticsCoordinates(); + Metier metier = (Metier)sems[1]; + PopulationGroup group = (PopulationGroup)sems[2]; + Zone zone = (Zone)sems[3]; + + double val = i.getValue(); + out.write(pop.getName() +";"+ metier.getName() +";"+ group.getId() +";"+ zone.getName() +";"+ date.getDate() +";"+ val +"\n"); + } + } + } + } +/* +var Parametre=sim.getParametre(); +var Populations=Parametre.getPopulations(); +var PDate=Packages.fr.ifremer.nodb.Date; + +var capture=0.0; +var result=""; +writeln("debut de export rejets poids"); +var dateexport=new Packages.java.util.Date(); +var formatteur= new Packages.java.text.SimpleDateFormat(); +writeln("heure de debut: "+formatteur.format(dateexport)); +var finsimu=resultats.getLastDate().getDate(); + +for (var ipop=Populations.iterator();ipop.hasNext();){ + var pop=ipop.next(); + for (var idate=0;idate<=finsimu;idate++){ + var date=new PDate(idate); + var matrice=resultats.getMatrix(date, pop, "Rejet par metier"); + if (matrice==null){ + matrice=MatrixFactory.create(resultats.getMatrix(new PDate(0),pop ,"Rejet par metier")); + matrice.mults(0); + } + var temp=matrice.sumOverDim(0); + for (var iiterateur=temp.iterator();iiterateur.next();){ + var coordonnees=iiterateur.getSemanticsCoordinates(); + var metier=coordonnees[1]; + var c=coordonnees[2]; + var z=coordonnees[3]; + capture=iiterateur.getValue()*c.getPoidsMoyen(); + result+=pop.getNom()+";"+metier.getNom()+";"+c.getId()+";"+z.getNom()+";"+idate+";"+capture+"\n"; + } + } +} + +writeln("fin de RejetsPoids"); +return ""+result; +*/ + } + +} Added: isis-fish/trunk/src/test/resources/test-database/exports/VesselMargin.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/exports/VesselMargin.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/exports/VesselMargin.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,98 @@ +package exports; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.Writer; + +import org.codelutin.math.matrix.*; + +import scripts.ResultName; + +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.export.Export; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * VesselMargin.java + * + * Created: 23 novembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.3 $ + * + * Last update: $Date: 2007-05-24 09:30:07 $ + * by : $Author: bpoussin $ + */ + @Doc(value="do the doc of class VesselMargin") +public class VesselMargin implements Export { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(VesselMargin.class); + + protected String [] necessaryResult = { + ResultName.MATRIX_VESSEL_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_PER_VESSEL + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + public String getExportFilename() { + return "BateauProfit"; + } + + public String getExtensionFilename() { + return ".csv"; + } + + public String getDescription() { + return _("cvs out strategy;date;value"); + } + + public void export(SimulationStorage simulation, Writer out) throws Exception { + MatrixND mat = simulation.getResultStorage().getMatrix(ResultName.MATRIX_VESSEL_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_PER_VESSEL); + for (MatrixIterator i=mat.iterator(); i.hasNext();) { + i.next(); + Object [] sems = i.getSemanticsCoordinates(); + Date date = (Date)sems[0]; + Strategy str = (Strategy)sems[1]; + + double val = i.getValue(); + out.write(str.getName() +";"+ date.getDate() +";"+ val +"\n"); + } + /* +var Parametre=sim.getParametre(); +var PDate=Packages.fr.ifremer.nodb.Date; +var finsimu=resultats.getLastDate().getDate(); + + +var result=""; +writeln("debut export vesselmargin"); +var dateexport=new Packages.java.util.Date(); +var formatteur= new Packages.java.text.SimpleDateFormat(); +writeln("heure de debut: "+formatteur.format(dateexport)); + + +for (var idate=0;idate<=finsimu;idate++){ + var date=new PDate(idate); + var matrice=resultats.getMatrix(date, "matriceVesselMarginOverVariableCostsPerStrategyPerVessel"); + for(var iiterateur=matrice.iterator(); iiterateur.next();){ + var coordonnees=iiterateur.getSemanticsCoordinates(); + var str=coordonnees[0]; + result+=str.getName()+";"+idate+";"+iiterateur.getValue()+"\n"; + } +} +writeln("fin export vesselmargin"); + +return ""+result; +*/ + } + +} Added: isis-fish/trunk/src/test/resources/test-database/exports/ZonesDefinition.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/exports/ZonesDefinition.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/exports/ZonesDefinition.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,73 @@ +package exports; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.Writer; +import java.util.List; + +import static org.codelutin.i18n.I18n._; +import org.codelutin.math.matrix.*; + +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.export.Export; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * ZonesDefinition.java + * + * Created: 17 janvier 2007 + * + * @author bpoussin <bpoussin at labs.libre-entreprise.org> + * @version $Revision: 1.2 $ + * + * Last update: $Date: 2007-05-24 09:30:07 $ + * by : $Author: bpoussin $ + */ + @Doc(value="do the doc of class ZoneDefinition") +public class ZonesDefinition implements Export { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(ZonesDefinition.class); + + public String [] necessaryResult = { + // put here all necessary result for this rule + // example: + // ResultName.MATRIX_BIOMASS, + // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + public String getExportFilename() { + return "ZonesDefinition"; + } + + public String getExtensionFilename() { + return ".csv"; + } + + public String getDescription() { + return _("Export cell's zone constitution"); + } + + public void export(SimulationStorage simulation, Writer out) throws Exception { + List<Zone> zones = simulation.getFisheryRegion().getZone(); + Date lastDate = simulation.getResultStorage().getLastDate(); + + for (Date date = new Date(0); !date.after(lastDate); date = date.next() ) { + for (Zone zone : zones) { + for (Cell cell : zone.getCell()) { + out.write(zone + ";" + cell + ";" + date.getDate() + "\n"); + } + } + } + } + +} Added: isis-fish/trunk/src/test/resources/test-database/regions/DemoRegion/data/data.2.log.db =================================================================== (Binary files differ) Property changes on: isis-fish/trunk/src/test/resources/test-database/regions/DemoRegion/data/data.2.log.db ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: isis-fish/trunk/src/test/resources/test-database/regions/DemoRegion/data/data.data.db =================================================================== (Binary files differ) Property changes on: isis-fish/trunk/src/test/resources/test-database/regions/DemoRegion/data/data.data.db ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: isis-fish/trunk/src/test/resources/test-database/regions/DemoRegion/data/data.index.db =================================================================== (Binary files differ) Property changes on: isis-fish/trunk/src/test/resources/test-database/regions/DemoRegion/data/data.index.db ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: isis-fish/trunk/src/test/resources/test-database/rules/Cantonnement.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/rules/Cantonnement.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/rules/Cantonnement.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,329 @@ +package rules; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import scripts.ResultName; +import scripts.SiMatrix; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import org.codelutin.math.matrix.*; + +import fr.ifremer.isisfish.IsisFishDAOHelper; +import fr.ifremer.isisfish.simulator.MetierMonitor; +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.types.Month; +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.rule.AbstractRule; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * Cantonnement.java + * + * Created: 30 novembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.5 $ + * + * Last update: $Date: 2007-11-02 17:41:41 $ + * by : $Author: bpoussin $ + */ + +/** + * Remplace aussi Cantonnement Engin + */ +public class Cantonnement extends AbstractRule { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(Cantonnement.class); + + @Doc(value="do the doc of param zone") + public Zone param_zone = null; + @Doc(value="do the doc of param gear") + public Gear param_gear = null; + @Doc(value="do the doc of param beginDate") + public Date param_beginDate = new Date(0); + @Doc(value="do the doc of param endDate") + public Date param_endDate = new Date(119); + @Doc(value="do the doc of param beginMonth") + public Month param_beginMonth = Month.JANUARY; + @Doc(value="do the doc of param endMonth") + public Month param_endMonth = Month.DECEMBER; + + public String [] necessaryResult = { + // put here all necessary result for this rule + // example: + // ResultName.MATRIX_BIOMASS, + // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + ResultName.MATRIX_NO_ACTIVITY, + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + /** + * Permet d'afficher a l'utilisateur une aide sur la regle. + * @return L'aide ou la description de la regle + */ + public String getDescription() throws Exception { + return _("Cantonnement: can be used to Cantonnement with gear if you put gear in parameter"); + } + + /** + * Appelé au démarrage de la simulation, cette méthode permet d'initialiser + * des valeurs + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void init(SimulationContext context) throws Exception { + } + + /** + * La condition qui doit etre vrai pour faire les actions + * @param simulation La simulation pour lequel on utilise cette regle + * @return vrai si on souhaite que les actions soit faites + */ + public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception { + if(date.before(param_beginDate)) { + return false; + } else if(date.after(param_endDate)) { + return false; + } + + if (date.getMonth().before(param_beginMonth)) { + return false; + } else if (date.getMonth().after(param_endMonth)) { + return false; + } + if (param_gear != null && !param_gear.equals(metier.getGear())) { + return false; + } + + + List<Cell> cellMetiers = metier.getMetierSeasonInfo(date.getMonth()).getCells(); + List<Cell> cells = param_zone.getCell(); + + cellMetiers.retainAll(cells); + + boolean result = !Collections.disjoint(cellMetiers, cells); + if (result && log.isInfoEnabled()) { + log.info("Cantonnement condition true"); + } + return result; + +/* +writeln("condition fermeture zone"); +var mois = p.date.getMois().getNumMois(); +writeln("mois:"+mois); +if(p.moisDeb>mois || p.moisFin<mois) + return false; +writeln("on est dans l'espace des mois possible"); +//on est dans l'espace des mois possible +if(p.date.before(p.dateDeb)) + return false; +if(p.date.after(p.dateFin)) + return false; + + +var mailleMetier = p.metier.getSecteurMois(p.date.getMois()).getMaille(); + +// s'il y a une intersection avec la zone ferme, alors la regle s'applique +mailleMetier.retainAll(p.mailles); +var result = mailleMetier.size() != 0; + +if(result) + writeln("===== Fermeture Zone s'applique ======"); +return result; +*/ + } + + /** + * Si la condition est vrai alors cette action est executée avant le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void preAction(SimulationContext context, Date date, Metier metier) throws Exception { + MetierMonitor metierMon = context.getMetierMonitor(); + + MetierSeasonInfo infoMetier = metier.getMetierSeasonInfo(date.getMonth()); + + List<Cell> cellMetiers = infoMetier.getCells(); + List<Cell> cells = param_zone.getCell(); + + cellMetiers.removeAll(cells); + + if (cellMetiers.size() != 0) { + ZoneDAO dao = IsisFishDAOHelper.getZoneDAO(context.getDB()); + + // + // Create new empty zone for cantonnement + // + String name = "ZoneCantonnement-" + metier.getName()+ "-" + date.getDate(); + Zone zoneCantonnement = dao.findByName(name); + int cpt=0; + while (zoneCantonnement != null) { + cpt++; + zoneCantonnement = dao.findByName(name + "-" + cpt); + } + zoneCantonnement = dao.create(); + if (cpt > 0) { + name += "-" + cpt; + } + zoneCantonnement.setName(name); + + // + // Remove prohibited zone and add not prohibited cell to zoneCantonnement + // + Collection<Zone> zoneMetiers = infoMetier.getZone(); + for (Iterator<Zone> i=zoneMetiers.iterator(); i.hasNext();) { + Zone zone = i.next(); + // copy list cell to not modify original zone + List<Cell> tmpCells = new ArrayList<Cell>(zone.getCell()); + tmpCells.removeAll(param_zone.getCell()); + + zoneCantonnement.addAllCell(tmpCells); + i.remove(); + } + ArrayList<Zone> newZone = new ArrayList<Zone>(); + newZone.add(zoneCantonnement); + infoMetier.setZone(newZone); + } else { + // sinon toute la zone de pratique du metier est incluse dans zone Cantonnement + // alors metier devient metier-nonactivite + + SiMatrix siMatrix = SiMatrix.getSiMatrix(context); + MatrixND noActivity = metierMon.getOrCreateNoActivity(date, + ResultName.MATRIX_NO_ACTIVITY, + siMatrix.getStrategies(date), + siMatrix.getMetiers(date)); + metierMon.addforbiddenMetier(metier); + List<Strategy> strategies = siMatrix.getStrategies(date); + + for(Strategy str : strategies){ + StrategyMonthInfo info = str.getStrategyMonthInfo(date.getMonth()); + double prop = info.getProportionMetier(metier); + if (prop != 0){ + noActivity.setValue(str , metier, prop); + info.setProportionMetier(metier, 0); + } + } + } + // fin de preAction + +/* +writeln("Cantonnement zone Action avant metier:"+p.metier); +writeln("Les mailles fermees sont:"+p.mailles); + +var zoneMetier = p.metier.getSecteurMois(p.date.getMois()); +var mailleMetier = zoneMetier.getMaille().copy(); +mailleMetier.removeAll(p.mailles); +writeln("inter maille:"+mailleMetier.size()); +// test pour savoir si toute la zone de pratique du metier +// (reunion de toutes les zones metiers de metier a date) +// est totalement incluse dans la zone Cantonnement +if (mailleMetier.size() != 0){ //le cas intersection.length==mailleMetier est dans condition + // si toute la zone de pratique du metier n'est pas incluse dans zone Cantonnement + + //creation du nouveau secteur de metier + //on vérifie si le secteur a pas déjà été modifié par une autre règle afin de ne pas avoir de problème d'ID + var ListeSecteur=MetaSecteurFactory.findAllByKey("MetaCantonnement-"+p.metier.getNom()+"-"+date.getDate(),p.metier.getRegion()); + if (ListeSecteur.size()!=0){ + var secteurResult = MetaSecteurFactory.create(zoneMetier.getNom()+"Modif", p.metier.getRegion(), "Secteur creer durant la simulation."); + } + else{ + var secteurResult = MetaSecteurFactory.create("MetaCantonnement-"+p.metier.getNom()+"-"+date.getDate(), p.metier.getRegion(), "Secteur creer durant la simulation."); + } + writeln("nouveau secteur cree:"+secteurResult); + var zonesMetier = zoneMetier.getAllSecteur(); + writeln("zonesMetier:"+zonesMetier); + writeln("zonesMetier.size:"+zonesMetier.size()); + + for(var i=0; i<zonesMetier.size(); i++){ + var zonemet = zonesMetier.get(i); + writeln("zonemet:"+zonemet); + // intersection entre la zeme zone metier a date et zone de Cantonnement + var listemailleszonemetier = zonemet.getMaille().copy(); + var nbMailleZoneMetier = listemailleszonemetier.size(); + writeln("maille metier:"+listemailleszonemetier); + writeln("maille Cantonnement:"+p.mailles); + listemailleszonemetier.removeAll(p.mailles); + if(0==listemailleszonemetier.size()){ + //si completement inclus on le supprime + //donc on ne le met pas dans le nouveau + writeln("on supprime la zone"+zonemet); + } + else if (listemailleszonemetier.size() != nbMailleZoneMetier) { + // si la zone metier n'est pas totalement incluse dans zone de Cantonnement + // on reduit la zeme zone metier de cette intersection + // pas de modif de la matrice de proportion strmet + writeln("on cree une nouvelle zone a partir de:"+zonemet+" avec "+listemailleszonemetier); + var simpleSecteur = SecteurSimpleFactory.create("Cantonnement-"+p.metier.getNom()+"-"+zonemet+"-"+date.getDate(), p.metier.getRegion(), "Secteur creer durant la simulation."); + simpleSecteur.addAllMaille(listemailleszonemetier); + secteurResult.addSecteur(simpleSecteur); + writeln("apres addSecteur"); + }else { + //sinon on le met dans le nouveau + writeln("On remet tel quelle la zone:"+zonemet); + secteurResult.addSecteur(zonemet); + } + }// fin du for sur les zone metier de la zone de pratique du metier + writeln("Zone metier avant"+zoneMetier.getMaille()); + writeln("Zone metier apres"+secteurResult); + writeln("Zone metier apres"+secteurResult.getMaille()); + p.metier.setSecteurMois(secteurResult, p.date.getMois()); +} +else { + writeln("Toute la zone metier est ferme"); + // sinon toute la zone de pratique du metier est incluse dans zone Cantonnement + // alors metier devient metier-nonactivite + + //on regarde si la matrice nonActivite a été crée, sinon on la crée + var matNonActivite=nonActivite.get(p.date); + var nonactivite=matNonActivite!=null; + if (!nonactivite){ + matNonActivite=MatrixFactory.create("nonActivite",new Array(SiMatrice.getListStrategies(),SiMatrice.getListMetiers()) + ,new Array("Strategies", "Metiers")); + nonActivite.put(p.date,matNonActivite); + } + + //listes des strategies contenant ce metier et tel que strmet(metier,date)!=0 + MetiersInterdits.put(new Packages.java.lang.String(p.metier.getNom()),true); + var listestrategies=StrategyFactory.findAllByRegion(p.metier.getRegion()); + + for(var i=0; i<listestrategies.size(); i++){ + var SetOfBateau=listestrategies.get(i).getSetOfVessels(); + var MetiersPosibles=SetOfBateau.getMetiers(); + + if (MetiersPosibles.contains(p.metier) ){ + var InfoMois=listestrategies.get(i).getStrategyMonthInfo(p.date.getMois()); + if (InfoMois.getProportionMetier(p.metier)!=0){ + matNonActivite.setValue(listestrategies.get(i),p.metier,InfoMois.getProportionMetier(p.metier)); + InfoMois.setProportionMetier(p.metier,new Packages.java.lang.Float(0)); + } + } + } +}// fin du else passage a metier-nonactivite +writeln("fin Cantonnement zone action avant"); +return p.gestionMetier; +*/ + } + + /** + * Si la condition est vrai alors cette action est executée apres le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void postAction(SimulationContext context, Date date, Metier metier) throws Exception { + // nothing + } + +} Added: isis-fish/trunk/src/test/resources/test-database/rules/CantonnementPreSimu.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/rules/CantonnementPreSimu.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/rules/CantonnementPreSimu.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,718 @@ +package rules; + +import static org.codelutin.i18n.I18n.n_; +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import scripts.ResultName; +import scripts.SiMatrix; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.codelutin.math.matrix.*; + +import fr.ifremer.isisfish.IsisFishDAOHelper; +import fr.ifremer.isisfish.simulator.MetierMonitor; +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.types.Month; +import fr.ifremer.isisfish.datastore.RegionStorage; +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.rule.AbstractRule; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * Cantonnement.java + * + * Created: 30 novembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.2 $ + * + * Last update: $Date: 2007-01-24 18:25:34 $ + * by : $Author: bpoussin $ + */ +public class CantonnementPreSimu extends AbstractRule { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(CantonnementPreSimu.class); + + @Doc(value="do the doc of param zone") + public Zone param_zone = null; + @Doc(value="do the doc of param gear") + public Gear param_gear = null; + @Doc(value="do the doc of param enginSelective") + public boolean param_enginSelective = true; + @Doc(value="do the doc of param beginMonth") + public Month param_beginMonth = Month.JANUARY; + @Doc(value="do the doc of param endMonth") + public Month param_endMonth = Month.DECEMBER; + + protected Map<Month, MatrixND> tableNonActivite = new HashMap<Month, MatrixND>(); + protected boolean affectNonActivite = false; + + public String [] necessaryResult = { + // put here all necessary result for this rule + // example: + // ResultName.MATRIX_BIOMASS, + // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + ResultName.MATRIX_NO_ACTIVITY, + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + /** + * Permet d'afficher a l'utilisateur une aide sur la regle. + * @return L'aide ou la description de la regle + */ + public String getDescription() throws Exception { + return _("Cantonnement: can be used to Cantonnement with gear if you put gear in parameter"); + } + + private void reportNonActivite(SimulationContext context, + List<Strategy> listestrategies, List<Metier> metiers, + Metier metier, List<Month> chomageMonth) { + for(Strategy strategy : listestrategies) { + SetOfVessels SetOfBateau = strategy.getSetOfVessels(); + EffortDescription effort = SetOfBateau.getPossibleMetiers(metier); + if (effort != null){ + for (Month month : chomageMonth) { + StrategyMonthInfo InfoMois = strategy.getStrategyMonthInfo(month); +//this.p.tableNonActivite=Regle_action_lib.reportNonActivite(this.p.tableNonActivite, listestrategies.get(i), metier, mois, InfoMois.getProportionMetier(metier)); + + log.info("debut reportNonActivite"); + // on regarde si on a déjà une entrée pour le mois courant + MatrixND matNonActiviteMois=tableNonActivite.get(month); + if (matNonActiviteMois == null){ + matNonActiviteMois = MatrixFactory.getInstance().create( + ResultName.MATRIX_NO_ACTIVITY, + new List[]{listestrategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + tableNonActivite.put(month, matNonActiviteMois); + } + + matNonActiviteMois.setValue(strategy, metier, InfoMois.getProportionMetier(metier)); + log.info("fin reportNonActivite"); + + InfoMois.setProportionMetier(metier, 0); + MetierMonitor metierMon = context.getMetierMonitor(); + metierMon.isLimited(metier, month); + metierMon.addforbiddenMetier(metier, month); + } + } + } + } + + /** + * Appelé au démarrage de la simulation, cette méthode permet d'initialiser + * des valeurs + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void init(SimulationContext context) throws Exception { + SiMatrix siMatrix = SiMatrix.getSiMatrix(context); + +// MetierDAO metierDao = IsisFishDAOHelper.getMetierDAO(context.getDB()); + ZoneDAO zoneDao = IsisFishDAOHelper.getZoneDAO(context.getDB()); + MetierSeasonInfoDAO metierSeasonInfoDao = IsisFishDAOHelper.getMetierSeasonInfoDAO(context.getDB()); + +// List<Metier> metiers = metierDao.findAll(); + List<Month> SaisonFermee = Month.getMonths(param_beginMonth, param_endMonth); + List<Cell> maillefermee = param_zone.getCell(); + + FisheryRegion region = RegionStorage.getFisheryRegion(context.getDB()); + List<Strategy> listestrategies= region.getStrategy(); + List<Metier> metiers = region.getMetier(); + +// var SaisonFermee= new Packages.fr.ifremer.nodb.Saison(moisDeb,moisFin); + + + for (Metier metier : metiers) { + log.info("metier examiné " + metier.getName()); + if (param_gear != null && !metier.getGear().equals(param_gear)){ + log.info("l engin du métier n est pas concerné"); + } + else { + log.info("l engin du métier est bien concerné"); + List<MetierSeasonInfo> saisons = metier.getMetierSeasonInfo(); + for (MetierSeasonInfo saisonmetier: saisons){ + int inter = siMatrix.nbCellInter(saisonmetier.getZone(), param_zone); + if (inter != 0){ + List<Cell> MailleMetier = siMatrix.getCells(saisonmetier.getZone()); + + // les mailles qui reste dans la zone metier + List<Cell> newCellMetier = new ArrayList<Cell>(MailleMetier); + newCellMetier.removeAll(maillefermee); + + List<Month> saison=saisonmetier.getMonths(); + if (saison.containsAll(SaisonFermee)){ + log.info("il y a bien intersection entre la zone métier et le cantonnement pour la saison "+saison.toString()); + // calcule de la zone restante: + boolean ToutFerme=false; + boolean DebInclus=saison.contains(param_beginMonth); + boolean FinInclus=saison.contains(param_endMonth); + + //creation du nouveau secteur de metier + Zone secteurResult = zoneDao.create(); + secteurResult.setName("MetaCantonnement-" + metier.getName() + "-" + saison.toString()); + secteurResult.setComment("Secteur créé durant la simulation."); + // on ajoute les mailles restants de la zone metier dans la zone resultante + secteurResult.addAllCell(newCellMetier); + + + // test pour savoir si toute la zone de pratique du metier + // (reunion de toutes les zones metiers de metier a date) + // est totalement incluse dans la zone Cantonnement + if (newCellMetier.size() != 0){ //le cas intersection.length==mailleMetier est dans condition + // si toute la zone de pratique du metier n'est pas incluse dans zone Cantonnement + ToutFerme=false; + } else { + log.info("Toute la zone metier est ferme"); + ToutFerme=true; + } + +// 1er cas: la saison métier est identique (ou totalement incluse dans la saison fermée, dans ce cas là, on change juste +// le secteur + if (SaisonFermee.containsAll(saison)){ + log.info("toute la saison metier est incluse dans la saison de fermeture"); + //si tout est fermé, on met le metier au chômage + + if (ToutFerme==true) { + log.info ("toute la zone est fermée, le metier passe donc à chômage pour cette saison"); + reportNonActivite(context, listestrategies, metiers, metier, saison); + + } else { + log.info("tout n'est pas fermée, le secteur de pêche devient " + secteurResult); + for (Month month : SaisonFermee){ + metier.getMetierSeasonInfo(month).clearZone(); + metier.getMetierSeasonInfo(month).addZone(secteurResult); + } + } + } + +// 2ème cas de figure: moisDeb est inclus mais pas moisFin (ou alors c'est le dernier mois) + else if (DebInclus && ((!FinInclus) || param_endMonth.equals(saison.get(saison.size()-1)))) { + log.info ("il y a intersection de la saison de fermeture avec la saison métier de " + param_beginMonth + " à " + saison.get(saison.size()-1)); + //si tout est fermé on met les proportions à 0 pour les mois fermes + if (ToutFerme==true){ + log.info ("toute la zone métier est fermée"); + List<Month> chomageMonth = new ArrayList<Month>(SaisonFermee); + chomageMonth.retainAll(saison); + log.info ("de "+chomageMonth.get(0)+" a "+ chomageMonth.get(chomageMonth.size()-1)+ ", le metier est donc mis au chomage"); + + reportNonActivite(context, listestrategies, metiers, metier, chomageMonth); + } else { + //on commence par crée les nouvelles saisons +// var NouvelleSaison2= new Packages.fr.ifremer.nodb.Saison(moisDeb,saison.getLastMois().getNumMois()); +// var NouvelleSaison1= new Packages.fr.ifremer.nodb.Saison(saison.getFirstMois().getNumMois(),moisDeb-1); + saisonmetier.setLastMonth(param_beginMonth.previous()); + //on crée un nouveau infoSaisonMetier + MetierSeasonInfo NouvelInfoSaison= metierSeasonInfoDao.create(); + NouvelInfoSaison.setMetier(metier); + NouvelInfoSaison.setFirstMonth(param_beginMonth); + NouvelInfoSaison.setLastMonth(saison.get(saison.size()-1)); + NouvelInfoSaison.addZone(secteurResult); + NouvelInfoSaison.setComment("saison crée pendant la simulation") ; + + metier.addMetierSeasonInfo(NouvelInfoSaison); + log.info ("de "+saison.get(0)+" à "+param_beginMonth.previous()+" le metier peche en "+saisonmetier.getZone()); + log.info ("de "+param_beginMonth+" à "+saison.get(saison.size()-1)+" le metier peche en "+secteurResult); + } + } +// 3ème cas de figure: moisFin est inclus mais pas moisDeb (ou alors il est égal au premier mois) + else if (((!DebInclus) || param_beginMonth.equals(saison.get(0))) && FinInclus) { + log.info ("il y a intersection de la saison de fermeture avec la saison métier de "+param_beginMonth+" à "+saison.get(saison.size()-1)); + //si tout est fermé on met les proportions à 0 pour les mois fermes + if (ToutFerme==true){ + log.info ("toute la zone est fermee"); + List<Month> chomageMonth = new ArrayList<Month>(SaisonFermee); + chomageMonth.retainAll(saison); + reportNonActivite(context, listestrategies, metiers, metier, chomageMonth); + } + else { + //on commence par crée les nouvelles saisons + saisonmetier.setFirstMonth(param_endMonth.next()); + //on crée un nouveau infoSaisonMetier + MetierSeasonInfo NouvelInfoSaison= metierSeasonInfoDao.create(); + NouvelInfoSaison.setMetier(metier); + NouvelInfoSaison.setFirstMonth(saison.get(0)); + NouvelInfoSaison.setLastMonth(param_endMonth); + NouvelInfoSaison.addZone(secteurResult); + NouvelInfoSaison.setComment("saison crée pendant la simulation") ; + + metier.addMetierSeasonInfo(NouvelInfoSaison); + log.info ("de "+saison.get(0)+" à "+param_endMonth+" le metier peche en "+secteurResult); + log.info ("de "+param_endMonth.next()+" à "+saison.get(saison.size()-1)+" le metier peche en "+saisonmetier.getZone()); + } + } + +// dernier cas de figure: les deux sont inclus et sont différents des bornes + else { + //si tout est fermé on met les proportions à 0 pour les mois fermes + if (ToutFerme==true){ + log.info("toute la zone métier est fermée"); + reportNonActivite(context, listestrategies, metiers, metier, SaisonFermee); + } + else { + //on commence par crée les nouvelles saisons +// var NouvelleSaison1= new Packages.fr.ifremer.nodb.Saison(saison.getFirstMois().getNumMois(),moisDeb-1); +// var NouvelleSaison2= new Packages.fr.ifremer.nodb.Saison(moisDeb,moisFin); +// var NouvelleSaison3=new Packages.fr.ifremer.nodb.Saison(moisFin+1,saison.getLastMois().getNumMois()); +// + saisonmetier.setFirstMonth(param_beginMonth.previous()); + //on crée un nouveau infoSaisonMetier + MetierSeasonInfo NouvelInfoSaison = metierSeasonInfoDao.create(); + NouvelInfoSaison.setMetier(metier); + NouvelInfoSaison.setFirstMonth(param_beginMonth); + NouvelInfoSaison.setLastMonth(param_endMonth); + NouvelInfoSaison.addZone(secteurResult); + NouvelInfoSaison.setComment("saison crée pendant la simulation") ; + metier.addMetierSeasonInfo(NouvelInfoSaison); + + //on crée un nouveau infoSaisonMetier + MetierSeasonInfo NouvelInfoSaison2 = metierSeasonInfoDao.create(); + NouvelInfoSaison2.setMetier(metier); + NouvelInfoSaison2.setFirstMonth(param_endMonth.next()); + NouvelInfoSaison2.setLastMonth(saison.get(saison.size()-1)); + NouvelInfoSaison2.setZone(saisonmetier.getZone()); + NouvelInfoSaison2.setComment("saison crée pendant la simulation") ; + metier.addMetierSeasonInfo(NouvelInfoSaison2); + + log.info ("de "+saison.get(0)+" à "+param_beginMonth.previous()+" le metier peche en "+saisonmetier.getZone()); + log.info ("de "+param_beginMonth+" à "+param_endMonth+" le metier peche en "+secteurResult); + log.info ("de "+param_endMonth.next()+" à "+saison.get(saison.size()-1)+" le metier peche en "+saisonmetier.getZone()); + } + } + } + } + } + } + } + + /* + this.p = new Object(); + this.p.paramRegle = this.param; + this.p.tableNonActivite=new Packages.java.util.HashMap(); + this.p.affectNonActivite=false; + + + var enginselectif=this.param.getValue("EnginSelective");//entrez le nom de l'engin fermée ou non si pas de sélection sur engin + var moisDeb=this.param.getValue("moisDeb"); //entrez le mois debut de fermeture + var moisFin=this.param.getValue("moisFin");//entrez le mois de fin de fermeture + + + + var ZoneFermee=this.param.getValue("zone"); + writeln("bla"); + if (enginselectif) {var EnginInterdit=this.param.getValue("engin");} else {var EnginInterdit=MetierFactory.findByNom("nonActivite").getEngin();} + var RegionSimu=ZoneFermee.getRegion(); + var ListeMetiers=MetierFactory.findAllByRegion(RegionSimu); + var MoisDeb=new Packages.fr.ifremer.nodb.Mois(moisDeb); + var MoisFin=new Packages.fr.ifremer.nodb.Mois(moisFin); + var SaisonFermee= new Packages.fr.ifremer.nodb.Saison(moisDeb,moisFin); + + + + for (var imetier = ListeMetiers.iterator() ; imetier.hasNext();){ + var metier=imetier.next(); + writeln ("metier examiné "+metier.getNom()); + if ((!metier.getEngin().equals(EnginInterdit)) && enginselectif){ + writeln("l engin du métier n est pas concerné"); + } + else { + writeln("l engin du métier est bien concerné"); + var ListeSaisons = metier.getInfoSaison(); + for (var isaisonmetier = ListeSaisons.iterator() ; isaisonmetier.hasNext();){ + var saisonmetier=isaisonmetier.next(); + var maillefermee=ZoneFermee.getMaille(); + var MailleMetier=saisonmetier.getSecteur().getMaille().copy(); + MailleMetier.retainAll(maillefermee); + + if (MailleMetier.size()!=0){ + MailleMetier=saisonmetier.getSecteur().getMaille().copy(); + var saison=saisonmetier.getSaison(); + if (saison.contains(SaisonFermee)){ + writeln("il y a bien intersection entre la zone métier et le cantonnement pour la saison "+saison.toString()); +// calcule de la zone restante: + var ToutFerme=false; + var DebInclus=saison.contains(MoisDeb); + var FinInclus=saison.contains(MoisFin); + MailleMetier.removeAll(maillefermee); + writeln("inter maille:"+MailleMetier.size()); + // test pour savoir si toute la zone de pratique du metier + // (reunion de toutes les zones metiers de metier a date) + // est totalement incluse dans la zone Cantonnement + + if (MailleMetier.size() != 0){ //le cas intersection.length==mailleMetier est dans condition + // si toute la zone de pratique du metier n'est pas incluse dans zone Cantonnement + + ToutFerme=false; + + //creation du nouveau secteur de metier + //on vérifie si le secteur a pas déjà été modifié par une autre règle afin de ne pas avoir de problème d'ID + var ListeSecteur=MetaSecteurFactory.findAllByKey("MetaCantonnement-"+metier.getNom()+saison.toString(), RegionSimu); + if (ListeSecteur.size()!=0){ + var secteurResult = MetaSecteurFactory.create(saisonmetier.getSecteur().getNom()+"Modif", RegionSimu, "Secteur créé durant la simulation."); + } + else{ + var secteurResult = MetaSecteurFactory.create("MetaCantonnement-"+metier.getNom()+saison.toString(),RegionSimu, "Secteur créé durant la simulation."); + } + + writeln("nouveau secteur cree:"+secteurResult); + var zonesMetier = saisonmetier.getSecteur().getAllSecteur(); + writeln("zonesMetier:"+zonesMetier); + writeln("zonesMetier.size:"+zonesMetier.size()); + + for(var i=0; i<zonesMetier.size(); i++){ + var zonemet = zonesMetier.get(i); + writeln("zonemet:"+zonemet); + // intersection entre la zeme zone metier a date et zone de Cantonnement + var listemailleszonemetier = zonemet.getMaille().copy(); + var nbMailleZoneMetier = listemailleszonemetier.size(); + writeln("maille metier:"+listemailleszonemetier); + writeln("maille Cantonnement:"+maillefermee); + listemailleszonemetier.removeAll(maillefermee); + if(0==listemailleszonemetier.size()){ + //si completement inclus on le supprime + //donc on ne le met pas dans le nouveau + writeln("on supprime la zone"+zonemet); + } + else if (listemailleszonemetier.size() != nbMailleZoneMetier) { + // si la zone metier n'est pas totalement incluse dans zone de Cantonnement + // on reduit la zeme zone metier de cette intersection + // pas de modif de la matrice de proportion strmet + writeln("on cree une nouvelle zone a partir de:"+zonemet+" avec "+listemailleszonemetier); + var simpleSecteur = SecteurSimpleFactory.create("Cantonnement-"+metier.getNom()+"-"+zonemet+saison.toString(), RegionSimu, "Secteur creer durant la simulation."); + simpleSecteur.addAllMaille(listemailleszonemetier); + secteurResult.addSecteur(simpleSecteur); + writeln("apres addSecteur"); + } + else { + //sinon on le met dans le nouveau + writeln("On remet tel quelle la zone:"+zonemet); + secteurResult.addSecteur(zonemet); + } + }// fin du for sur les zone metier de la zone de pratique du metier + } + + else { + var secteurResult=saisonmetier.getSecteur().getAllSecteur(); + writeln("Toute la zone metier est ferme"); + ToutFerme=true; + } + +// 1er cas: la saison métier est identique (ou totalement incluse dans la saison fermée, dans ce cas là, on change juste +// le secteur + if (SaisonFermee.toListMois().containsAll(saison.toListMois())){ + writeln("toute la saison metier est incluse dans la saison de fermeture"); + //si tout est fermé, on met le metier au chômage + + if (ToutFerme==true){ + writeln ("toute la zone est fermée, le metier passe donc à chômage pour cette saison"); + var listestrategies=StrategyFactory.findAllByRegion(RegionSimu); + var ListeMois=saison.toListMois(); + for(var i=0; i<listestrategies.size(); i++){ + var SetOfBateau=listestrategies.get(i).getSetOfVessels(); + var MetiersPosibles=SetOfBateau.getMetiers(); + if (MetiersPosibles.contains(metier)){ + for (imois=ListeMois.iterator();imois.hasNext();){ + var mois=imois.next(); + var InfoMois=listestrategies.get(i).getStrategyMonthInfo(mois); + //this.p.tableNonActivite=Regle_action_lib.reportNonActivite(this.p.tableNonActivite, listestrategies.get(i), metier, mois, InfoMois.getProportionMetier(metier)); + + + +writeln("debut reportNonActivite"); +//on regarde si on a déjà une entrée pour le mois courant +var matNonActiviteMois=table.get(mois); +var nonactivite=matNonActiviteMois!=null; + +if (!nonactivite){ + matNonActiviteMois=MatrixFactory.create("nonActivite",new Array(SiMatrice.getListStrategies(),SiMatrice.getListMetiers()) + ,new Array("Strategies", "Metiers")); + table.put(mois,matNonActiviteMois); +} + +matNonActiviteMois.setValue(strategie,metier,proportion); +writeln("fin reportNonActivite"); + + + + InfoMois.setProportionMetier(metier,new Packages.java.lang.Float(0)); + MetiersInterditsPresimu.put(new Chaine(metier.getNom()+"-"+mois.getNumMois()),true); + } + } + } + } + else { + writeln("tout n'est pas fermée, le secteur de pêche devient "+secteurResult); + var ListeMois=SaisonFermee.toListMois(); + for (imois=ListeMois.iterator();imois.hasNext();){ + mois=imois.next(); + metier.setSecteurMois(secteurResult, mois); + } + } + } + +// 2ème cas de figure: moisDeb est inclus mais pas moisFin (ou alors c'est le dernier mois) + else if (DebInclus && ((!FinInclus) || moisFin==saison.getLastMois().getNumMois())){ + writeln ("il y a intersection de la saison de fermeture avec la saison métier de "+moisDeb+" à "+saison.getLastMois().getNumMois()); + //si tout est fermé on met les proportions à 0 pour les mois fermes + if (ToutFerme==true){ + writeln ("toute la zone métier est fermée"); + var listestrategies=StrategyFactory.findAllByRegion(RegionSimu); + var ListeMois=SaisonFermee.toListMois().retainAll(saison.toListMois()); + writeln ("de "+ListeMois.get(0)+" a "+ ListeMois.get(ListeMois.size())+ ", le metier est donc mis au chomage"); + for(var i=0; i<listestrategies.size(); i++){ + var SetOfBateau=listestrategies.get(i).getSetOfVessels(); + var MetiersPosibles=SetOfBateau.getMetiers(); + if (MetiersPosibles.contains(metier)){ + for (imois=ListeMois.iterator();imois.hasNext();){ + var mois=imois.next(); + var InfoMois=listestrategies.get(i).getStrategyMonthInfo(mois); + //this.p.tableNonActivite=Regle_action_lib.reportNonActivite(this.p.tableNonActivite, listestrategies.get(i), metier, mois, InfoMois.getProportionMetier(metier)); + + + +writeln("debut reportNonActivite"); +//on regarde si on a déjà une entrée pour le mois courant +var matNonActiviteMois=table.get(mois); +var nonactivite=matNonActiviteMois!=null; + +if (!nonactivite){ + matNonActiviteMois=MatrixFactory.create("nonActivite",new Array(SiMatrice.getListStrategies(),SiMatrice.getListMetiers()) + ,new Array("Strategies", "Metiers")); + table.put(mois,matNonActiviteMois); +} + +matNonActiviteMois.setValue(strategie,metier,proportion); +writeln("fin reportNonActivite"); + + + + + InfoMois.setProportionMetier(metier,new Packages.java.lang.Float(0)); + MetiersInterditsPresimu.put(new Chaine(metier.getNom()+"-"+mois.getNumMois()),true); + } + } + } + } + else { + //on commence par crée les nouvelles saisons + var NouvelleSaison2= new Packages.fr.ifremer.nodb.Saison(moisDeb,saison.getLastMois().getNumMois()); + var NouvelleSaison1= new Packages.fr.ifremer.nodb.Saison(saison.getFirstMois().getNumMois(),moisDeb-1); + saisonmetier.setSaison(NouvelleSaison1); + //on crée un nouveau infoSaisonMetier + var NouvelInfoSaison=InfoSaisonMetierFactory.create(metier, NouvelleSaison2, secteurResult, "saison crée pendant la simulation") ; + metier.addInfoSaison(NouvelInfoSaison); + writeln ("de "+saison.getFirstMois().getNumMois()+" à "+moisDeb-1+" le metier peche en "+saisonmetier.getSecteur()); + writeln ("de "+moisDeb+" à "+saison.getLastMois().getNumMois()+" le metier peche en "+secteurResult); + } + } +// 3ème cas de figure: moisFin est inclus mais pas moisDeb (ou alors il est égal au premier mois) + else if (((!DebInclus) || moisDeb==saison.getFirstMois().getNumMois()) && FinInclus){ + writeln ("il y a intersection de la saison de fermeture avec la saison métier de "+moisDeb+" à "+saison.getLastMois().getNumMois()); + //si tout est fermé on met les proportions à 0 pour les mois fermes + if (ToutFerme==true){ + writeln ("toute la zone est fermee"); + var listestrategies=StrategyFactory.findAllByRegion(RegionSimu); + var ListeMois=SaisonFermee.toListMois().retainAll(saison.toListMois()); + writeln ("de "+ListeMois.get(0)+" a "+ ListeMois.get(ListeMois.size())+ ", le metier est donc mis au chomage"); + for(var i=0; i<listestrategies.size(); i++){ + var SetOfBateau=listestrategies.get(i).getSetOfVessels(); + var MetiersPosibles=SetOfBateau.getMetiers(); + if (MetiersPosibles.contains(metier) ){ + for (imois=ListeMois.iterator();imois.hasNext();){ + var mois=imois.next(); + var InfoMois=listestrategies.get(i).getStrategyMonthInfo(mois); + //this.p.tableNonActivite=Regle_action_lib.reportNonActivite(this.p.tableNonActivite, listestrategies.get(i), metier, mois, InfoMois.getProportionMetier(metier)); + + +writeln("debut reportNonActivite"); +//on regarde si on a déjà une entrée pour le mois courant +var matNonActiviteMois=table.get(mois); +var nonactivite=matNonActiviteMois!=null; + +if (!nonactivite){ + matNonActiviteMois=MatrixFactory.create("nonActivite",new Array(SiMatrice.getListStrategies(),SiMatrice.getListMetiers()) + ,new Array("Strategies", "Metiers")); + table.put(mois,matNonActiviteMois); +} + +matNonActiviteMois.setValue(strategie,metier,proportion); +writeln("fin reportNonActivite"); + + + + + InfoMois.setProportionMetier(metier,new Packages.java.lang.Float(0)); + MetiersInterditsPresimu.put(new Chaine(metier.getNom()+"-"+mois.getNumMois()),true); + } + } + } + } + else { + //on commence par crée les nouvelles saisons + var NouvelleSaison1= new Packages.fr.ifremer.nodb.Saison(saison.getFirstMois().getNumMois(),moisFin); + var NouvelleSaison2= new Packages.fr.ifremer.nodb.Saison(moisFin+1,saison.getLastMois.getNumMois()); + saisonmetier.setSaison(NouvelleSaison2); + //on crée un nouveau infoSaisonMetier + var NouvelInfoSaison=InfoSaisonMetierFactory.create(metier, NouvelleSaison1, secteurResult, "saison crée pendant la simulation") ; + metier.addInfoSaison(NouvelInfoSaison); + writeln ("de "+saison.getFirstMois().getNumMois()+" à "+moisFin+" le metier peche en "+secteurResult); + writeln ("de "+moisFin+1+" à "+saison.getLastMois().getNumMois()+" le metier peche en "+saisonmetier.getSecteur()); + } + } + +// dernier cas de figure: les deux sont inclus et sont différents des bornes + else { + //si tout est fermé on met les proportions à 0 pour les mois fermes + if (ToutFerme==true){ + writeln("toute la zone métier est fermée"); + var listestrategies=StrategyFactory.findAllByRegion(metier.getRegion()); + var ListeMois=SaisonFermee.toListMois(); + writeln("le métier passe à chômage de "+moisDeb+" à "+moidFin); + for(var i=0; i<listestrategies.size(); i++){ + var SetOfBateau=listestrategies.get(i).getSetOfVessels(); + var MetiersPosibles=SetOfBateau.getMetiers(); + if (MetiersPosibles.contains(metier) ){ + for (imois=ListeMois.iterator();imois.hasNext();){ + var mois=imois.next(); + var InfoMois=listestrategies.get(i).getStrategyMonthInfo(mois); + //this.p.tableNonActivite=Regle_action_lib.reportNonActivite(this.p.tableNonActivite, listestrategies.get(i), metier, mois, InfoMois.getProportionMetier(metier)); + + +writeln("debut reportNonActivite"); +//on regarde si on a déjà une entrée pour le mois courant +var matNonActiviteMois=table.get(mois); +var nonactivite=matNonActiviteMois!=null; + +if (!nonactivite){ + matNonActiviteMois=MatrixFactory.create("nonActivite",new Array(SiMatrice.getListStrategies(),SiMatrice.getListMetiers()) + ,new Array("Strategies", "Metiers")); + table.put(mois,matNonActiviteMois); +} + +matNonActiviteMois.setValue(strategie,metier,proportion); +writeln("fin reportNonActivite"); + + + + InfoMois.setProportionMetier(metier,new Packages.java.lang.Float(0)); + MetiersInterditsPresimu.put(new Chaine(metier.getNom()+"-"+mois.getNumMois()),true); + } + } + } + } + else { + //on commence par crée les nouvelles saisons + var NouvelleSaison1= new Packages.fr.ifremer.nodb.Saison(saison.getFirstMois().getNumMois(),moisDeb-1); + var NouvelleSaison2= new Packages.fr.ifremer.nodb.Saison(moisDeb,moisFin); + var NouvelleSaison3=new Packages.fr.ifremer.nodb.Saison(moisFin+1,saison.getLastMois().getNumMois()); + saisonmetier.setSaison(NouvelleSaison1); + //on crée 2 nouveau infoSaisonMetier + var NouvelInfoSaison2=InfoSaisonMetierFactory.create(metier, NouvelleSaison2, secteurResult, "saison crée pendant la simulation") ; + var NouvelInfoSaison3=InfoSaisonMetierFactory.create(metier, NouvelleSaison3, saisonmetier.getSecteur(), "saison crée pendant la simulation") ; + metier.addInfoSaison(NouvelInfoSaison2); + metier.addInfoSaison(NouvelInfoSaison3); + writeln ("de "+saison.getFirstMois().getNumMois()+" à "+(moisDeb-1)+" le metier peche en "+saisonmetier.getSecteur()); + writeln ("de "+moisDeb+" à "+moisFin+" le metier peche en "+secteurResult); + writeln ("de "+(moisFin+1)+" à "+saison.getLastMois().getNumMois()+" le metier peche en "+saisonmetier.getSecteur()); + } + } + } + } + } + } + } + */ + + } + + /** + * La condition qui doit etre vrai pour faire les actions + * @param simulation La simulation pour lequel on utilise cette regle + * @return vrai si on souhaite que les actions soit faites + */ + public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception { + boolean result = false; + MatrixND mat = tableNonActivite.get(date.getMonth()); + if (mat != null && affectNonActivite == false) { + result = true; + } + return result; + // fin + + /* + var mat=p.tableNonActivite.get(p.date.getMois()); + writeln(p.affectNonActivite); + if(oldValue != undefined) + return oldValue; + else if (mat!=null && p.affectNonActivite==false){ + return true; + } + else {return false;} + */ + } + + /** + * Si la condition est vrai alors cette action est executée avant le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void preAction(SimulationContext context, Date date, Metier metier) throws Exception { + // on ne doit le faire qu'une seul fois quelque soit le nombre de metier + affectNonActivite=true; + MatrixND mat = tableNonActivite.get(date.getMonth()); + + MetierMonitor metierMon = context.getMetierMonitor(); + MatrixND noActivity = metierMon.getNoActivity(date); + + if (noActivity == null){ + metierMon.setNoActivity(date, mat.copy()); + } + else{ + noActivity = noActivity.add(mat); + } + + /* + p.affectNonActivite=true; +var mat=p.tableNonActivite.get(p.date.getMois()); +var matNonActivite=nonActivite.get(p.date); +var nonactivite=matNonActivite!=null; +if (!nonactivite){ + nonActivite.put(p.date,mat); +} +else{ + matNonActivite=matNonActivite.add(mat); +} +return p.gestionMetier; + + */ + } + + /** + * Si la condition est vrai alors cette action est executée apres le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void postAction(SimulationContext context, Date date, Metier metier) throws Exception { + affectNonActivite = false; + + /* + p.affectNonActivite=false; +return p.gestionMetier; + */ + } + +} Added: isis-fish/trunk/src/test/resources/test-database/rules/ChangementParamControlablePresimu.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/rules/ChangementParamControlablePresimu.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/rules/ChangementParamControlablePresimu.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,323 @@ +package rules; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import scripts.ResultName; +import scripts.SiMatrix; + +import java.io.Writer; +import java.util.ArrayList; +import java.util.List; + +import org.codelutin.math.matrix.*; + +import fr.ifremer.isisfish.IsisFishDAOHelper; +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.types.Month; +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.rule.AbstractRule; +import fr.ifremer.isisfish.datastore.RegionStorage; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * TailleMin.java + * + * Created: 30 novembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.1 $ + * + * Last update: $Date: 2007-01-24 18:25:34 $ + * by : $Author: bpoussin $ + */ +public class ChangementParamControlablePresimu extends AbstractRule { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(ChangementParamControlablePresimu.class); + + @Doc(value="do the doc of param zone") + public Zone param_zone = null; + @Doc(value="do the doc of param gear") + public Gear param_gear = null; + @Doc(value="do the doc of param beginMonth") + public Month param_beginMonth = Month.JANUARY; + @Doc(value="do the doc of param endMonth") + public Month param_endMonth = Month.DECEMBER; + @Doc(value="do the doc of param newParamValue") + public String param_newParamValue = "80"; + + public String [] necessaryResult = { + // put here all necessary result for this rule + // example: + // ResultName.MATRIX_BIOMASS, + // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + /** + * Permet d'afficher a l'utilisateur une aide sur la regle. + * @return L'aide ou la description de la regle + */ + public String getDescription() throws Exception { + return _("Change gear parameter value for all metier with this gear"); + } + + /** + * Appelé au démarrage de la simulation, cette méthode permet d'initialiser + * des valeurs + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void init(SimulationContext context) throws Exception { + SiMatrix siMatrix = SiMatrix.getSiMatrix(context); + + Zone ZoneFermee = param_zone; + Month MoisDeb = param_beginMonth; + Month MoisFin= param_endMonth; + String nouvelleValeurParam = param_newParamValue; + Gear EnginInterdit = param_gear; + + log.info("nom de l'engin interdit " + EnginInterdit.getName()); + + FisheryRegion RegionSimu = RegionStorage.getFisheryRegion(context.getDB()); + List<Metier> ListeMetiers = RegionSimu.getMetier(); + List<Month> SaisonFermee = Month.getMonths(MoisDeb, MoisFin); + + for (Metier metier : ListeMetiers) { + log.info("metier examiné " + metier.getName() + " son engin " + metier.getGear().getName()); + if (!metier.getGear().equals(EnginInterdit)){ + log.info("l engin du métier n est pas concerné"); + } else { + log.info("l engin du métier est bien concerné"); + if (ZoneFermee == null && Month.JANUARY.equals(MoisDeb) && Month.DECEMBER.equals(MoisFin)){ + //aucun critère spatio-temporel il suffit donc de mettre + //le param controlable à la nouvelle valeur + metier.setGearParameterValue(nouvelleValeurParam); + log.info("aucune spatialisation ni saisonnalité, on passe le Param Controlable a "+nouvelleValeurParam); + } else { + List<MetierSeasonInfo> ListeSaisons = metier.getMetierSeasonInfo(); + for (MetierSeasonInfo saisonmetier : ListeSaisons) { + List<Month> saison = saisonmetier.getMonths(); + int taille=0; + if (ZoneFermee != null){ + taille = siMatrix.nbCellInter(saisonmetier.getZone(), ZoneFermee); + } else { + log.info ("pas de sélection de zone, toute la zone d'étude est donc concernée"); + } + if (ZoneFermee == null || taille!=0){ + if (saison.containsAll(SaisonFermee)){ + log.info ("il y a intersection de la zone metier au cours de la saison" + saison); + List<Month> moisconcerne = new ArrayList<Month>(saison); + moisconcerne.retainAll(SaisonFermee); + + MetierDAO metierDao = IsisFishDAOHelper.getMetierDAO(context.getDB()); + MetierSeasonInfoDAO infoDao = IsisFishDAOHelper.getMetierSeasonInfoDAO(context.getDB()); + EffortDescriptionDAO effortDao = IsisFishDAOHelper.getEffortDescriptionDAO(context.getDB()); + + Metier NouveauMetier = metierDao.create(); + NouveauMetier.setName(metier.getName()+" Mois "+moisconcerne.get(0).getMonthNumber()+" a "+moisconcerne.get(moisconcerne.size()-1).getMonthNumber()+" ValeurParam "+nouvelleValeurParam); + NouveauMetier.setGear(EnginInterdit); + NouveauMetier.setGearParameterValue(nouvelleValeurParam); + NouveauMetier.setComment("métier créé pendant la simu pour le changement de paramètre contrôlable"); + + for (MetierSeasonInfo infsais : metier.getMetierSeasonInfo()){ + List<Month> sais = infsais.getMonths(); + MetierSeasonInfo NouveauInfoSaison = infoDao.create(); + NouveauInfoSaison.setMetier(NouveauMetier); + NouveauInfoSaison.setMonths(sais); + NouveauInfoSaison.setZone(infsais.getZone()); + NouveauInfoSaison.setComment("créé durant la simulation"); + NouveauMetier.addMetierSeasonInfo(NouveauInfoSaison); + } + + //On ajoute aux strategies qui pratiquent le métier le nouveau métier + List<Strategy> listestrategies = RegionSimu.getStrategy(); + for(Strategy strategie : listestrategies){ + SetOfVessels SetOfBateau = strategie.getSetOfVessels(); + EffortDescription AncienEffort = SetOfBateau.getPossibleMetiers(metier); + if (AncienEffort != null) { + EffortDescription DescriptionEffort = effortDao.create(); + DescriptionEffort.setPossibleMetiers(NouveauMetier); + DescriptionEffort.setSetOfVessels(SetOfBateau); + DescriptionEffort.setFishingOperation(AncienEffort.getFishingOperation()); + DescriptionEffort.setFishingOperationDuration(AncienEffort.getFishingOperationDuration()); + DescriptionEffort.setGearsNumberPerOperation(AncienEffort.getGearsNumberPerOperation()); + DescriptionEffort.setCrewSize(AncienEffort.getCrewSize()); + DescriptionEffort.setUnitCostOfFishing(AncienEffort.getUnitCostOfFishing()); + DescriptionEffort.setFixedCrewSalary(AncienEffort.getFixedCrewSalary()); + DescriptionEffort.setCrewShareRate(AncienEffort.getCrewShareRate()); + DescriptionEffort.setCrewFoodCost(AncienEffort.getCrewFoodCost()); + DescriptionEffort.setRepairAndMaintenanceGearCost(AncienEffort.getRepairAndMaintenanceGearCost()); + DescriptionEffort.setLandingCosts(AncienEffort.getLandingCosts()); + DescriptionEffort.setOtherRunningCost(AncienEffort.getOtherRunningCost()); + + SetOfBateau.addPossibleMetiers(DescriptionEffort); + + // on a ajouté le nouveau métier au set of vessels, + // maintenant, on va reporté l'effort du métier ancien + // vers le nouveau pour les mois concernés + for (Month mois : Month.MONTH){ + StrategyMonthInfo PropStratMois = strategie.getStrategyMonthInfo(mois); + double prop = PropStratMois .getProportionMetier(metier); + if (moisconcerne.contains(mois) && prop != 0){ + //on créé un nouveau PropStrMet + log.info ("la stratégie "+strategie.getName()+" pratique bien le metier "+metier.getName()+" au mois " + mois); + PropStratMois.setProportionMetier(NouveauMetier, prop); + PropStratMois.setProportionMetier(metier, 0); + } + } + } + } + } + } + } + } + } + } + + // fin de la methode + + /* +this.p = new Object(); +this.p.paramRegle = this.param; + + +//attention: cette règle de gestion ne fonctionne que si le changement a lieu pour toutes +//les années de simulation + + +var zoneselective=this.param.getValue("ZoneSelective"); //entrez le nom de la zone concernée, non si pas de sélection sur zone +var moisDeb=this.param.getValue("moisDeb"); //entrez le mois debut de fermeture +var moisFin=this.param.getValue("moisFin");//entrez le mois de fin de fermeture +var nouvelleValeurParam=this.param.getValue("nouvelleValeurParam");//entrez la valeur du paramètre contrôlable + + +if (zoneselective!="non") { + var ZoneFermee=this.param.getValue("zone"); +} +var EnginInterdit=this.param.getValue("engin"); +writeln("nom de l'engin interdit "+EnginInterdit.getNom()); +var RegionSimu=EnginInterdit.getRegion(); +var ListeMetiers=MetierFactory.findAllByRegion(RegionSimu); +var MoisDeb=new Packages.fr.ifremer.nodb.Mois(moisDeb); +var MoisFin=new Packages.fr.ifremer.nodb.Mois(moisFin); +var SaisonFermee= new Packages.fr.ifremer.nodb.Saison(moisDeb,moisFin); + + + + +for (var imetier = ListeMetiers.iterator() ; imetier.hasNext();){ + var metier=imetier.next(); + writeln ("metier examiné "+metier.getNom()+"son engin "+metier.getEngin().getNom()); + if (!metier.getEngin().equals(EnginInterdit)){ + writeln("l engin du métier n est pas concerné"); + } + else { + writeln("l engin du métier est bien concerné"); + if (zoneselective==false && moisDeb==0 && moisFin==11){ + //aucun critère spatio-temporel il suffit donc de mettre + //le param controlable à la nouvelle valeur + metier.setValeurParamControlable(nouvelleValeurParam); + writeln("aucune spatialisation ni saisonnalité, on passe le Param Controlable a "+nouvelleValeurParam); + } + else { + var ListeSaisons = metier.getInfoSaison(); + for (var isaisonmetier = ListeSaisons.iterator() ; isaisonmetier.hasNext();){ + var saisonmetier=isaisonmetier.next(); + var saison=saisonmetier.getSaison(); + var taille=0; + if (zoneselective){ + var maillefermee=ZoneFermee.getMaille(); + var MailleMetier=saisonmetier.getSecteur().getMaille().copy(); + MailleMetier.retainAll(maillefermee); + taille=MailleMetier.size(); + } + else { + writeln ("pas de sélection de zone, toute la zone d'étude est donc concernée"); + } + if (zoneselective==false || taille!=0){ + if (saison.contains(SaisonFermee)){ + writeln ("il y a intersection de la zone metier au cours de la saison"+saison.toString()); + var moisconcerne=saison.copy().toListMois(); + moisconcerne.retainAll(SaisonFermee.toListMois()); + var NouveauMetier=MetierFactory.create(metier.getNom()+" Mois "+moisconcerne.get(0).getNumMois()+" a "+moisconcerne.get(moisconcerne.size()-1).getNumMois()+" ValeurParam "+nouvelleValeurParam, RegionSimu, EnginInterdit,nouvelleValeurParam, "métier créé pendant la simu pour le changement de paramètre contrôlable"); + for (var iinfsais=metier.getInfoSaison().iterator();iinfsais.hasNext();){ + var infsais=iinfsais.next(); + var sais=infsais.getSaison(); + var NouveauInfoSaison=InfoSaisonMetierFactory.create(NouveauMetier, sais, infsais.getSecteur(), "créé durant la simulation") + NouveauMetier.addInfoSaison(NouveauInfoSaison); + } + + //On ajoute aux strategies qui pratiquent le métier le nouveau métier + var listestrategies=StrategyFactory.findAllByRegion(RegionSimu); + for(var i=0; i<listestrategies.size(); i++){ + var strategie=listestrategies.get(i); + var SetOfBateau=strategie.getSetOfVessels(); + var MetiersPosibles=SetOfBateau.getMetiers(); + if (MetiersPosibles.contains(metier)){ + var AncienEffort=SetOfBateau.getEffort(metier); + var DescriptionEffort=EffortDescriptionFactory.create(NouveauMetier, SetOfBateau, AncienEffort.getFishingOperation(), AncienEffort.getFishingOperationDuration(), AncienEffort.getGearsNumberPerOperation(), AncienEffort.getCrewSize(), AncienEffort.getUnitCostOfFishing(), AncienEffort.getFixedCrewSalary(), AncienEffort.getCrewShareRate(), AncienEffort.getCrewFoodCost(), AncienEffort.getRepairAndMaintenanceGearCost(), AncienEffort.getLandingCosts(), AncienEffort.getOtherRunningCosts(), "effort description créé durant la simulation"); + + SetOfBateau.addPossibleMetiers(DescriptionEffort); + + //on a ajouté le nouveau métier au set of vessels, maintenant, on va reporté l'effort du métier ancien vers le nouveau pour les mois concernés + for (var intmois=0; intmois<=11;intmois++){ + var mois=new Packages.fr.ifremer.nodb.Mois(intmois); + var PropStratMois=strategie.getStrategyMonthInfo(mois); + var NouveauStrMet=PropStrMetFactory.create(PropStratMois, NouveauMetier, 0, "créé durant la simulation"); + PropStratMois.addPropStrMet(NouveauStrMet); + if (moisconcerne.contains(mois) && PropStratMois.getProportionMetier(metier)!=0){ + //on créé un nouveau PropStrMet + writeln ("la stratégie "+strategie.getName()+" pratique bien le metier "+metier.getNom()+" au mois "+mois.getNumMois()); + PropStratMois.setProportionMetier(NouveauMetier,new Packages.java.lang.Float(PropStratMois.getProportionMetier(metier))); + PropStratMois.setProportionMetier(metier,new Packages.java.lang.Float(0)); + } + } + } + } + } + } + } + } + } +} + */ + } + + /** + * La condition qui doit etre vrai pour faire les actions + * @param simulation La simulation pour lequel on utilise cette regle + * @return vrai si on souhaite que les actions soit faites + */ + public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception { + return false; + } + + /** + * Si la condition est vrai alors cette action est executée avant le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void preAction(SimulationContext context, Date date, Metier metier) throws Exception { + // nothing + } + + /** + * Si la condition est vrai alors cette action est executée apres le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void postAction(SimulationContext context, Date date, Metier metier) throws Exception { + // nothing + } + +} Added: isis-fish/trunk/src/test/resources/test-database/rules/GraviteCPUE.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/rules/GraviteCPUE.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/rules/GraviteCPUE.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,484 @@ +package rules; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import scripts.GravityModel; +import scripts.ResultName; +import scripts.SiMatrix; + +import java.util.Arrays; +import java.util.List; + +import org.codelutin.math.matrix.*; + +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.types.Month; +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.rule.AbstractRule; +import fr.ifremer.isisfish.datastore.ResultStorage; + +/** + * GraviteCPUE.java + * + * Created: 30 novembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.2 $ + * + * Last update: $Date: 2007-07-18 08:59:38 $ + * by : $Author: hilaire $ + */ +public class GraviteCPUE extends AbstractRule { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(GraviteCPUE.class); + + /** stocke la somme des prop initiales [str x month] */ + private MatrixND SommePropInitial = null; + /** stocke par strat*met, la dernière attractivite pour chaque mois + * [str x met x month] */ + private MatrixND HistoriqueCPUE = null; + + /** va permettre de stocker a chaque pas de temps la somme des attractivite [str] */ + MatrixND SommeCPUEstrat = null; + /** va permettre de stocker a chaque pas de temps la somme des proportions + * pour les metiers n'ayant pas d'attractivite [str] */ + MatrixND SommeProp = null; + + /** permet de stocker les CPUE standardiser [str x met] */ + private MatrixND catchPerUnitOfEffort = null; + + public String [] necessaryResult = { + // put here all necessary result for this rule + // example: + // ResultName.MATRIX_BIOMASS, + // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP, + ResultName.MATRIX_EFFORT_PER_STRATEGY_MET, + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + /** + * Permet d'afficher a l'utilisateur une aide sur la regle. + * @return L'aide ou la description de la regle + */ + public String getDescription() throws Exception { + // TODO + return _("GraviteCPUE"); + } + + /** + * function used to initialise MatrixND to NaN double + */ + private MapFunction nanFunction = new MapFunction() { + public double apply(double value) { + return Double.NaN; + } + }; + + /** + * Appelé au démarrage de la simulation, cette méthode permet d'initialiser + * des valeurs + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void init(SimulationContext context) throws Exception { + Date date = new Date(0); + + List<Strategy> strs = SiMatrix.getSiMatrix(context).getStrategies(date); + List<Metier> metiers = SiMatrix.getSiMatrix(context).getMetiers(date); + List<Month> months = Arrays.asList(Month.MONTH); + + SommePropInitial = MatrixFactory.getInstance().create("SommePropInitial", + new List[]{strs, months}, new String[]{"Strategies", "Months"}); + SommePropInitial.map(nanFunction); + + HistoriqueCPUE = MatrixFactory.getInstance().create("HistoriqueCPUE", + new List[]{strs, metiers, months}, new String[]{"Strategies", "Metiers", "Months"}); + HistoriqueCPUE.map(nanFunction); + + + SommeCPUEstrat = MatrixFactory.getInstance().create("SommeCPUEstrat", + new List[]{strs}, new String[]{"Strategies"}); + SommeCPUEstrat.map(nanFunction); + + SommeProp = MatrixFactory.getInstance().create("SommeProp", + new List[]{strs}, new String[]{"Strategies"}); + SommeProp.map(nanFunction); + + catchPerUnitOfEffort = MatrixFactory.getInstance().create("ValuePerUnitOfEffort", + new List[]{strs, metiers}, new String[]{"Strategies", "Metiers"}); + catchPerUnitOfEffort.map(nanFunction); + + for (Strategy str : strs) { + List<Metier> strMetiers = SiMatrix.getSiMatrix(context).getMetiers(str, date); + List<StrategyMonthInfo> infos = str.getStrategyMonthInfo(); + for (StrategyMonthInfo info : infos) { + double somme = 0; + for (Metier strMetier : strMetiers) { + somme += info.getProportionMetier(strMetier); + } + // FIXME soit on somme pour toutes les str le meme metier; donc pas de notion de str.getName dans la cle + // soit pour une str on somme tous ces metiers (mais ce doit etre 1; donc pas de notion de metier.getName dans la cle + SommePropInitial.setValue(str, info.getMonth(), somme); + } + } + +/* +var allStr = SiMatrice.getListStrategies(); + +for(var i=0; i<allStr.size(); i++){ + var str=allStr.get(i); + var metiers=str.getSetOfVessels().getMetiers(); + var ListeStrMonthInfos=str.getStrategyMonthInfos(); + for (var j=0; j<ListeStrMonthInfos.size();j++){ + var somme=0; + var StrMonthInfo=ListeStrMonthInfos.get(j); + for (var k=0;k<metiers.size();k++){ + var metier=metiers.get(k); + somme+=StrMonthInfo.getProportionMetier(metier); + } + this.p.SommePropInitial.put(new Chaine(str.getName()+"-"+metier.getNom()+"-"+StrMonthInfo.getMonth().getNumMois()),somme); + } +} + + //permet de stocker les CPUE standardiser +CatchperUnitOfEffort = MatrixFactory.create("ValuePerUnitOfEffort",new Array(allStr,SiMatrice.getListMetiers()),new Array("Strategies","Metiers")); +*/ + } + /** + * La condition qui doit etre vrai pour faire les actions + * @param simulation La simulation pour lequel on utilise cette regle + * @return vrai si on souhaite que les actions soit faites + */ + public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception { + // Il faut etre au moins au deuxieme pas de temps. + // FIXME 2eme pas de temps ou 2eme annee ? ici c 2eme annee et non pas 2eme mois + return date.getYear() > 0; + } + + /** + * Si la condition est vrai alors cette action est executée avant le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void preAction(SimulationContext context, Date date, Metier metier) throws Exception { + if (log.isDebugEnabled()) { + log.debug("Gravite Action avant metier:"+ metier + "date:"+ date); + } + + List<Strategy> strs = SiMatrix.getSiMatrix(context).getStrategies(date); + List<Population> populations = SiMatrix.getSiMatrix(context).getPopulations(date); + + double newPropDiv = 0; + + ResultStorage resultmanager = context.getSimulationStorage().getResultStorage(); + + //on commence par creer une matrice de capture par strategie met + MatrixND catchWeigthPerStrMet = null; + for (Population pop : populations){ + MatrixND temp = resultmanager.getMatrix( + date.previousYear(), + pop, + ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP); + // on somme sur les zones + temp=temp.sumOverDim(3); + // on somme sur les groupes + temp=temp.sumOverDim(2); + if (catchWeigthPerStrMet == null) { + catchWeigthPerStrMet = temp; + } else { + catchWeigthPerStrMet.add(temp); + } + } + + MatrixND effortPerStrMet = resultmanager.getMatrix( + date.previousYear(), + ResultName.MATRIX_EFFORT_PER_STRATEGY_MET); + + for (Strategy str : strs){ + List<Metier> strMetiers = SiMatrix.getSiMatrix(context).getMetiers(str, date); + for (Metier strMetier : strMetiers){ + double effort = effortPerStrMet.getValue(str, strMetier); + if (effort > 0){ + EffortDescription effortdesc = str.getSetOfVessels().getPossibleMetiers(strMetier); + int nombreop=effortdesc.getFishingOperation(); + int nombregear=effortdesc.getGearsNumberPerOperation(); + double param=strMetier.getGearParameterValueAsDouble(); + double facteur = param * nombreop * nombregear*strMetier.getGear().getStandardisationFactor() / 24.0; + //on restandardise l'effort + effort /= facteur; + //on recupere la capture tot + Object group = catchWeigthPerStrMet.getSemantics(2).get(0); + Object zone = catchWeigthPerStrMet.getSemantics(3).get(0); + + double capture = catchWeigthPerStrMet.getValue(str, strMetier, group, zone); + + catchPerUnitOfEffort.setValue(str, strMetier, capture/effort); + } + } + } + + + + for (Strategy str : strs){ + List<Metier> strMetiers = SiMatrix.getSiMatrix(context).getMetiers(str, date); + StrategyMonthInfo info = str.getStrategyMonthInfo(date.getMonth()); + + if(strMetiers.contains(metier)){ + // on verifie que le metier est bien un metier possible + double CPUE = Double.NaN; + if (SommeCPUEstrat.getValue(str) == Double.NaN){ + if (effortPerStrMet.getValue(str, metier) > 0){ + CPUE = catchPerUnitOfEffort.getValue(str, metier); + } + } + + if (CPUE != Double.NaN){ + if (log.isDebugEnabled()) { + log.debug("on a une CPUE l'année n-1, on la met dans l'historique\n" + info + " " + metier); + } + HistoriqueCPUE.setValue(str, metier, info.getMonth(), CPUE); + } else { + if (log.isDebugEnabled()) { + log.debug("ou calcul déjà fait ou pas de CPUE à l'année n-1"); + } + CPUE = HistoriqueCPUE.getValue(str, metier, info.getMonth()); + if (CPUE != Double.NaN) { + if (log.isDebugEnabled()) { + log.debug("on a une CPUE dans le passé: " + CPUE); + } + } else{ + if (log.isDebugEnabled()) { + log.debug("on a pas de CPUE dans le passé, on remet donc la poportion initiale"); + } + } + } + if (CPUE != Double.NaN) { + // si on a une CPUE, il faut aller voir l'attractivite des autres metiers: 2 cas de figure: + // soit on en retrouve une dans le passe qui est son attractivite + // soit on en retrouve pas et dans ce cas le, la proportion d'effort sera celle initiale de la db + // on a alors newProp=(1-sum(pmet1))*CPUE/somme(CPUEmet2) + // avec pmet1 la proprtion initiale pour les metiers pour lesquels on a pas retrouve de CPUE, CPUEmet2, la CPUE pour les + // metiers qui ont eu une CPUE dans le passe, et CPUE la CPUE du metier courant + if (SommeCPUEstrat.getValue(str) == Double.NaN){ + double SommeCPUE=0; + double PropTot=0; + for (Metier strMetier : strMetiers){ + double temp = Double.NaN; + if (effortPerStrMet.getValue(str, strMetier) > 0){ + temp = catchPerUnitOfEffort.getValue(str, strMetier); + } + if (temp != Double.NaN){ + if (log.isDebugEnabled()) { + log.debug("on a une CPUE l'année n-1, on l'ajoute à p.SommeCPUEstrat"); + } + HistoriqueCPUE.setValue(str, metier, info.getMonth(), temp); + SommeCPUE += temp; + } + else{ + if (log.isDebugEnabled()) { + log.debug("on a pas de CPUE l'année n-1, on regarde si il y en a dans le passé"); + } + temp = HistoriqueCPUE.getValue(str, metier, info.getMonth()); + if (temp != Double.NaN){ + if (log.isDebugEnabled()) { + log.debug("on a une CPUE dans le passé: "+temp); + } + SommeCPUE+=temp; + } + else{ + if (log.isDebugEnabled()) { + log.debug("on a pas de CPUE dans le passé, on l'ajoute donc à p.SommeProp"); + } + PropTot += info.getProportionMetier(strMetier); + } + } + } + SommeCPUEstrat.setValue(str, SommeCPUE); + SommeProp.setValue(str, PropTot); + } + + if (SommeCPUEstrat.getValue(str) > 0){ + newPropDiv = (SommePropInitial.getValue(str, info.getMonth()) - SommeProp.getValue(str)) + * CPUE / SommeCPUEstrat.getValue(str); + if (log.isDebugEnabled()) { + log.debug("newpropdiv: " + newPropDiv); + } + info.setProportionMetier(metier, newPropDiv); + } + else { // c'est le cas e priori quasi impossible oe y a toujours eu une CPUE nulle quelquesoit le metier, dans ce cas le on remet aussi la prop iniitiale + if (log.isDebugEnabled()) { + log.debug("aucun metier n'a d'attractivite, on remet la prop initiale"); + } + } + } + } + } + + if (log.isDebugEnabled()) { + log.debug("fin Gravite CPUEAction avant"); + } + +/* +writeln("Gravite Action avant metier:"+p.metier+ "date:"+ p.date); +var Chaine=Packages.java.lang.String; + + + +var month=p.date.getMois(); +var allStr = SiMatrice.getListStrategies(); +var newPropDiv=0.0; + +if (!p.CalculCatch){ + var resultmanager=control.getResultatManager(); + + //on commence par creer une matrice de capture par strategie met + var ListePopulation=SiMatrice.getListPopulations(); + pop=ListePopulation.get(0); + var CaptureParStrMet=resultmanager.getMatrix(new Packages.fr.ifremer.nodb.Date(p.date.getDate()-12),pop,"matriceCatchWeightPerStrategyMet"); + CaptureParStrMet=CaptureParStrMet.sumOverDim(3); + CaptureParStrMet=CaptureParStrMet.sumOverDim(2); + writeln(CaptureParStrMet); + for (var ipop=1;ipop<ListePopulation.size();ipop++){ + var pop=ListePopulation.get(ipop); + var temp=resultmanager.getMatrix(new Packages.fr.ifremer.nodb.Date(p.date.getDate()-12),pop,"matriceCatchWeightPerStrategyMet"); + temp=temp.sumOverDim(3); + temp=temp.sumOverDim(2); + writeln(temp); + CaptureParStrMet.add(temp); + writeln(CaptureParStrMet); + } + + var Effort=resultmanager.getMatrix(new Packages.fr.ifremer.nodb.Date(p.date.getDate()-12),"matriceEffortPerStrategyMet"); + writeln("on récupère la matrice d'effort"); + for (var iStrategie=allStr.iterator();iStrategie.hasNext();){ + var Strategie=iStrategie.next(); + var listeMet=Strategie.getSetOfVessels().getMetiers(); + for (imetier=listeMet.iterator();imetier.hasNext();){ + var metier=imetier.next(); + var effort=Effort.getValue(Strategie,metier); + if (effort>0){ + var effortdesc=Strategie.getSetOfVessels().getEffort(metier); + var nombreop=effortdesc.getFishingOperation(); + var nombregear=effortdesc.getGearsNumberPerOperation(); + var param=metier.getValeurParamControlable(); + var facteur=metier.getValeurParamControlable()*nombreop*nombregear/24.0; + //on restandardise l'effort + effort/=facteur; + //on recupere la capture tot + var dim3=new Packages.java.util.ArrayList(CaptureParStrMet.getSemantics(3)); + var dim2=new Packages.java.util.ArrayList(CaptureParStrMet.getSemantics(2)); + + var capture=CaptureParStrMet.getValue(Strategie,metier,dim2.get(0),dim3.get(0)); + + p.CatchperUnitOfEffort.setValue(Strategie,metier,capture/effort); + } + } + } + p.CalculCatch=true; +} + + + +for(var i=0; i<allStr.size(); i++){ + var str = allStr.get(i); + var strMonthInfo = str.getStrategyMonthInfo(month); + var propStrMet = strMonthInfo.getPropStrMetier(p.metier); + + if(str.getSetOfVessels().getMetiers().contains(p.metier)){ +//on verifie que le metier est bien un metier possible + var CPUE=null; + if (!p.SommeCPUEstrat.containsKey(new Chaine(str.getName()))){ + if (GravityModel.getEffortPerStrategyMet(str, p.metier, new Packages.fr.ifremer.nodb.Date(p.date.getDate()-12))>0){ + CPUE=p.CatchperUnitOfEffort.getValue(str,p.metier); + } + } + if (CPUE!=null){ + writeln("on a une CPUE l'année n-1, on la met dans l'historique"); + writeln(strMonthInfo+" "+p.metier); + p.HistoriqueCPUE.put(new Chaine(str.getName()+"-"+p.metier.getNom()+"-"+strMonthInfo.getMonth().getNumMois()),CPUE); + } + else{ + writeln ("ou calcul déjà fait ou pas de CPUE à l'année n-1"); + CPUE=p.HistoriqueCPUE.get(new Chaine(str.getName()+"-"+p.metier.getNom()+"-"+strMonthInfo.getMonth().getNumMois())); + if (CPUE!=null){ + writeln ("on a une CPUE dans le passé: "+CPUE); + } + else{ + writeln ("on a pas de CPUE dans le passé, on remet donc la poportion initiale"); + } + } + if (CPUE!=null) { +//si on a une CPUE, il faut aller voir l'attractivite des autres metiers: 2 cas de figure: +// soit on en retrouve une dans le passe qui est son attractivite +// soit on en retrouve pas et dans ce cas le, la proportion d'effort sera celle initiale de la db +//on a alors newProp=(1-sum(pmet1))*CPUE/somme(CPUEmet2) +//avec pmet1 la proprtion initiale pour les metiers pour lesquels on a pas retrouve de CPUE, CPUEmet2, la CPUE pour les +//metiers qui ont eu une CPUE dans le passe, et CPUE la CPUE du metier courant + if (!p.SommeCPUEstrat.containsKey(str.getName())){ + var SommeCPUE=0; + var PropTot=0; + var metiers=str.getSetOfVessels().getMetiers(); + for (var imetiers=metiers.iterator();imetiers.hasNext();){ + var metier=imetiers.next(); + var temp=null; + if (GravityModel.getEffortPerStrategyMet(str, metier, new Packages.fr.ifremer.nodb.Date(p.date.getDate()-12))>0){ + temp=p.CatchperUnitOfEffort.getValue(str,metier); + } + if (temp!=null){ + writeln("on a une CPUE l'année n-1, on l'ajoute à p.SommeCPUEstrat"); + p.HistoriqueCPUE.put(new Chaine(str.getName()+"-"+metier.getNom()+"-"+strMonthInfo.getMonth().getNumMois()),CPUE); + SommeCPUE+=temp; + } + else{ + writeln ("on a pas de CPUE l'année n-1, on regarde si il y en a dans le passé"); + temp=p.HistoriqueCPUE.get(new Chaine(str.getName()+"-"+metier.getNom()+"-"+strMonthInfo.getMonth().getNumMois())); + if (temp!=null){ + writeln ("on a une CPUE dans le passé: "+temp); + SommeCPUE+=temp; + } + else{ + writeln ("on a pas de CPUE dans le passé, on l'ajoute donc à p.SommeProp"); + PropTot+=strMonthInfo.getProportionMetier(metier); + } + } + } + p.SommeCPUEstrat.put(new Chaine(str.getName()),SommeCPUE); + p.SommeProp.put(new Chaine(str.getName()),PropTot); + } + if (p.SommeCPUEstrat.get(new Chaine(str.getName()))>0){ + newPropDiv = (p.SommePropInitial.get(new Chaine(str.getName()+"-"+strMonthInfo.getMonth().getNumMois()))-p.SommeProp.get(new Chaine(str.getName())))*CPUE/ p.SommeCPUEstrat.get(new Chaine(str.getName())); + writeln("newpropdiv: "+newPropDiv); + strMonthInfo.setProportionMetier(p.metier, new Packages.java.lang.Float(newPropDiv)); + } + else { // c'est le cas e priori quasi impossible oe y a toujours eu une CPUE nulle quelquesoit le metier, dans ce cas le on remet aussi la prop iniitiale + writeln("aucun metier n'a d'attractivite, on remet la prop initiale"); + } + } + } +} + +writeln("fin Gravite CPUEAction avant"); +return p.gestionMetier; +*/ + } + + /** + * Si la condition est vrai alors cette action est executée apres le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void postAction(SimulationContext context, Date date, Metier metier) throws Exception { + SommeCPUEstrat.map(nanFunction); + SommeProp.map(nanFunction); + catchPerUnitOfEffort.map(nanFunction); + } + +} Added: isis-fish/trunk/src/test/resources/test-database/rules/InterdictionEngin.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/rules/InterdictionEngin.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/rules/InterdictionEngin.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,279 @@ +package rules; + +import static org.codelutin.i18n.I18n._; +import static org.codelutin.i18n.I18n.n_; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import scripts.ResultName; +import scripts.SiMatrix; + +import java.io.Writer; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.codelutin.math.matrix.*; + +import fr.ifremer.isisfish.simulator.MetierMonitor; +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.types.Month; +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.rule.AbstractRule; +import fr.ifremer.isisfish.datastore.RegionStorage; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * InterdictionEngin.java + * + * Created: 30 novembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.1 $ + * + * Last update: $Date: 2007-01-24 18:25:34 $ + * by : $Author: bpoussin $ + */ +public class InterdictionEngin extends AbstractRule { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(InterdictionEngin.class); + + @Doc(value="do the doc of param gear") + public Gear param_gear = null; + @Doc(value="do the doc of param beginDate") + public Date param_beginDate = new Date(0); + @Doc(value="do the doc of param endDate") + public Date param_endDate = new Date(119); + @Doc(value="do the doc of param beginMonth") + public Month param_beginMonth = Month.JANUARY; + @Doc(value="do the doc of param endMonth") + public Month param_endMonth = Month.DECEMBER; + + public String [] necessaryResult = { + // put here all necessary result for this rule + // example: + // ResultName.MATRIX_BIOMASS, + // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + /** + * Permet d'afficher a l'utilisateur une aide sur la regle. + * @return L'aide ou la description de la regle + */ + public String getDescription() throws Exception { + return _("Prohibited gear"); + } + + /** + * Appelé au démarrage de la simulation, cette méthode permet d'initialiser + * des valeurs + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void init(SimulationContext context) throws Exception { + // TODO + } + /** + * La condition qui doit etre vrai pour faire les actions + * @param simulation La simulation pour lequel on utilise cette regle + * @return vrai si on souhaite que les actions soit faites + */ + public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception { + log.info("condition fermeture zone"); + boolean result = true; + Month mois = date.getMonth(); + log.info("mois:" + mois); + if(!(param_beginMonth.getMonthNumber()<=mois.getMonthNumber() + && mois.getMonthNumber()<=param_endMonth.getMonthNumber())) { + result = false; + } else { + log.info("on est dans l'espace des mois possible"); + if(date.before(param_beginDate)) { + result = false; + } else if(date.after(param_endDate)) { + result = false; + } else if (!metier.getGear().equals(param_gear)) { + result = false; + } + } + + return result; + // fin condition + + /* +writeln("condition fermeture zone"); +var result=true; +var mois = p.date.getMois().getNumMois(); +writeln("mois:"+mois); +if(!(p.moisDeb<=mois && mois<=p.moisFin)) + return false; +writeln("on est dans l'espace des mois possible"); +//on est dans l'espace des mois possible +if(p.date.before(p.dateDeb)) + return false; +if(p.date.after(p.dateFin)) + return false; +if (!p.metier.getEngin().equals(p.engin)) + return false; + + +return result; +*/ + } + + /** + * Si la condition est vrai alors cette action est executée avant le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void preAction(SimulationContext context, Date date, Metier metier) throws Exception { + log.info("le metier vise par l'interdiction : " + metier); + + MetierMonitor metierMon = context.getMetierMonitor(); + metierMon.addforbiddenMetier(metier); + + // récupère toutes les stratégies pratiquant le métier et pour lesquelles la proportion !=0 + SiMatrix siMatrix = SiMatrix.getSiMatrix(context); + List<Strategy> strs = siMatrix.getStrategies(date); + List<Strategy> ListeStrat = new ArrayList<Strategy>(); + + for (Strategy str : strs) { + double prop = str.getStrategyMonthInfo(date.getMonth()).getProportionMetier(metier); + if (prop != 0) { + ListeStrat.add(str); + } + } + + for (Strategy Strat : ListeStrat) { + StrategyMonthInfo StratMonthInfo = Strat.getStrategyMonthInfo(date.getMonth()); + + // 1er cas:l'effort est reporte sur un metier de la meme strategie, + // n'ayant pas l'espece comme capture principale et pechant avec le meme engin + List<EffortDescription> MetiersPossibles= new ArrayList<EffortDescription>(Strat.getSetOfVessels().getPossibleMetiers()); + + // on verifie que les metiers sont bien pratiques au mois courant, + // qu'ils n'ont pas le meme engin et qu'ils ne sont pas + // interdits par ailleurs + for (Iterator<EffortDescription> effort=MetiersPossibles.iterator(); effort.hasNext();) { + Metier met = effort.next().getPossibleMetiers(); + if (StratMonthInfo.getProportionMetier(met) == 0 + || met.getGear().equals(metier.getGear()) + || met.getName().equalsIgnoreCase("nonActivite") + || metierMon.isForbidden(metier, date.getMonth())){ + effort.remove(); + } + } + + // on repartit maintenant l'effort entre les differents metiers + // possibles dans la meme strategie si un metier possible existe bien + if (MetiersPossibles.size() != 0){ + int NbMetier=MetiersPossibles.size(); + for (EffortDescription effort : MetiersPossibles) { + Metier met = effort.getPossibleMetiers(); + double NouvelleProportion = + StratMonthInfo.getProportionMetier(met) + + (StratMonthInfo.getProportionMetier(metier) / NbMetier); + StratMonthInfo.setProportionMetier(met, NouvelleProportion); + } + StratMonthInfo.setProportionMetier(metier, 0); //le metier vise a alors une proportion nulle + } + // s'il n'y a pas de metier alternatif, on passe a nonActivite + else{ + MatrixND matNonActivite = metierMon.getOrCreateNoActivity(date, + ResultName.MATRIX_NO_ACTIVITY, + siMatrix.getStrategies(date), + siMatrix.getMetiers(date)); + matNonActivite.setValue(Strat, metier, StratMonthInfo.getProportionMetier(metier)); + StratMonthInfo.setProportionMetier(metier,0); + } + } + + // fin methode + + /* +var Chaine=Packages.java.lang.String; +writeln("Action avant"); +var metier=p.metier; +writeln("le metier vise par l'interdiction : "+metier); + + +MetiersInterdits.put(new Chaine(p.metier.getNom(),true)); +//récupère toutes les stratégies pratiquant le métier et pour lesquelles la proportion !=0 +var ListeStrat=new Packages.org.codelutin.dbobject.DBCollection(StrategyFactory); +var Vessels=SetOfVesselsFactory.findAllByRegion(p.metier.getRegion()); +for (var ves=0; ves<Vessels.size();ves++){ + if (Vessels.get(ves).getMetiers().contains(p.metier)){ + var listestrattemp=StrategyFactory.findAllBySetOfVessels(Vessels.get(ves)).copy(); + for (var strat=0;strat<listestrattemp.size();strat++){ + var proportion=listestrattemp.get(strat).getStrategyMonthInfo(p.date.getMois()).getProportionMetier(p.metier) //on recupere la proportion d'effort attribue au metier + if (proportion!=0){ + listestrattemp.removeAll(ListeStrat); + ListeStrat.addAll(listestrattemp);//permet d'obtenir une liste sans doublon + } + } + } +} + + + +for (iStrat=ListeStrat.iterator();iStrat.hasNext();){ + var Strat=iStrat.next(); + var StratMonthInfo=Strat.getStrategyMonthInfo(p.date.getMois()); + //1er cas:l'effort est reporte sur un metier de la meme strategie, n'ayant pas l'espece comme capture principale et pechant avec le meme engin + var MetiersPossibles=Strat.getSetOfVessels().getMetiers().copy(); + + //on verifie que les metiers sont bien pratiques au mois courant, qu'ils n'ont pas le meme ont le meme engin et qu'ils ne sont pas interdits par ailleurs + for (var imet=MetiersPossibles.iterator();imet.hasNext();){ + var met=imet.next(); + if (StratMonthInfo.getProportionMetier(met)==0 || met.getEngin().equals(p.metier.getEngin()) || met.getNom()=="nonActivite" || MetiersInterdits.containsKey(new Chaine(met.getNom())) || MetiersInterditsPresimu.containsKey(new Chaine(met.getNom()+"-"+p.date.getMois().getNumMois()))){ + MetiersPossibles.remove(met); + } + } + + //on repartit maintenant l'effort entre les differents metiers possibles dans la meme strategie si un metier possible existe bien + if (MetiersPossibles.size()!=0){ + var NbMetier=MetiersPossibles.size(); + for (imet=MetiersPossibles.iterator();imet.hasNext();){ + met=imet.next(); + var NouvelleProportion=StratMonthInfo.getProportionMetier(met)+(StratMonthInfo.getProportionMetier(p.metier)/NbMetier); + StratMonthInfo.setProportionMetier(met, new Packages.java.lang.Float(NouvelleProportion)) + } + StratMonthInfo.setProportionMetier(p.metier, new Packages.java.lang.Float(0)) //le metier vise a alors une proportion nulle + } +//s'il n'y a pas de metier alternatif, on passe a nonActivite + else{ + var matNonActivite=nonActivite.get(p.date); + var nonactivite=matNonActivite!=null; + if (!nonactivite){ + matNonActivite=MatrixFactory.create("nonActivite",new Array(SiMatrice.getListStrategies(),SiMatrice.getListMetiers()) + ,new Array("Strategies", "Metiers")); + nonActivite.put(p.date,matNonActivite); + } + + matNonActivite.setValue(Strat,p.metier,InfoMois.getProportionMetier(p.metier)); + StratMonthInfo.setProportionMetier(p.metier,new Packages.java.lang.Float(0)); + } +} +return p.gestionMetier; +*/ + } + + /** + * Si la condition est vrai alors cette action est executée apres le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void postAction(SimulationContext context, Date date, Metier metier) throws Exception { + // nothing + } + +} Added: isis-fish/trunk/src/test/resources/test-database/rules/InterdictionEnginPreSimu.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/rules/InterdictionEnginPreSimu.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/rules/InterdictionEnginPreSimu.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,301 @@ +package rules; + +import static org.codelutin.i18n.I18n._; +import static org.codelutin.i18n.I18n.n_; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import scripts.ResultName; + +import java.io.Writer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.codelutin.math.matrix.*; + +import fr.ifremer.isisfish.simulator.MetierMonitor; +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.types.Month; +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.rule.AbstractRule; +import fr.ifremer.isisfish.datastore.RegionStorage; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * InterdictionEngin.java + * + * Created: 30 novembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.1 $ + * + * Last update: $Date: 2007-01-24 18:25:34 $ + * by : $Author: bpoussin $ + */ +public class InterdictionEnginPreSimu extends AbstractRule { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(InterdictionEnginPreSimu.class); + + @Doc(value="do the doc of param gear") + public Gear param_gear = null; + @Doc(value="do the doc of param beginMonth") + public Month param_beginMonth = Month.JANUARY; + @Doc(value="do the doc of param endMonth") + public Month param_endMonth = Month.DECEMBER; + + protected Map<Month, MatrixND> tableNonActivite = new HashMap<Month, MatrixND>(); + protected boolean affectNonActivite = false; + + public String [] necessaryResult = { + // put here all necessary result for this rule + // example: + // ResultName.MATRIX_BIOMASS, + // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + /** + * Permet d'afficher a l'utilisateur une aide sur la regle. + * @return L'aide ou la description de la regle + */ + public String getDescription() throws Exception { + return _("Prohibited gear"); + } + + /** + * Appelé au démarrage de la simulation, cette méthode permet d'initialiser + * des valeurs + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void init(SimulationContext context) throws Exception { + MetierMonitor metierMon = context.getMetierMonitor(); + + Month moisDeb = param_beginMonth; + Month moisFin = param_endMonth; + Gear EnginInterdit = param_gear; + + log.info("nom de l'engin interdit "+EnginInterdit.getName()); + FisheryRegion RegionSimu = RegionStorage.getFisheryRegion(context.getDB()); + List<Metier> ListeMetiers = RegionSimu.getMetier(); + + for (Metier metier : ListeMetiers) { + if (metier.getGear().equals(EnginInterdit)) { + //récupère toutes les stratégies pratiquant le métier et pour lesquelles la proportion !=0 + List<Strategy> ListeStrat=RegionSimu.getStrategy(); + for (Strategy Strat : ListeStrat){ + SetOfVessels vessels = Strat.getSetOfVessels(); + if (vessels.getPossibleMetiers(metier) != null){ + for (Month mois : Month.getMonths(param_beginMonth, param_endMonth)) { + StrategyMonthInfo StratMonthInfo = Strat.getStrategyMonthInfo(mois); + metierMon.addforbiddenMetier(metier, mois); + + //1er cas:l'effort est reporte sur un metier de la meme strategie, n'ayant pas l'espece comme capture principale et pechant avec le meme engin + List<EffortDescription> MetiersPossibles = + new ArrayList<EffortDescription>(Strat.getSetOfVessels().getPossibleMetiers()); + + // on verifie que les metiers sont bien pratiques au mois courant, + // qu'ils n'ont pas le meme ont le meme engin et qu'ils ne sont + // pas interdits par ailleurs + for (Iterator<EffortDescription> effort=MetiersPossibles.iterator(); effort.hasNext();) { + Metier met = effort.next().getPossibleMetiers(); + if (StratMonthInfo.getProportionMetier(met) == 0 + || met.getGear().equals(metier.getGear()) + || met.getName().equalsIgnoreCase("nonActivite") + || metierMon.isForbidden(metier, mois)){ + effort.remove(); + } + } + + //on repartit maintenant l'effort entre les differents metiers possibles dans la meme strategie si un metier possible existe bien + if (MetiersPossibles.size() != 0){ + int NbMetier=MetiersPossibles.size(); + for (EffortDescription effort : MetiersPossibles) { + Metier met = effort.getPossibleMetiers(); + double NouvelleProportion = + StratMonthInfo.getProportionMetier(met) + + (StratMonthInfo.getProportionMetier(metier) / NbMetier); + StratMonthInfo.setProportionMetier(met, NouvelleProportion); + } + StratMonthInfo.setProportionMetier(metier, 0); //le metier vise a alors une proportion nulle + } + else{ + log.info("debut reportNonActivite"); + // on regarde si on a déjà une entrée pour le mois courant + MatrixND matNonActiviteMois=tableNonActivite.get(mois); + if (matNonActiviteMois == null){ + matNonActiviteMois = MatrixFactory.getInstance().create( + ResultName.MATRIX_NO_ACTIVITY, + new List[]{ListeStrat, ListeMetiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + tableNonActivite.put(mois, matNonActiviteMois); + } + + matNonActiviteMois.setValue(Strat, metier, StratMonthInfo.getProportionMetier(metier)); + log.info("fin reportNonActivite"); + + StratMonthInfo.setProportionMetier(metier, 0); + } + } + } + } + } + } + + // fin methode + + /* +this.param = param; + +//construction de p +this.p = new Object(); +this.p.paramRegle = this.param; +this.p.tableNonActivite=new Packages.java.util.HashMap(); +this.p.affectNonActivite=false; + +//attention: cette règle de gestion ne fonctionne que si le changement a lieu pour toutes +//les années de simulation + + +var moisDeb=this.param.getValue("moisDeb"); //entrez le mois debut de fermeture +var moisFin=this.param.getValue("moisFin");//entrez le mois de fin de fermeture +var EnginInterdit=this.param.getValue("engin"); + +writeln("nom de l'engin interdit "+EnginInterdit.getNom()); +var RegionSimu=EnginInterdit.getRegion(); +var ListeMetiers=MetierFactory.findAllByRegion(RegionSimu); + +for (var imetier=ListeMetiers.iterator();imetier.hasNext();){ + var metier=imetier.next(); + if (metier.getEngin().equals(EnginInterdit)){ + //récupère toutes les stratégies pratiquant le métier et pour lesquelles la proportion !=0 + var ListeStrat=SiMatrice.getListStrategies(); + for (iStrat=ListeStrat.iterator();iStrat.hasNext();){ + var Strat=iStrat.next(); + var vessels=Strat.getSetOfVessels(); + if (vessels.getMetiers().contains(metier)){ + for (var imois=moisDeb; imois<=moisFin;imois++){ + var mois=new Packages.fr.ifremer.nodb.Mois(imois); + var StratMonthInfo=Strat.getStrategyMonthInfo(mois); + MetiersInterditsPresimu.put(new Chaine(metier.getNom()+"-"+mois.getNumMois()),true); + //1er cas:l'effort est reporte sur un metier de la meme strategie, n'ayant pas l'espece comme capture principale et pechant avec le meme engin + var MetiersPossibles=Strat.getSetOfVessels().getMetiers().copy(); + var MetiersPossibles2=Strat.getSetOfVessels().getMetiers().copy(); + //on verifie que les metiers sont bien pratiques au mois courant, qu'ils n'ont pas le meme ont le meme engin et qu'ils ne sont pas interdits par ailleurs + for (var imet=MetiersPossibles2.iterator();imet.hasNext();){ + var met=imet.next(); + if (StratMonthInfo.getProportionMetier(met)==0 || met.getEngin().equals(metier.getEngin()) || met.getNom()=="nonActivite" || MetiersInterditsPresimu.containsKey(new Chaine(met.getNom()+"-"+mois.getNumMois()))){ + MetiersPossibles.remove(met); + } + } + + //on repartit maintenant l'effort entre les differents metiers possibles dans la meme strategie si un metier possible existe bien + if (MetiersPossibles.size()!=0){ + var NbMetier=MetiersPossibles.size(); + for (imet=MetiersPossibles.iterator();imet.hasNext();){ + met=imet.next(); + var NouvelleProportion=StratMonthInfo.getProportionMetier(met)+(StratMonthInfo.getProportionMetier(metier)/NbMetier); + StratMonthInfo.setProportionMetier(met, new Packages.java.lang.Float(NouvelleProportion)) + } + StratMonthInfo.setProportionMetier(metier, new Packages.java.lang.Float(0)) //le metier vise a alors une proportion nulle + } + //s'il n'y a pas de metier alternatif, on passe e nonActivite + else{ + p.tableNonActivite=Regle_action_lib.reportNonActivite(p.tableNonActivite, Strat, metier, mois, StratMonthInfo.getProportionMetier(metier)); + StratMonthInfo.setProportionMetier(metier,new Packages.java.lang.Float(0)); + } + } + } + } + } +} + */ + } + /** + * La condition qui doit etre vrai pour faire les actions + * @param simulation La simulation pour lequel on utilise cette regle + * @return vrai si on souhaite que les actions soit faites + */ + public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception { + boolean result = false; + MatrixND mat = tableNonActivite.get(date.getMonth()); + if (mat != null && affectNonActivite == false) { + result = true; + } + return result; + // fin + + /* +var mat=p.tableNonActivite.get(p.date.getMois()); +writeln(p.affectNonActivite); +if(oldValue != undefined) + return oldValue; +else if (mat!=null && p.affectNonActivite==false){ + return true; +} +else {return false;} +*/ + } + + /** + * Si la condition est vrai alors cette action est executée avant le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void preAction(SimulationContext context, Date date, Metier metier) throws Exception { + // on ne doit le faire qu'une seul fois quelque soit le nombre de metier + affectNonActivite=true; + MatrixND mat = tableNonActivite.get(date.getMonth()); + + MetierMonitor metierMon = context.getMetierMonitor(); + MatrixND noActivity = metierMon.getNoActivity(date); + + if (noActivity == null){ + metierMon.setNoActivity(date, mat.copy()); + } + else{ + noActivity = noActivity.add(mat); + } + // fin + + /* +p.affectNonActivite=true; +var mat=p.tableNonActivite.get(p.date.getMois()); +var matNonActivite=nonActivite.get(p.date); +var nonactivite=matNonActivite!=null; +if (!nonactivite){ + nonActivite.put(p.date,mat); +} +else{ + matNonActivite=matNonActivite.add(mat); +} +return p.gestionMetier; +*/ + } + + /** + * Si la condition est vrai alors cette action est executée apres le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void postAction(SimulationContext context, Date date, Metier metier) throws Exception { + affectNonActivite = false; + + /* + p.affectNonActivite=false; +return p.gestionMetier; + */ + } + +} Added: isis-fish/trunk/src/test/resources/test-database/rules/RecrutementLangoustine.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/rules/RecrutementLangoustine.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/rules/RecrutementLangoustine.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,184 @@ +package rules; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import scripts.ResultName; + +import java.io.Writer; + +import org.codelutin.math.matrix.*; +import org.codelutin.topia.TopiaContext; +import org.codelutin.util.StringUtil; + +import fr.ifremer.isisfish.IsisFishDAOHelper; +import fr.ifremer.isisfish.simulator.PopulationMonitor; +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.types.Month; +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.rule.AbstractRule; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * RecrutementLangoustine.java + * + * Created: 22 mars 2007 + * + * @author stephanie MAHEVAS <smahevas at ifremer.fr> + * @version $Revision: 1.1 $ + * + * Last update: $Date: 2007-03-22 17:33:56 $ + * by : $Author: bpoussin $ + */ +public class RecrutementLangoustine extends AbstractRule { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(RecrutementLangoustine.class); + + @Doc(value="do the doc of param recrut1998") + public double param_recrut1998 =0; + @Doc(value="do the doc of param recrut1999") + public double param_recrut1999 =0; + @Doc(value="do the doc of param recrut2000") + public double param_recrut2000 =0; + @Doc(value="do the doc of param recrut2001") + public double param_recrut2001 =0; + @Doc(value="do the doc of param recrut2002") + public double param_recrut2002 =0; + @Doc(value="do the doc of param recrut2003") + public double param_recrut2003 =0; + @Doc(value="do the doc of param recrut2004") + public double param_recrut2004 =0; + @Doc(value="do the doc of param recrut2005") + public double param_recrut2005 =0; + + public double [] recru = null; + + public String [] necessaryResult = { + // put here all necessary result for this rule + // example: + // ResultName.MATRIX_BIOMASS, + // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + /** + * Permet d'afficher a l'utilisateur une aide sur la regle. + * @return L'aide ou la description de la regle + */ + public String getDescription() throws Exception { + // TODO + return _("TODO description rule"); + } + + /** + * Appelé au démarrage de la simulation, cette méthode permet d'initialiser + * des valeurs + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void init(SimulationContext context) throws Exception { + // remarque on pourrait aussi avoir un seul parametre de regle + // par exemple param_recru_depuis_1998 = "0;0;0;0;0;0;0;0"; + // on ferait alors + // recru = StringUtil.toArrayDouble(param_recru_depuis_1998.split(";")); + + recru = new double[]{ + param_recrut1998, + param_recrut1999, + param_recrut2000, + param_recrut2001, + param_recrut2002, + param_recrut2003, + param_recrut2004, + param_recrut2005, + }; + } + /** + * La condition qui doit etre vrai pour faire les actions + * @param simulation La simulation pour lequel on utilise cette regle + * @return vrai si on souhaite que les actions soit faites + */ + public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception { + boolean result = false; + if (date.getMonth().equals(Month.SEPTEMBER) || + date.getMonth().equals(Month.OCTOBER) + || date.getMonth().equals(Month.NOVEMBER) + ||date.getMonth().equals(Month.DECEMBER)) { + result = true; + } + return result; +/* +writeln("recrutement CIEM"); +var mois = p.date.getMois().getNumMois(); +//si le recrutement a lieu en octobre +if( mois==8 ||mois==9 || mois==10 || mois==11){ +//??&& p.oprfaite==false{ +var result = true; +} + return result ; +*/ + + } + + /** + * Si la condition est vrai alors cette action est executée avant +le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void preAction(SimulationContext context, Date date, Metier metier) throws Exception { + TopiaContext db = context.getDB(); + + PopulationDAO popDao = IsisFishDAOHelper.getPopulationDAO(db); + Population pop = popDao.findByName("nephrops"); + PopulationGroup group0 = pop.getPopulationGroup().get(0); + + ZoneDAO zoneDao = IsisFishDAOHelper.getZoneDAO(db); + Zone zone1 = zoneDao.findByName("zone L21E7"); + Zone zone2 = zoneDao.findByName("zone L21E8"); + Zone zone3 = zoneDao.findByName("zone L22E6"); + Zone zone4 = zoneDao.findByName("zone L22E7"); + Zone zone5 = zoneDao.findByName("zone L23E5"); + Zone zone6 = zoneDao.findByName("zone L23E6"); + Zone zone7 = zoneDao.findByName("zone L23E7"); + Zone zone8 = zoneDao.findByName("zone L24E5"); + Zone zone9 = zoneDao.findByName("zone L24E6"); + + int year = date.getYear(); + MatrixND matN = context.getPopulationMonitor().getN(pop); + + double coefR =4/(Math.exp(-0.6/12))*(1+ Math.exp(-0.3/12)+ Math.exp(-0.6/12)+ Math.exp(-0.9/12)); + + double R = recru[year] * coefR / 9.0; + + matN.setValue(group0, zone1, R); + matN.setValue(group0, zone2, R); + matN.setValue(group0, zone3, R); + matN.setValue(group0, zone4, R); + matN.setValue(group0, zone5, R); + matN.setValue(group0, zone6, R); + matN.setValue(group0, zone7, R); + matN.setValue(group0, zone8, R); + matN.setValue(group0, zone9, R); + + } + + /** + * Si la condition est vrai alors cette action est executée apres le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void postAction(SimulationContext context, Date date, Metier metier) throws Exception { + // TODO + } + +} \ No newline at end of file Added: isis-fish/trunk/src/test/resources/test-database/rules/TACpoids.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/rules/TACpoids.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/rules/TACpoids.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,307 @@ +package rules; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.codelutin.math.matrix.MatrixFactory; +import org.codelutin.math.matrix.MatrixIterator; +import org.codelutin.math.matrix.MatrixND; + +import scripts.ResultName; +import scripts.RuleUtil; +import scripts.SiMatrix; + +import fr.ifremer.isisfish.entities.EffortDescription; +import fr.ifremer.isisfish.entities.Metier; +import fr.ifremer.isisfish.entities.Population; +import fr.ifremer.isisfish.entities.Species; +import fr.ifremer.isisfish.entities.Strategy; +import fr.ifremer.isisfish.entities.StrategyMonthInfo; +import fr.ifremer.isisfish.entities.TargetSpecies; +import fr.ifremer.isisfish.rule.AbstractRule; +import fr.ifremer.isisfish.simulator.MetierMonitor; +import fr.ifremer.isisfish.simulator.PopulationMonitor; +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.types.Month; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * TAC.java + * + * Created: 7 septembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.5 $ + * + * Last update: $Date: 2007-11-20 15:50:09 $ + * by : $Author: bpoussin $ + */ + +/** + * TAC peut-etre utilisé pour les différents TAC, en proportion des effectifs + * et/ou avec survie ou non. + * + * <li>Pour utiliser le tac proportionnel, il faut mettre dans le parametre propTac + * une valeur > 0, le TAC sera alors recalculé a chaque mois de janvier. + * <li>Pour utiliser la survie il faut mettre dans le paramètre propSurvie + * une valeur > 0, automatiquement les suvie seront ajouté aux effectifs + * + */ +public class TACpoids extends AbstractRule { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(TACpoids.class); + + @Doc(value="do the doc of param species") + public Species param_species = null; + @Doc(value="do the doc of param beginDate") + public Date param_beginDate = new Date(0); + @Doc(value="do the doc of param endDate") + public Date param_endDate = new Date(22); + @Doc(value="do the doc of param propSurvie") + public double param_propSurvie = 0; + @Doc(value="do the doc of param propTac") + public double param_propTac = 0; + + /** TAC in tonne */ + public double param_tacInTons = 0; + + boolean affectation = false; + + protected String [] necessaryResult = { + // put here all necessary result for this rule + // example: + // ResultName.MATRIX_BIOMASS, + // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + }; + + /** + * @return the necessaryResult + */ + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + /** + * Permet d'afficher a l'utilisateur une aide sur la regle. + * @return L'aide ou la description de la regle + */ + public String getDescription() { + return _("TAC weight in tons.\nIf you want survival discard use propSurvie other than 0.\nIf you wish TAC computed use propTac other than 0."); + } + + /** + * Appelé au démarrage de la simulation, cette méthode permet d'initialiser + * des valeurs + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void init(SimulationContext context) throws Exception { + } + + /** + * La condition qui doit etre vrai pour faire les actions + * @param simulation La simulation pour lequel on utilise cette regle + * @return vrai si on souhaite que les actions soit faites + */ + public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception { + // read species in current session + param_species = (Species)context.getDB().findByTopiaId(param_species.getTopiaId()); + + // on fait le calcul du tac si nécessaire + if (param_propTac > 0 && date.getMonth().equals(Month.JANUARY)){ + PopulationMonitor popMon = context.getPopulationMonitor(); + param_tacInTons = popMon.getBiomass(param_species) * param_propTac; + } + + boolean result = false; + if(date.before(param_beginDate)) { + result = false; + } else if(date.after(param_endDate)) { + result = false; + } else { + TargetSpecies ts = metier.getMetierSeasonInfo(date.getMonth()).getSpeciesTargetSpecies(param_species); + if (ts != null) { + double catchTons = RuleUtil.getTotalCatchTons(context, param_species, date); + log.info("[TAC] catchTons = " + catchTons + " >= param_tacInTons:" + param_tacInTons ); + if (catchTons >= param_tacInTons) { + result = true; + } + } + } + return result; + } + + /** + * Si la condition est vrai alors cette action est executée avant le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void preAction(SimulationContext context, Date date, Metier metier) throws Exception { + affectation = false; + log.info("[TAC] preAction for: " + metier); + + TargetSpecies ts = metier.getMetierSeasonInfo(date.getMonth()).getSpeciesTargetSpecies(param_species); + if(ts != null && ts.getPrimaryCatch()) { + // recupere tous les metiers qui ont l'espece en capture principale =>metiers vises + List<Metier> aimedMetiers = context.getDB().find("select distinct(metierSeasonInfo.metier) " + + "from fr.ifremer.isisfish.entities.TargetSpecies " + + "where species=? and primaryCatch=true", param_species); + + log.info("aimed Metier: " + aimedMetiers); + context.getMetierMonitor().addforbiddenMetier(metier); + + //récupere toutes les stratégies pratiquant le métier et pour lesquelles la proportion !=0 + SiMatrix siMatrix = SiMatrix.getSiMatrix(context); + Set<Strategy> strs = new HashSet<Strategy>(); + for (Strategy str : siMatrix.getStrategies(date)) { + double prop = str.getStrategyMonthInfo(date.getMonth()).getProportionMetier(metier); + if (prop != 0) { + strs.add(str); + } + } + + for (Strategy str : strs){ + StrategyMonthInfo smi = str.getStrategyMonthInfo(date.getMonth()); + + // 1er cas de figure: l'effort est reporte sur un metier de la + // meme strategie, n'ayant pas l'espece comme capture principale + // et pechant avec le meme engin + Set<Metier> possibleMetierCase1 = new HashSet<Metier>(); + // second cas de figure: on cherche un metier de substitution + // sans condition sur les engins, mais qui soit pratique + Set<Metier> possibleMetierCase2 = new HashSet<Metier>(); + // 3 eme cas de figure: on cherche des metiers non vises, + // sans consideration sur les engins, et pour lesquels la + // proportion peut etre nulle + Set<Metier> possibleMetierCase3 = new HashSet<Metier>(); + + for (EffortDescription effort : str.getSetOfVessels().getPossibleMetiers()) { + Metier newMetier = effort.getPossibleMetiers(); + if ( + !aimedMetiers.contains(newMetier) + && !metier.getName().equalsIgnoreCase("nonActiviy") + && !metier.getName().equalsIgnoreCase("nonActivie") + && !context.getMetierMonitor().getForbiddenMetier().contains(newMetier) + ) { + possibleMetierCase3.add(newMetier); + + if (smi.getProportionMetier(newMetier) != 0) { + possibleMetierCase2.add(newMetier); + + if (metier.getGear().equals(newMetier.getGear())) { + possibleMetierCase1.add(newMetier); + } + } + } + } + + Set<Metier> possibleMetier = null; + if (possibleMetierCase1.size() != 0){ + log.info("[TAC] Use case 1"); + possibleMetier = possibleMetierCase1; + } else if (possibleMetierCase2.size() != 0) { + log.info("[TAC] Use case 2"); + possibleMetier = possibleMetierCase2; + } else if (possibleMetierCase3.size() != 0){ + log.info("[TAC] Use case 3"); + possibleMetier = possibleMetierCase3; + } + + if (possibleMetier != null) { + // on repartit maintenant l'effort entre les differents metiers + // possibles dans la meme strategie si un metier possible existe + // bien la repartion est proportionnelle a l'effort deja alloue + // dans la strategie + + double somme=0; + for (Metier met : possibleMetierCase1) { + somme += smi.getProportionMetier(met); + } + for (Metier met : possibleMetierCase1) { + double newProportion = + smi.getProportionMetier(met) + + (smi.getProportionMetier(metier) + * smi.getProportionMetier(met) / somme); + smi.setProportionMetier(met, newProportion); + } + smi.setProportionMetier(metier, 0); //le metier vise a alors une proportion nulle + } else{ + log.info("[TAC] Use no activity"); + + // sinon on met tout dans le metier nonActivite + MetierMonitor metierMon = context.getMetierMonitor(); + MatrixND mat = metierMon.getOrCreateNoActivity(date, + ResultName.MATRIX_NO_ACTIVITY, + siMatrix.getStrategies(date), + siMatrix.getMetiers(date)); + mat.setValue(str, metier, smi.getProportionMetier(metier)); + + smi.getProportionMetier().setValue(metier, 0); + } + } + } + } + + /** + * Si la condition est vrai alors cette action est executée apres le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void postAction(SimulationContext context, Date date, Metier metier) throws Exception { + log.info("[TAC] postAction for: " + metier); + TargetSpecies ts = metier.getMetierSeasonInfo(date.getMonth()).getSpeciesTargetSpecies(param_species); + if(ts != null){ + if (!affectation){ + // ATTENTION + // les captures pour cette metapop ne sont plus du qu'au metier + // pour qui l'espece est secondaire: elles sont affectees aux + // rejets + + //pb : ne se fait pas par metier + // il faut une matrice pour chaques pas de temps qui stocke les + // rejets par metier, par metapop et par classes d'age (comme + // pour les captures) + ////// + PopulationMonitor popMon = context.getPopulationMonitor(); + for (Population pop : param_species.getPopulation()) { + // si on a deja une matrice rejet on le vide (elle vient + // forcement de la regle taille minimale or si le tac est + // atteint, tout va dorenavent dans les rejets et on mais + // TOUTES les captures dans les rejets + MatrixND discard = popMon.getDiscard(date, pop); + if (discard != null) { + discard.mults(0); + } + + discard = popMon.getCatch(pop).copy(); + discard.setName(ResultName.MATRIX_DISCARDS_PER_STR_MET); + popMon.addDiscard(date, pop, discard); + log.info("[TAC] add discard for " + pop + ": " + discard); + + if (param_propSurvie > 0) { + MatrixND eff = popMon.getN(pop); + //on réajoute les survivants aux effectifs + for (MatrixIterator i=discard.iterator(); i.next();){ + Object [] coord = i.getSemanticsCoordinates(); + eff.setValue(coord[2],coord[3], + eff.getValue(coord[2],coord[3])+i.getValue()*param_propSurvie); + } + } + + } + + // on a affecte une fois cette meta pop au rejet il ne faut pas + // le refaire + affectation=true; + } + } + } + +} Added: isis-fish/trunk/src/test/resources/test-database/rules/TailleMin.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/rules/TailleMin.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/rules/TailleMin.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,260 @@ +package rules; + +import static org.codelutin.i18n.I18n._; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import scripts.ResultName; +import scripts.SiMatrix; + +import java.io.Writer; +import java.util.List; + +import org.codelutin.math.matrix.*; + +import fr.ifremer.isisfish.simulator.PopulationMonitor; +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.entities.*; +import fr.ifremer.isisfish.rule.AbstractRule; +import fr.ifremer.isisfish.datastore.SimulationStorage; +import fr.ifremer.isisfish.datastore.ResultStorage; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * TailleMin.java + * + * Created: 30 novembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.1 $ + * + * Last update: $Date: 2007-01-24 18:25:34 $ + * by : $Author: bpoussin $ + */ + +/** + * Cette methode remplace aussi TailleMinSurvieRejet si propSurvie est > 0 + */ +public class TailleMin extends AbstractRule { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(TailleMin.class); + + @Doc(value="do the doc of param beginDate") + public Date param_beginDate = new Date(0); + @Doc(value="do the doc of param endDate") + public Date param_endDate = new Date(119); + @Doc(value="do the doc of param species") + public Species param_species = null; + @Doc(value="do the doc of param TailleMin") + public double param_TailleMin = 27; + @Doc(value="do the doc of param propSurvie") + public double param_propSurvie = 0; + + public String [] necessaryResult = { + // put here all necessary result for this rule + // example: + // ResultName.MATRIX_BIOMASS, + // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + }; + + public String[] getNecessaryResult() { + return this.necessaryResult; + } + + /** + * Permet d'afficher a l'utilisateur une aide sur la regle. + * @return L'aide ou la description de la regle + */ + public String getDescription() throws Exception { + // TODO + return _("TODO description rule"); + } + + /** + * Appelé au démarrage de la simulation, cette méthode permet d'initialiser + * des valeurs + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void init(SimulationContext context) throws Exception { + } + + /** + * @param context + * @param date + * @param param_species + * @param metier + * @return + */ + private boolean isCaptureDate(Date date, Species species, Metier metier) { + MetierSeasonInfo info = metier.getMetierSeasonInfo(date.getMonth()); + TargetSpecies target = info.getSpeciesTargetSpecies(species); + boolean result = target != null; + + return result; + } + + /** + * La condition qui doit etre vrai pour faire les actions + * @param simulation La simulation pour lequel on utilise cette regle + * @return vrai si on souhaite que les actions soit faites + */ + public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception { + log.info("Recherche si la taille Minimale s'applique"); + boolean result = true; + if (date.before(param_beginDate)) { + result = false; + } else if (date.after(param_endDate)) { + result = false; + } else if (isCaptureDate(date, param_species, metier) != true) { + result=false; + } + + log.info("fin de condition TailleMin:" + result); + return result; + + // fin + + /* + +writeln("Recherche si la taille Minimale s'applique (oldValue="+oldValue); +var metier=p.metier; +var result = true; +if(oldValue != undefined) + result = oldValue; +else if (Regle_libUtil.isCaptureDate(p.date,p.metapop, metier)!=true) + result=false; +else if(p.date.before(p.dateDeb)) + result = false; +else if(p.date.after(p.dateFin)) + result = false; + +writeln("fin de condition TailleMin:"+result); +return result; +*/ + } + + /** + * Si la condition est vrai alors cette action est executée avant le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void preAction(SimulationContext context, Date date, Metier metier) throws Exception { + // nothing + } + + /** + * Si la condition est vrai alors cette action est executée apres le pas + * de temps de la simulation. + * @param simulation La simulation pour lequel on utilise cette regle + */ + public void postAction(SimulationContext context, Date date, Metier metier) throws Exception { + log.info("*$*$*$* TailleMin.actionApres:" + date + " metapop:" + param_species + " metier:" + metier); + + if(isCaptureDate(date, param_species, metier)){ + log.info("*$*$*$* ok affecte capture infÃ?rieure Ã? TailleMin au rejet"); + // ATTENTION + // les captures pour cette metapop ne sont plus du qu'au metier pour qui + // l'espece est secondaire: elles sont affectees aux rejets + + //pb : ne se fait pas par metier + //il faut une matrice pour chaques pas de temps qui stocke les rejets + //par metier, par metapop et par classes d'age (comme pour les captures) + ////// + log.info("deb de affecterCaptureREJETTailleMin"); + + PopulationMonitor popMon = context.getPopulationMonitor(); + SiMatrix siMatrix = SiMatrix.getSiMatrix(context); + List<Population> pops = siMatrix.getPopulations(date); + + for (Population pop : pops) { + if (pop.getSpecies().equals(param_species)) { + if (popMon.getDiscard(date, pop) == null) { + MatrixND discard = popMon.getCatch(pop).copy(); + MatrixND eff = popMon.getN(pop); + + for (MatrixIterator i=discard.iterator(); i.next();) { + Object [] coordonnees = i.getSemanticsCoordinates(); + PopulationGroup group = (PopulationGroup)coordonnees[2]; + if (group.getLength() >= param_TailleMin) { + i.setValue(0); + } else if (param_propSurvie > 0) { + eff.setValue(coordonnees[2], coordonnees[3], + eff.getValue(coordonnees[2], coordonnees[3]) + + i.getValue() * param_propSurvie); + } + } + discard.setName(ResultName.MATRIX_DISCARDS_PER_STR_MET); + popMon.addDiscard(date, pop, discard); + } + } + } + + log.info("fin de affecterCaptureRejetTailleMin"); + + //on a affecte une fois cette meta pop au rejet il ne faut pas le refaire + } + + // fin + + /* + + + +writeln("*$*$*$* TailleMin.actionApres:"+p.date+" metapop:"+p.metapop+" metier:"+p.metier); +if(Regle_libUtil.isCaptureDate(p.date,p.metapop, p.metier)){ + writeln("*$*$*$* ok affecte capture infÃ?rieure Ã? TailleMin au rejet"); + // ATTENTION + // les captures pour cette metapop ne sont plus du qu'au metier pour qui + // l'espece est secondaire: elles sont affectees aux rejets + + //pb : ne se fait pas par metier + //il faut une matrice pour chaques pas de temps qui stocke les rejets + //par metier, par metapop et par classes d'age (comme pour les captures) + ////// +writeln("deb de affecterCaptureREJETTailleMin"); +var suivi = null; + +//recherche du suivi pour les pop qui ont une certaine meta pop +for(var i=0; i< suiviePop.size(); i++){ + if(suiviePop.get(i).getPop().getMetaPopulation().equals(metapop)){ + suivi = suiviePop.get(i); + var populations=suivi.getPop(); + + //si on a pas deja creer le rejet on le cree et on en fait un resultat + var matRejet = suivi.getRejet(date); + if (matRejet==null){ + var matRejetBis = MatrixFactory.create(suivi.getCapture()); + var eff=suivi.getN(); +//on encapsule les objets des 4 dimensions de la matrice capture + for (var iiterateur=matRejetBis.iterator();iiterateur.next();){ + var coordonnees=iiterateur.getSemanticsCoordinates(); + var classe=coordonnees[2]; + if (classe.getLongueur()>=TailleMin){ + iiterateur.setValue(0); + } + else if (param_propSurvie > 0) { + eff.setValue(coordonnees[2],coordonnees[3],eff.getValue(coordonnees[2],coordonnees[3])+iiterateur.getValue()*proportion); + } + } + matRejetBis.setName("Rejet par metier"); + suivi.addRejet(date,matRejetBis); + } + } +} + + +writeln("fin de affecterCaptureRejetTailleMin"); + + + //on a affecte une fois cette meta pop au rejet il ne faut pas le refaire +} + +return p.gestionMetier; +*/ + } + +} Added: isis-fish/trunk/src/test/resources/test-database/scripts/GravityModel.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/scripts/GravityModel.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/scripts/GravityModel.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,1311 @@ +/* *##% + * 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. + *##%*/ + +/* * + * GravityModel.java + * + * Created: 4 sept. 06 15:49:08 + * + * @author poussin + * @version $Revision: 1.9 $ + * + * Last update: $Date: 2007-03-01 17:16:12 $ + * by : $Author: bpoussin $ + */ + +package scripts; + +import static org.codelutin.i18n.I18n._; +import static org.codelutin.i18n.I18n.n_; + +import java.util.Collection; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.codelutin.math.matrix.MatrixFactory; +import org.codelutin.math.matrix.MatrixND; +import org.codelutin.topia.TopiaContext; +import org.codelutin.topia.TopiaException; + +import fr.ifremer.isisfish.datastore.ResultStorage; +import fr.ifremer.isisfish.datastore.StorageException; +import fr.ifremer.isisfish.entities.EffortDescription; +import fr.ifremer.isisfish.entities.Metier; +import fr.ifremer.isisfish.entities.Population; +import fr.ifremer.isisfish.entities.PopulationGroup; +import fr.ifremer.isisfish.entities.SetOfVessels; +import fr.ifremer.isisfish.entities.Strategy; +import fr.ifremer.isisfish.entities.Zone; +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.types.Month; +import fr.ifremer.isisfish.types.TimeUnit; + + +/** + * @author poussin + * + */ + +public class GravityModel { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(GravityModel.class); + + protected SimulationContext context = null; + protected TopiaContext db = null; + protected SiMatrix siMatrix = null; + protected ResultStorage resultManager = null; + + /** + * Method used to get GravityModel used for simulation + * @param context context simulation + * @return GravityModel or null if no GravityModel created for simulation + */ + public static GravityModel getGravityModel(SimulationContext context) { + GravityModel result = (GravityModel)context.getValue(GravityModel.class.getName()); + return result; + } + + private static void setGravityModel(SimulationContext context, GravityModel gravityModel) { + context.setValue(GravityModel.class.getName(), gravityModel); + } + + + public GravityModel(SimulationContext context, SiMatrix siMatrix) throws TopiaException, StorageException{ + this.context = context; + this.db = context.getDB(); + this.resultManager = context.getSimulationStorage().getResultStorage(); + this.siMatrix = siMatrix; + setGravityModel(context, this); + } + + ////////////////////////////////////////////////////////////////////// + // Matrice de Revenue et Cout + ////////////////////////////////////////////////////////////////////// + + ////////////////////////////////////////////////////////////////////// + // MatrixFishingTimePerMonthPerVessel + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixFishingTimePerMonthPerVessel(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + List<Metier> metiers = siMatrix.getMetiers(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_FISHING_TIME_PER_MONTH_PER_VESSEL, + new List[]{strategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = siMatrix.getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = fishingTimePerMonthPerVessel(str, metier, date); + result.setValue(str, metier, value); + } + } + +// for(Strategy str : strategies){ +// metiers = siMatrix.getMetiers(str, date); +// for(Metier metier : metiers) { +// double value = fishingTimePerMonthPerVessel(str, metier, date); +// result.setValue(str, metier, value); +// } +// } + + return result; + } + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * FishingTimePerMonthPerVessel[str,met,month] = FishingTimePerTrip[str,met,month]NbTripsPerMonth[str,month] + + * @param str + * @param metier + * @param date + * @return + */ + private double fishingTimePerMonthPerVessel(Strategy str, Metier metier, Date date) { + Month month = date.getMonth(); + double timePerTrip = siMatrix.fishingTimePerTrip(str, metier, date); + double nbTrip = str.getStrategyMonthInfo(month).getNumberOfTrips(); + return timePerTrip * nbTrip; + } + + + ////////////////////////////////////////////////////////////////////// + // matrixFuelCostsOfTravelPerVessel + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixFuelCostsOfTravelPerVessel(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + List<Metier> metiers = siMatrix.getMetiers(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_FUEL_COSTS_OF_TRAVEL_PER_VESSEL, + new List[]{strategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = siMatrix.getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = fuelCostsOfTravelPerVessel(str, metier, date); + result.setValue(str, metier, value); + } + } +// for(Strategy str : strategies){ +// metiers = siMatrix.getMetiers(str, date); +// for(Metier metier : metiers) { +// double value = fuelCostsOfTravelPerVessel(str, metier, date); +// result.setValue(str, metier, value); +// } +// } + + return result; + } + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * FuelCostsOfTravelPerVessel[sov,met,month]?=?NbTripsPerMonth[str,month]*TravelTimePerTrip[sov,met,month]*UnitFuelCostsOfTravel[vt] + * + * @param str + * @param metier + * @param date + * @return + */ + private double fuelCostsOfTravelPerVessel(Strategy str, Metier metier, Date date) { + Month month = date.getMonth(); + double nbTrip = str.getStrategyMonthInfo(month).getNumberOfTrips(); + + Collection<Zone> zone = metier.getMetierSeasonInfo(month).getZone(); + // TODO: verifier que travelTime est bien en heure, car le unitFuelCost est l'unite par heure + double travelTime = siMatrix.travelTimePerTrip(str.getSetOfVessels(), zone); + double unitFuelCost = str.getSetOfVessels().getVesselType().getUnitFuelCostOfTravel(); + + return nbTrip * travelTime * unitFuelCost; + } + + ////////////////////////////////////////////////////////////////////// + // matrixCostsOfFishingPerVessel + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixCostsOfFishingPerVessel(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + List<Metier> metiers = siMatrix.getMetiers(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_COSTS_OF_FISHING_PER_VESSEL, + new List[]{strategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = siMatrix.getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = costsOfFishingPerVessel(str, metier, date); + result.setValue(str, metier, value); + } + } +// for(Strategy str : strategies){ +// metiers = siMatrix.getMetiers(str, date); +// for(Metier metier : metiers) { +// double value = costsOfFishingPerVessel(str, metier, date); +// result.setValue(str, metier, value); +// } +// } + + return result; + } + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * CostsOfFishingPerVessel[str,met,month]= FishingTimePerMonthPerVessel [str,met,month] {NbFishingOperationsPerDay[sov,met] UnitCostsOfFishing[sov,met] / 24} + * + * @param str + * @param metier + * @param date + * @return + */ + private double costsOfFishingPerVessel(Strategy str, Metier metier, Date date) { + double fishingTime = fishingTimePerMonthPerVessel(str, metier, date); + + EffortDescription effort = str.getSetOfVessels().getPossibleMetiers(metier); + int nbOperation = 0; + double unitCostOfFishing = 0; + if(effort != null){ + nbOperation = effort.getFishingOperation(); + unitCostOfFishing = effort.getUnitCostOfFishing(); + } + + return fishingTime * ( nbOperation * unitCostOfFishing / TimeUnit.HOUR_PER_DAY); + } + + ////////////////////////////////////////////////////////////////////// + // matrixFuelCostsPerVessel + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixFuelCostsPerVessel(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + List<Metier> metiers = siMatrix.getMetiers(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_FUEL_COSTS_PER_VESSEL, + new List[]{strategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = siMatrix.getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = fuelCostsPerVessel(str, metier, date); + result.setValue(str, metier, value); + } + } +// for(Strategy str : strategies){ +// metiers = siMatrix.getMetiers(str, date); +// for(Metier metier : metiers) { +// double value = fuelCostsPerVessel(str, metier, date); +// result.setValue(str, metier, value); +// } +// } + + return result; + } + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * FuelCostsPerVessel[str,met,month] = FuelCostsOfTravelPerVessel [sov,met,month] + CostsOfFishingPerVessel [str,met,month] + * + * @param str + * @param metier + * @param date + * @return + */ + private double fuelCostsPerVessel(Strategy str, Metier metier, Date date) { + double fuelCosts = fuelCostsOfTravelPerVessel(str, metier, date); + double costsOfFishing = costsOfFishingPerVessel(str, metier, date); + + return fuelCosts + costsOfFishing; + } + + ////////////////////////////////////////////////////////////////////// + // matrixRepairAndMaintenanceGearCostsPerVessel + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixRepairAndMaintenanceGearCostsPerVessel(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + List<Metier> metiers = siMatrix.getMetiers(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_REPAIR_AND_MAINTENANCE_GEAR_COSTS_PER_VESSEL, + new List[]{strategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = siMatrix.getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = repairAndMaintenanceGearCostsPerVessel(str, metier, date); + result.setValue(str, metier, value); + } + } +// for(Strategy str : strategies){ +// metiers = siMatrix.getMetiers(str, date); +// for(Metier metier : metiers) { +// double value = repairAndMaintenanceGearCostsPerVessel(str, metier, date); +// result.setValue(str, metier, value); +// } +// } + + return result; + } + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * RepairAndMaintenanceGearCostsPerVessel[str,met,month]?=?FishingTimePerMonthPerVessel[str,met,month] *RepairAndMaintenanceGearCostsPerDay[sov,met]/NbHoursPerDay + * + * @param str + * @param metier + * @param date + * @return + */ + private double repairAndMaintenanceGearCostsPerVessel(Strategy str, Metier metier, Date date) { + double fishingTime = fishingTimePerMonthPerVessel(str, metier, date); + + EffortDescription effort = str.getSetOfVessels().getPossibleMetiers(metier); + + double repair = 0; + if(effort != null){ + repair = effort.getRepairAndMaintenanceGearCost(); + } + // FIXME verifier qu'il faut bien retourner 0, si pas d'effort + return fishingTime * repair / TimeUnit.HOUR_PER_DAY; + } + + ////////////////////////////////////////////////////////////////////// + // matrixOtherRunningCostsPerVessel + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixOtherRunningCostsPerVessel(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + List<Metier> metiers = siMatrix.getMetiers(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_OTHER_RUNNING_COSTS_PER_VESSEL, + new List[]{strategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = siMatrix.getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = otherRunningCostsPerVessel(str, metier, date); + result.setValue(str, metier, value); + } + } +// for(Strategy str : strategies){ +// metiers = siMatrix.getMetiers(str, date); +// for(Metier metier : metiers) { +// double value = otherRunningCostsPerVessel(str, metier, date); +// result.setValue(str, metier, value); +// } +// } + + return result; + } + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * OtherRunningCostsPerVessel[str,met,month]=?FishingTimePerMonthPerVessel[str,met,month]*OtherRunningCostsPerDay[sov,met]/ NbHoursPerDay + * + * @param str + * @param metier + * @param date + * @return + */ + private double otherRunningCostsPerVessel(Strategy str, Metier metier, Date date) { + double fishingTime = fishingTimePerMonthPerVessel(str, metier, date); + + EffortDescription effort = str.getSetOfVessels().getPossibleMetiers(metier); + + double otherCosts = 0; + if(effort != null){ + otherCosts = effort.getOtherRunningCost(); + } + // FIXME verifier qu'il faut bien retourner 0, si pas d'effort + return fishingTime * otherCosts / TimeUnit.HOUR_PER_DAY; + } + + ////////////////////////////////////////////////////////////////////// + // matrixSharedNotFixedCostsPerVessel + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixSharedNotFixedCostsPerVessel(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + List<Metier> metiers = siMatrix.getMetiers(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_SHARED_NOT_FIXED_COSTS_PER_VESSEL, + new List[]{strategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = siMatrix.getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = sharedNotFixedCostsPerVessel(str, metier, date); + result.setValue(str, metier, value); + } + } +// for(Strategy str : strategies){ +// metiers = siMatrix.getMetiers(str, date); +// for(Metier metier : metiers) { +// double value = sharedNotFixedCostsPerVessel(str, metier, date); +// result.setValue(str, metier, value); +// } +// } + + return result; + } + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * SharedNotFixedCostsPerVessel[str,met,month]=?FuelCostsPerVessel[str,met,month] +?OtherRunningCostsPerVessel[str,met,month] + * + * @param str + * @param metier + * @param date + * @return + */ + private double sharedNotFixedCostsPerVessel(Strategy str, Metier metier, Date date) { + double fuelCostsPerVessel = fuelCostsPerVessel(str, metier, date); + double otherRunningCostsPerVessel = otherRunningCostsPerVessel(str, metier, date); + + return fuelCostsPerVessel + otherRunningCostsPerVessel; + } + + ////////////////////////////////////////////////////////////////////// + // matrixSharedFixedCostsPerVesselPerMet + ////////////////////////////////////////////////////////////////////// +// Supprime avec Steph le 20070227 +// public MatrixND matrixSharedFixedCostsPerVesselPerMet(Date date) throws TopiaException{ +// List<Strategy> strategies = siMatrix.getStrategies(date); +// +// MatrixND result = MatrixFactory.getInstance().create( +// ResultName.MATRIX_SHARED_FIXED_COSTS_PER_VESSEL_PER_MET, +// new List[]{strategies}, +// new String[]{n_("Strategies")}); +// +// for (int s=0; s < strategies.size(); s++) { +// Strategy str = strategies.get(s); +// double value = sharedFixedCostsPerVesselPerMet(str, date); +// result.setValue(s, value); +// } +//// for(Strategy str : strategies){ +//// double value = sharedFixedCostsPerVesselPerMet(str, date); +//// result.setValue(str, value); +//// } +// +// return result; +// } +// +// /** +// * implant? suivant document ModifTable3PourBP25-07-2006.doc +// * SharedFixedCostsPerVesselPerMet [str,month]=FixedCostsPerMonth[sov]/NbMet[sov] +// * +// * @param str +// * @param date +// * @return +// */ +// private double sharedFixedCostsPerVesselPerMet(Strategy str, Date date) { +// SetOfVessels sov = str.getSetOfVessels(); +// double fixedCosts = sov.getFixedCosts(); +// int nbMet = sov.sizePossibleMetiers(); +// +// return fixedCosts / (double)nbMet; +// } + + ////////////////////////////////////////////////////////////////////// + // matrixGrossValueOfLandingsPerSpeciesPerStrategyMet + ////////////////////////////////////////////////////////////////////// + + + public MatrixND matrixGrossValueOfLandingsPerSpeciesPerStrategyMet(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + List<Metier> metiers = siMatrix.getMetiers(date); + List<Population> pops = siMatrix.getPopulations(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_GROSS_VALUE_OF_LANDINGS_PER_SPECIES_PER_STRATEGY_MET, + new List[]{strategies, metiers, pops}, + new String[]{n_("Strategies"), n_("Metiers"), n_("Populations")}); + + for (int p=0; p < pops.size(); p++) { + Population pop = pops.get(p); + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = siMatrix.getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = grossValueOfLandingsPerSpeciesPerStrategyMet(str, metier, pop, date); + result.setValue(str, metier, pop, value); + } + } + } + +// for(Population pop : pops){ +// for(Strategy str : strategies){ +// metiers = siMatrix.getMetiers(str, date); +// for(Metier metier : metiers) { +// double value = grossValueOfLandingsPerSpeciesPerStrategyMet(str, metier, pop, date); +// result.setValue(str, metier, pop, value); +// } +// } +// } + + return result; + } + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * GrossValueOfLandingsPerSpeciesPerStrategyMet[str,met,pop,month]?=?sum over classes_cl of [PricePerKg(pop,cl, t)* (CatchWeightPerStrategyMet [str,met,pop,cl,month] ?DiscardsWeightPerStrategyMet [str,met,pop,cl,mo +nth] + * GrossValueOfLandingsPerSpeciesPerStrategyMet[str,met,pop,month] = sum over classes_cl of [PricePerKg(pop,cl, t)* (CatchWeightPerStrategyMet [str,met,pop,cl,month] -DiscardsWeightPerStrategyMet [str,met,pop,cl,mo +nth])] + * + * @param str + * @param metier + * @param pop + * @param date + * @return + */ + private double grossValueOfLandingsPerSpeciesPerStrategyMet(Strategy str, Metier metier, Population pop, Date date) { + List<PopulationGroup> groups = pop.getPopulationGroup(); + double result = 0; + for(PopulationGroup group : groups){ + double price = group.getPrice(); + Collection<Zone> zones = pop.getPopulationZone(); + for(Zone zone : zones){ + double catchWeight = getCatchWeightPerStrMetPerZonePop(str, metier, group, zone, date); + double discardsWeight = getDiscardsWeightPerStrMet(str, metier, group, zone, date); + // FIXME demander/verifier que ce le bon calcule + result += price * (catchWeight - discardsWeight); + } + } + return result; + } + + /** + * @param str + * @param metier + * @param group + * @param zone + * @param date + * @return + */ + private double getCatchWeightPerStrMetPerZonePop(Strategy str, Metier metier, PopulationGroup group, Zone zone, Date date) { + MatrixND mat = resultManager.getMatrix(date, group.getPopulation(), ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP); + double result = 0; + if(mat != null){ + result = mat.getValue(str, metier, group, zone); + } + return result; + } + + /** + * @param str + * @param metier + * @param group + * @param zone + * @param date + * @return + */ + private double getDiscardsWeightPerStrMet(Strategy str, Metier metier, PopulationGroup group, Zone zone, Date date) { + MatrixND mat = resultManager.getMatrix(date, group.getPopulation(), ResultName.MATRIX_DISCARDS_WEIGHT_PER_STR_MET_PER_ZONE_POP); + double result = 0; + if(mat != null){ + result = mat.getValue(str, metier, group, zone); + } + return result; + } + + ////////////////////////////////////////////////////////////////////// + // matrixGrossValueOfLandingsPerStrategyMet + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixGrossValueOfLandingsPerStrategyMet(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + List<Metier> metiers = siMatrix.getMetiers(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_GROSS_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + new List[]{strategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = siMatrix.getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = grossValueOfLandingsPerStrategyMet(str, metier, date); + result.setValue(str, metier, value); + } + } +// for(Strategy str : strategies){ +// metiers = siMatrix.getMetiers(str, date); +// for(Metier metier : metiers) { +// double value = grossValueOfLandingsPerStrategyMet(str, metier, date); +// result.setValue(str, metier, value); +// } +// } + + return result; + } + + /** + * @param str + * @param metier + * @param date + * @return + * @throws TopiaException + */ + private double grossValueOfLandingsPerStrategyMet(Strategy str, Metier metier, Date date) throws TopiaException { + List<Population> pops = siMatrix.getPopulations(date); + double result = 0; + for(int i=0; i<pops.size(); i++){ + Population pop = (Population)pops.get(i); + result += grossValueOfLandingsPerSpeciesPerStrategyMet(str, metier, pop, date); + } + return result; + } + + ////////////////////////////////////////////////////////////////////// + // matrixGrossValueOfLandingsPerStrategyMetPerVessel + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixGrossValueOfLandingsPerStrategyMetPerVessel(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + List<Metier> metiers = siMatrix.getMetiers(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_GROSS_VALUE_OF_LANDINGS_PER_STRATEGY_MET_PER_VESSEL, + new List[]{strategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = siMatrix.getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = grossValueOfLandingsPerStrategyMetPerVessel(str, metier, date); + result.setValue(str, metier, value); + } + } +// for(Strategy str : strategies){ +// metiers = siMatrix.getMetiers(str, date); +// for(Metier metier : metiers) { +// double value = grossValueOfLandingsPerStrategyMetPerVessel(str, metier, date); +// result.setValue(str, metier, value); +// } +// } + + return result; + } + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * GrossValueOfLandingsPerStrategyMetPerVessel[str,met,month]?= GrossValueOfLandingsPerStrategyMet[str,met,month]?/[PropNbVessels(str,sov)*NbVesselsSetOfVessels(sov)] + * + * @param str + * @param metier + * @param date + * @return + * @throws TopiaException + */ + private double grossValueOfLandingsPerStrategyMetPerVessel(Strategy str, Metier metier, Date date) throws TopiaException { + double grossValueOfLandingsPerStrategyMet = grossValueOfLandingsPerStrategyMet(str, metier, date); + // FIXME verifier que c bien cette donn?e qu'il faut utiliser dans le doc: PropNbVessels(str, sov) + double proportionSetOfVessels = str.getProportionSetOfVessels(); + double numberOfVessels = str.getSetOfVessels().getNumberOfVessels(); + + double grossValueOfLandingsOtherSpeciesPerStrategyMet = grossValueOfLandingsOtherSpeciesPerStrategyMet(str,metier,date); + + + return (grossValueOfLandingsPerStrategyMet + grossValueOfLandingsOtherSpeciesPerStrategyMet) / (proportionSetOfVessels * numberOfVessels); + } + + ////////////////////////////////////////////////////////////////////// + // matrixNetValueOfLandingsPerStrategyMet + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixNetValueOfLandingsPerStrategyMet(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + List<Metier> metiers = siMatrix.getMetiers(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, + new List[]{strategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = siMatrix.getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = netValueOfLandingsPerStrategyMet(str, metier, date); + result.setValue(str, metier, value); + } + } +// for(Strategy str : strategies){ +// metiers = siMatrix.getMetiers(str, date); +// for(Metier metier : metiers) { +// double value = netValueOfLandingsPerStrategyMet(str, metier, date); +// result.setValue(str, metier, value); +// } +// } + + return result; + } + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * NetValueOfLandingsPerStrategyMet[str,met,month]?=?GrossValueOfLandingsPerStrategyMet[str,met,month]?(1-LandingCostRate[str,met]?) + * + * @param str + * @param metier + * @param date + * @return + * @throws TopiaException + */ + private double netValueOfLandingsPerStrategyMet(Strategy str, Metier metier, Date date) throws TopiaException { + double grossValue = grossValueOfLandingsPerStrategyMet(str, metier, date); + EffortDescription effort = str.getSetOfVessels().getPossibleMetiers(metier); + double landingCost = 1; + // FIXME demander si le metier n'a pas d'effort s'il faut que landingCost soit bien a 1 + if(effort != null){ + landingCost -= effort.getLandingCosts(); + } + + double grossValueOfLandingsOtherSpeciesPerStrategyMet = grossValueOfLandingsOtherSpeciesPerStrategyMet(str,metier,date); + + double result = (grossValue + grossValueOfLandingsOtherSpeciesPerStrategyMet)* landingCost; + return result; + } + + private double grossValueOfLandingsOtherSpeciesPerStrategyMet(Strategy str, Metier metier, Date date) throws TopiaException { + // FIXME evaluer l'equation dans suivant le doc des equations + return 0; + } + + ////////////////////////////////////////////////////////////////////// + // matrixNetValueOfLandingsPerStrategyMetPerVessel + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixNetValueOfLandingsPerStrategyMetPerVessel(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + List<Metier> metiers = siMatrix.getMetiers(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET_PER_VESSEL, + new List[]{strategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = siMatrix.getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = netValueOfLandingsPerStrategyMetPerVessel(str, metier, date); + result.setValue(str, metier, value); + } + } +// for(Strategy str : strategies){ +// metiers = siMatrix.getMetiers(str, date); +// for(Metier metier : metiers) { +// double value = netValueOfLandingsPerStrategyMetPerVessel(str, metier, date); +// result.setValue(str, metier, value); +// } +// } + + return result; + } + + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * NetValueOfLandingsPerStrategyMetPerVessel[str,met,month]?=?NetValueOfLandingsPerStrategyMet[str,met,month]?/[PropNbVessels(str,sov)*NbVesselsSetOfVessels(sov)] + * + * @param str + * @param metier + * @param date + * @return + * @throws TopiaException + */ + private double netValueOfLandingsPerStrategyMetPerVessel(Strategy str, Metier metier, Date date) throws TopiaException { + double netValueOfLandingsPerStrategyMet = netValueOfLandingsPerStrategyMet(str, metier, date); + // FIXME verifier que c bien cette donn?e qu'il faut utiliser dans le doc: PropNbVessels(str, sov) + double proportionSetOfVessels = str.getProportionSetOfVessels(); + double numberOfVessels = str.getSetOfVessels().getNumberOfVessels(); + + return netValueOfLandingsPerStrategyMet / (proportionSetOfVessels * numberOfVessels); + } + + ////////////////////////////////////////////////////////////////////// + // matrixNetRenevueToSharePerStrategyMetPerVessel + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixNetRenevueToSharePerStrategyMetPerVessel(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + List<Metier> metiers = siMatrix.getMetiers(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_NET_RENEVUE_TO_SHARE_PER_STRATEGY_MET_PER_VESSEL, + new List[]{strategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = siMatrix.getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = netRenevueToSharePerStrategyMetPerVessel(str, metier, date); + result.setValue(str, metier, value); + } + } +// for(Strategy str : strategies){ +// metiers = siMatrix.getMetiers(str, date); +// for(Metier metier : metiers) { +// double value = netRenevueToSharePerStrategyMetPerVessel(str, metier, date); +// result.setValue(str, metier, value); +// } +// } + + return result; + } + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * NetRevenueToSharePerStrategyMetPerVessel[str,met,month]?=?NetValueOfLandingsPerStrategyMetPerVessel[str,met,month]?-?SharedNotFixedCostsPerVessel [str,met,month]*PropStr(str,met,month) - SharedFixedCostsPerVessel +PerMet[str,month] + * + * @param str + * @param metier + * @param date + * @return + * @throws TopiaException + */ + private double netRenevueToSharePerStrategyMetPerVessel(Strategy str, Metier metier, Date date) throws TopiaException { + double netRenevueToSharePerStrategyMetPerVessel = netValueOfLandingsPerStrategyMetPerVessel(str, metier, date); + double sharedNotFixedCostsPerVessel = sharedNotFixedCostsPerVessel(str, metier, date); + double propStr = str.getStrategyMonthInfo(date.getMonth()).getProportionMetier(metier); + + double result = netRenevueToSharePerStrategyMetPerVessel - sharedNotFixedCostsPerVessel * propStr; + return result; + } + + ////////////////////////////////////////////////////////////////////// + // matrixCrewSharePerStrategyMetPerVessel + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixCrewSharePerStrategyMetPerVessel(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + List<Metier> metiers = siMatrix.getMetiers(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_CREW_SHARE_PER_STRATEGY_MET_PER_VESSEL, + new List[]{strategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = siMatrix.getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = crewSharePerStrategyMetPerVessel(str, metier, date); + result.setValue(str, metier, value); + } + } +// for(Strategy str : strategies){ +// metiers = siMatrix.getMetiers(str, date); +// for(Metier metier : metiers) { +// double value = crewSharePerStrategyMetPerVessel(str, metier, date); +// result.setValue(str, metier, value); +// } +// } + + return result; + } + + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * CrewSharePerStrategyMetPerVessel[str,met,month]?=?NetRevenueToSharePerStrategyMetPerVessel[str,met,month]*CrewShareRate[sov,met] + * + * @param str + * @param metier + * @param date + * @return + * @throws TopiaException + */ + private double crewSharePerStrategyMetPerVessel(Strategy str, Metier metier, Date date) throws TopiaException { + double netRenevueToShare = netRenevueToSharePerStrategyMetPerVessel(str, metier, date); + + EffortDescription effort = str.getSetOfVessels().getPossibleMetiers(metier); + + double crewShareRate = 0; + if(effort != null){ + crewShareRate = effort.getCrewShareRate(); + } + // FIXME verifier qu'il faut bien retourner 0, si pas d'effort + return netRenevueToShare * crewShareRate; + } + + ////////////////////////////////////////////////////////////////////// + // matrixOwnerMarginOverVariableCostsPerStrategyMetPerVessel + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixOwnerMarginOverVariableCostsPerStrategyMetPerVessel(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + List<Metier> metiers = siMatrix.getMetiers(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_OWNER_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_MET_PER_VESSEL, + new List[]{strategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = siMatrix.getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = ownerMarginOverVariableCostsPerStrategyMetPerVessel(str, metier, date); + result.setValue(str, metier, value); + } + } +// for(Strategy str : strategies){ +// metiers = siMatrix.getMetiers(str, date); +// for(Metier metier : metiers) { +// double value = ownerMarginOverVariableCostsPerStrategyMetPerVessel(str, metier, date); +// result.setValue(str, metier, value); +// } +// } + + return result; + } + + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * OwnerMarginOverVariableCostsPerStrategyMetPerVessel[str,met,month] = NetRevenueToSharePerStrategyMetPerVessel[str,met,month]?- CrewSharePerStrategyMetPerVessel[str,met,month]?- RepairAndMaintenanceGearCostsPerVes +sel[str,met,month]?* PropStr(str,met,month) + * + * @param str + * @param metier + * @param date + * @return + * @throws TopiaException + */ + private double ownerMarginOverVariableCostsPerStrategyMetPerVessel(Strategy str, Metier metier, Date date) throws TopiaException { + double netRenevueToShare = netRenevueToSharePerStrategyMetPerVessel(str, metier, date); + double crewShare = crewSharePerStrategyMetPerVessel(str, metier, date); + double repair = repairAndMaintenanceGearCostsPerVessel(str, metier, date); + double propStr = str.getStrategyMonthInfo(date.getMonth()).getProportionMetier(metier); + + return netRenevueToShare - crewShare - repair * propStr; + } + + + ////////////////////////////////////////////////////////////////////// + // matrixVesselMarginOverVariableCostsPerStrategyMetPerVessel + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixVesselMarginOverVariableCostsPerStrategyMetPerVessel(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + List<Metier> metiers = siMatrix.getMetiers(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_VESSEL_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_MET_PER_VESSEL, + new List[]{strategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = siMatrix.getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = vesselMarginOverVariableCostsPerStrategyMetPerVessel(str, metier, date); + result.setValue(str, metier, value); + } + } +// for(Strategy str : strategies){ +// metiers = siMatrix.getMetiers(str, date); +// for(Metier metier : metiers) { +// double value = vesselMarginOverVariableCostsPerStrategyMetPerVessel(str, metier, date); +// result.setValue(str, metier, value); +// } +// } + + return result; + } + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * VesselMarginOverVariableCostsPerStrategyMetPerVessel?[str,met,month]?=NetRevenueToSharePerStrategyMetPerVessel[str,met,month]- RepairAndMaintenanceGearCostsPerVessel [str,met,month]?* PropStr(str,met,month) + * + * @param str + * @param metier + * @param date + * @return + * @throws TopiaException + */ + private double vesselMarginOverVariableCostsPerStrategyMetPerVessel(Strategy str, Metier metier, Date date) throws TopiaException { + double netRenevueToShare = netRenevueToSharePerStrategyMetPerVessel(str, metier, date); + double repair = repairAndMaintenanceGearCostsPerVessel(str, metier, date); + double propStr = str.getStrategyMonthInfo(date.getMonth()).getProportionMetier(metier); + + return netRenevueToShare - repair * propStr; + } + + ////////////////////////////////////////////////////////////////////// + // matrixOwnerMarginOverVariableCostsPerStrategyPerVessel + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixOwnerMarginOverVariableCostsPerStrategyPerVessel(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_OWNER_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_PER_VESSEL, + new List[]{strategies}, + new String[]{n_("Strategies")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + double value = ownerMarginOverVariableCostsPerStrategyPerVessel(str, date); + result.setValue(s, value); + } +// for(Strategy str : strategies){ +// double value = ownerMarginOverVariableCostsPerStrategyPerVessel(str, date); +// result.setValue(str, value); +// } + + return result; + } + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * OwnerMarginOverVariableCostsPerStrategyPerVessel[str,month]?=?somme sur tous les m?tiers de OwnerMarginOverVariableCostsPerStrategyMetPerVessel [str,met,month] + * + * @param str + * @param date + * @return + * @throws TopiaException + */ + private double ownerMarginOverVariableCostsPerStrategyPerVessel(Strategy str, Date date) throws TopiaException { + SetOfVessels sov = str.getSetOfVessels(); + Collection<EffortDescription> efforts = sov.getPossibleMetiers(); + + float result = 0; + + for (EffortDescription effort : efforts) { + Metier metier = effort.getPossibleMetiers(); + result += ownerMarginOverVariableCostsPerStrategyMetPerVessel(str, metier, date); + } + return result; + } + + ////////////////////////////////////////////////////////////////////// + // matrixOwnerMarginOverVariableCostsPerStrategy + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixOwnerMarginOverVariableCostsPerStrategy(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_OWNER_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY, + new List[]{strategies}, + new String[]{n_("Strategies")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + double value = ownerMarginOverVariableCostsPerStrategy(str, date); + result.setValue(s, value); + } +// for(Strategy str : strategies){ +// double value = ownerMarginOverVariableCostsPerStrategy(str, date); +// result.setValue(str, value); +// } + + return result; + } + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * OwnerMarginOverVariableCostsPerStrategy[str,month]?=?OwnerMarginOverVariableCostsPerStrategyPerVessel[str,month]?*[PropNbVessels(str,sov)*NbVesselsSetOfVessels(sov)] + * + * @param str + * @param date + * @return + * @throws TopiaException + */ + private double ownerMarginOverVariableCostsPerStrategy(Strategy str, Date date) throws TopiaException { + double ownerMarginOverVariableCostsPerStrategyPerVessel = ownerMarginOverVariableCostsPerStrategyPerVessel(str, date); + double proportionSetOfVessels = str.getProportionSetOfVessels(); + double numberOfVessels = str.getSetOfVessels().getNumberOfVessels(); + + return ownerMarginOverVariableCostsPerStrategyPerVessel * (proportionSetOfVessels * numberOfVessels); + } + + ////////////////////////////////////////////////////////////////////// + // matrixVesselMarginOverVariableCostsPerStrategyPerVessel + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixVesselMarginOverVariableCostsPerStrategyPerVessel(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_VESSEL_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_PER_VESSEL, + new List[]{strategies}, + new String[]{n_("Strategies")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + double value = vesselMarginOverVariableCostsPerStrategyPerVessel(str, date); + result.setValue(s, value); + } +// for(Strategy str : strategies){ +// double value = vesselMarginOverVariableCostsPerStrategyPerVessel(str, date); +// result.setValue(str, value); +// } + + return result; + } + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * VesselMarginOverVariableCostsPerStrategyPerVessel[str,month]?= somme sur tous les m?tiers de VesselMarginOverVariableCostsPerStrategyMetPerVessel? [str,met,month] + * + * @param str + * @param date + * @return + * @throws TopiaException + */ + private double vesselMarginOverVariableCostsPerStrategyPerVessel(Strategy str, Date date) throws TopiaException { + SetOfVessels sov = str.getSetOfVessels(); + Collection<EffortDescription> efforts = sov.getPossibleMetiers(); + + float result = 0; + + for (EffortDescription effort : efforts) { + Metier metier = effort.getPossibleMetiers(); + result += vesselMarginOverVariableCostsPerStrategyMetPerVessel(str, metier, date); + } + return result; + } + + + ////////////////////////////////////////////////////////////////////// + // matrixVesselMarginOverVariableCostsPerStrategy + ////////////////////////////////////////////////////////////////////// + + public MatrixND matrixVesselMarginOverVariableCostsPerStrategy(Date date) throws TopiaException{ + List<Strategy> strategies = siMatrix.getStrategies(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_VESSEL_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY, + new List[]{strategies}, + new String[]{n_("Strategies")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + double value = vesselMarginOverVariableCostsPerStrategy(str, date); + result.setValue(s, value); + } +// for(Strategy str : strategies){ +// double value = vesselMarginOverVariableCostsPerStrategy(str, date); +// result.setValue(str, value); +// } + + return result; + } + + /** + * implant? suivant document ModifTable3PourBP25-07-2006.doc + * VesselMarginOverVariableCostsPerStrategy[str,month]?=VesselMarginOverVariableCostsPerStrategyPerVessel?[str,month] *[PropNbVessels(str,sov)*NbVesselsSetOfVessels(sov)] + * + * @param str + * @param date + * @return + * @throws TopiaException + */ + private double vesselMarginOverVariableCostsPerStrategy(Strategy str, Date date) throws TopiaException { + double vesselMarginOverVariableCostsPerStrategyPerVessel = vesselMarginOverVariableCostsPerStrategyPerVessel(str, date); + double proportionSetOfVessels = str.getProportionSetOfVessels(); + double numberOfVessels = str.getSetOfVessels().getNumberOfVessels(); + + return vesselMarginOverVariableCostsPerStrategyPerVessel * (proportionSetOfVessels * numberOfVessels); + } + + + /////////////////////////////////////////////////////////////////////////// + // + // Methode non utilis?e directement dans GravityModel, mais dans les rules + // + /////////////////////////////////////////////////////////////////////////// + + public double valuePerUnitFishingEffort(Strategy str, Metier metier, Date date) throws TopiaException{ + List<Population> pops = siMatrix.getPopulations(date); + + double result = 0; + + for(Population pop : pops){ + List<PopulationGroup> groups = pop.getPopulationGroup(); + Collection<Zone> zones = pop.getPopulationZone(); + for(PopulationGroup group : groups){ + double price = group.getPrice(); + for(Zone zone : zones){ + double catchValue = getCatchWeightPerStrMetPerZonePop(str, metier, group, zone, date); + double discards = getDiscardsWeightPerStrMet(str, metier, group, zone, date); + result += price * (catchValue - discards); + } + } + } + + double effort = getEffortPerStrategyMet(str, metier, date); + + if(effort == 0){ + result = 0; + } else { + result = result / effort; + } + // FIXME verifier qu'il faut bien retourner 0, si pas d'effort + return result; + } + + /** + * @param str + * @param metier + * @param date + * @return + */ + public double getEffortPerStrategyMet(Strategy str, Metier metier, Date date) { + MatrixND mat = resultManager.getMatrix(date, ResultName.MATRIX_EFFORT_PER_STRATEGY_MET); + double result = 0; + if(mat != null){ + result = mat.getValue(str, metier); + } + return result; + } + + public double landingPerUnitFishingEffort(Strategy str, Metier metier, Date date) throws TopiaException{ + List<Population> pops = siMatrix.getPopulations(date); + + double effort = getEffortPerStrategyMet(str, metier, date); + double result = 0; + + if(effort != 0){ // s'il n'y a pas d'effort on retournera 0 + for(Population pop : pops){ + List<PopulationGroup> groups = pop.getPopulationGroup(); + Collection<Zone> zones = pop.getPopulationZone(); + for(PopulationGroup group : groups){ + for(Zone zone : zones){ + double catchValue = getCatchWeightPerStrMetPerZonePop(str, metier, group, zone, date); + double discards = getDiscardsWeightPerStrMet(str, metier, group, zone, date); + result += catchValue - discards; + } + } + } + result = result / effort; + } + + return result; + } + +} + + Added: isis-fish/trunk/src/test/resources/test-database/scripts/ResultName.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/scripts/ResultName.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/scripts/ResultName.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,139 @@ +/* *##% + * 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. + *##%*/ + +/* * + * ResultName.java + * + * Created: 23 août 2006 15:09:37 + * + * @author poussin + * @version $Revision: 1.10 $ + * + * Last update: $Date: 2007-07-09 19:51:34 $ + * by : $Author: bpoussin $ + */ + +package scripts; + +import static org.codelutin.i18n.I18n.n_; + +import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) + +/** + * Contient l'ensemble des noms des differents resultats. Le mieux lorsque l'on + * veut un nouveau résultat est d'ajouter une constante ici, et de l'utiliser + * ensuite lors de la création de la matrice. + * <p> + * Ceci permet d'avoir un endroit unique ou l'on voit l'ensemble des résultats + * potentiellement disponible et de ne pas ce tromper en écrivent le nom + * d'un résultat + * <p> + * Cette classe ne doit contenir que des noms de resultat en static public String + * l'interface de lancement de simulation se base sur cette classe pour + * afficher l'ensemble des résultats disponible + * + * @author poussin + */ +public class ResultName { + @Doc(value = "do the doc of Result matrixDiscardsWeightPerStrMet") + static final public String MATRIX_DISCARDS_WEIGHT_PER_STR_MET_PER_ZONE_POP = n_("matrixDiscardsWeightPerStrMet"); + + @Doc(value = "do the doc of Result matrixDiscardsPerStrMet") + static final public String MATRIX_DISCARDS_PER_STR_MET_PER_ZONE_POP = n_("matrixDiscardsPerStrMet"); + @Doc(value = "do the doc of Result matrixLandingPerMet") + static final public String MATRIX_LANDING_PER_MET = n_("matrixLandingPerMet"); + + @Doc(value = "do the doc of Result matrixEffortPerStrategyMet") + static final public String MATRIX_EFFORT_PER_STRATEGY_MET = n_("matrixEffortPerStrategyMet"); + @Doc(value = "do the doc of Result matrixStdTravelEffortPerStrategyMet") + static final public String MATRIX_STD_TRAVEL_EFFORT_PER_STRATEGY_MET = n_("matrixStdTravelEffortPerStrategyMet"); + @Doc(value = "do the doc of Result matrixEffortPerZonePop") + static final public String MATRIX_EFFORT_PER_ZONE_POP = n_("matrixEffortPerZonePop"); + @Doc(value = "Disponible uniquement avec les simulations par Zone. do the doc of Result matrixCatchRatePerStrategyMet") + static final public String MATRIX_CATCH_RATE_PER_STRATEGY_MET_PER_ZONE_POP = n_("matrixCatchRatePerStrategyMet"); + @Doc(value = "do the doc of Result matrixCatchPerStrategyMetPerZoneMet") + static final public String MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_MET = n_("matrixCatchPerStrategyMetPerZoneMet"); + @Doc(value = "do the doc of Result matrixCatchPerStrategyMetPerZonePop") + static final public String MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_POP = n_("matrixCatchPerStrategyMetPerZonePop"); + @Doc(value = "do the doc of Result matrixCatchWeightPerStrategyMetPerZoneMet") + static final public String MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_MET = n_("matrixCatchWeightPerStrategyMetPerZoneMet"); + @Doc(value = "do the doc of Result matrixCatchWeightPerStrategyMetPerZonePop") + static final public String MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP = n_("matrixCatchWeightPerStrategyMetPerZonePop"); + @Doc(value = "Disponible uniquement avec les simulations par Zone. do the doc of Result matrixFishingMortality") + static final public String MATRIX_FISHING_MORTALITY = n_("matrixFishingMortality"); + @Doc(value = "do the doc of Result matrixAbundance") + static final public String MATRIX_ABUNDANCE = n_("matrixAbundance"); + @Doc(value = "do the doc of Result matrixBiomass") + static final public String MATRIX_BIOMASS = n_("matrixBiomass"); + @Doc(value = "do the doc of Result matrixBiomassBeginMonth") + static final public String MATRIX_BIOMASS_BEGIN_MONTH = n_("matrixBiomassBeginMonth"); + @Doc(value = "do the doc of Result matrixBiomassBeginMonth") + static final public String MATRIX_ABONDANCE_BEGIN_MONTH = n_("matrixAbondanceBeginMonth"); + + @Doc(value = "do the doc of Result matrixFishingTimePerMonthPerVessel") + static final public String MATRIX_FISHING_TIME_PER_MONTH_PER_VESSEL = n_("matrixFishingTimePerMonthPerVessel"); + @Doc(value = "do the doc of Result matrixFuelCostsOfTravelPerVessel") + static final public String MATRIX_FUEL_COSTS_OF_TRAVEL_PER_VESSEL = n_("matrixFuelCostsOfTravelPerVessel"); + @Doc(value = "do the doc of Result matrixCostsOfFishingPerVessel") + static final public String MATRIX_COSTS_OF_FISHING_PER_VESSEL = n_("matrixCostsOfFishingPerVessel"); + @Doc(value = "do the doc of Result matrixFuelCostsPerVessel") + static final public String MATRIX_FUEL_COSTS_PER_VESSEL = n_("matrixFuelCostsPerVessel"); + @Doc(value = "do the doc of Result matrixRepairAndMaintenanceGearCostsPerVessel") + static final public String MATRIX_REPAIR_AND_MAINTENANCE_GEAR_COSTS_PER_VESSEL = n_("matrixRepairAndMaintenanceGearCostsPerVessel"); + @Doc(value = "do the doc of Result matrixOtherRunningCostsPerVessel") + static final public String MATRIX_OTHER_RUNNING_COSTS_PER_VESSEL = n_("matrixOtherRunningCostsPerVessel"); + @Doc(value = "do the doc of Result matrixSharedNotFixedCostsPerVessel") + static final public String MATRIX_SHARED_NOT_FIXED_COSTS_PER_VESSEL = n_("matrixSharedNotFixedCostsPerVessel"); +// static final public String MATRIX_SHARED_FIXED_COSTS_PER_VESSEL_PER_MET = n_("matrixSharedFixedCostsPerVesselPerMet"); + @Doc(value = "do the doc of Result matrixGrossValueOfLandingsPerSpeciesPerStrategyMet") + static final public String MATRIX_GROSS_VALUE_OF_LANDINGS_PER_SPECIES_PER_STRATEGY_MET = n_("matrixGrossValueOfLandingsPerSpeciesPerStrategyMet"); + @Doc(value = "do the doc of Result matrixGrossValueOfLandingsPerStrategyMet") + static final public String MATRIX_GROSS_VALUE_OF_LANDINGS_PER_STRATEGY_MET = n_("matrixGrossValueOfLandingsPerStrategyMet"); + @Doc(value = "do the doc of Result matrixGrossValueOfLandingsPerStrategyMetPerVessel") + static final public String MATRIX_GROSS_VALUE_OF_LANDINGS_PER_STRATEGY_MET_PER_VESSEL = n_("matrixGrossValueOfLandingsPerStrategyMetPerVessel"); + @Doc(value = "do the doc of Result matrixNetValueOfLandingsPerStrategyMet") + static final public String MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET = n_("matrixNetValueOfLandingsPerStrategyMet"); + @Doc(value = "do the doc of Result matrixNetValueOfLandingsPerStrategyMetPerVessel") + static final public String MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET_PER_VESSEL = n_("matrixNetValueOfLandingsPerStrategyMetPerVessel"); + @Doc(value = "do the doc of Result matrixNetRenevueToSharePerStrategyMetPerVessel") + static final public String MATRIX_NET_RENEVUE_TO_SHARE_PER_STRATEGY_MET_PER_VESSEL = n_("matrixNetRenevueToSharePerStrategyMetPerVessel"); + @Doc(value = "do the doc of Result matrixCrewSharePerStrategyPerVessel") + static final public String MATRIX_CREW_SHARE_PER_STRATEGY_MET_PER_VESSEL = n_("matrixCrewSharePerStrategyPerVessel"); + @Doc(value = "do the doc of Result matrixOwnerMarginOverVariableCostsPerStrategyMetPerVessel") + static final public String MATRIX_OWNER_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_MET_PER_VESSEL = n_("matrixOwnerMarginOverVariableCostsPerStrategyMetPerVessel"); + @Doc(value = "do the doc of Result matrixVesselMarginOverVariableCostsPerStrategyMetPerVessel") + static final public String MATRIX_VESSEL_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_MET_PER_VESSEL = n_("matrixVesselMarginOverVariableCostsPerStrategyMetPerVessel"); + @Doc(value = "do the doc of Result matrixOwnerMarginOverVariableCostsPerStrategyPerVessel") + static final public String MATRIX_OWNER_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_PER_VESSEL = n_("matrixOwnerMarginOverVariableCostsPerStrategyPerVessel"); + @Doc(value = "do the doc of Result matrixOwnerMarginOverVariableCostsPerStrategy") + static final public String MATRIX_OWNER_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY = n_("matrixOwnerMarginOverVariableCostsPerStrategy"); + @Doc(value = "do the doc of Result matrixVesselMarginOverVariableCostsPerStrategyPerVessel") + static final public String MATRIX_VESSEL_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_PER_VESSEL = n_("matrixVesselMarginOverVariableCostsPerStrategyPerVessel"); + @Doc(value = "do the doc of Result matrixVesselMarginOverVariableCostsPerStrategy") + static final public String MATRIX_VESSEL_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY = n_("matrixVesselMarginOverVariableCostsPerStrategy"); + + @Doc(value = "do the doc of Result matrixNoActivity") + static final public String MATRIX_NO_ACTIVITY = n_("matrixNoActivity"); + @Doc(value = "do the doc of Result matrixMetierZone") + static final public String MATRIX_METIER_ZONE = n_("matrixMetierZone"); + @Doc(value = "do the doc of Result matrixPrice") + static final public String MATRIX_PRICE = n_("matrixPrice"); +} + + Added: isis-fish/trunk/src/test/resources/test-database/scripts/RuleUtil.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/scripts/RuleUtil.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/scripts/RuleUtil.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,65 @@ +package scripts; + +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.codelutin.math.matrix.*; + +import fr.ifremer.isisfish.entities.Population; +import fr.ifremer.isisfish.entities.PopulationGroup; +import fr.ifremer.isisfish.entities.Species; +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.types.Date; + +/** + * ChangeMatrixBackend.java + * + * Created: 6 septembre 2006 + * + * @author anonymous <anonymous at labs.libre-entreprise.org> + * @version $Revision: 1.3 $ + * + * Last update: $Date: 2007-11-20 15:51:05 $ + * by : $Author: bpoussin $ + */ +public class RuleUtil { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(RuleUtil.class); + + /** + * @param context le context de simulation + * @param species l'espece sur lequel on souhaite le total + * @param date la date pour laquel on veut le calcul, cet argument est + * passe seulement pour que le cache ne retourne pas toujours la meme valeur + * @return + */ + public static double getTotalCatchTons(SimulationContext context, Species species, Date date) { + double result = 0; + for (Population pop : species.getPopulation()) { + MatrixND mat = context.getPopulationMonitor().getHoldCatch(pop); + if(mat!=null) { + mat = mat.copy(); + mat = mat.sumOverDim(0); // sum over Strategies + mat = mat.sumOverDim(1); // sum over metiers + mat = mat.sumOverDim(3); // sum over zones +// List<PopulationGroup> groups = mat.getSemantics(2); + + List<PopulationGroup> groups = pop.getPopulationGroup(); + + for (int c=0; c<groups.size(); c++) { + PopulationGroup group = groups.get(c); + double weight = group.getMeanWeight(); + result += mat.getValue(0, 0, c, 0) * weight / 1000.0; + } + } + } + return result; + } + + + + +} Added: isis-fish/trunk/src/test/resources/test-database/scripts/SiMatrix.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/scripts/SiMatrix.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/scripts/SiMatrix.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,1756 @@ +/* *##% + * Copyright (C) 2006 + * Code Lutin, 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. + *##%*/ + +/* * + * SiMatrix.java + * + * Created: 21 ao?t 2006 15:53:01 + * + * @author poussin + * @version $Revision: 1.18 $ + * + * Last update: $Date: 2007-11-02 17:53:20 $ + * by : $Author: bpoussin $ + */ + +package scripts; + +import static org.codelutin.i18n.I18n._; +import static org.codelutin.i18n.I18n.n_; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.codelutin.math.matrix.MatrixFactory; +import org.codelutin.math.matrix.MatrixIterator; +import org.codelutin.math.matrix.MatrixND; +import org.codelutin.topia.TopiaContext; +import org.codelutin.topia.TopiaException; + +import fr.ifremer.isisfish.IsisFishDAOHelper; +import fr.ifremer.isisfish.IsisFishException; +import fr.ifremer.isisfish.entities.Cell; +import fr.ifremer.isisfish.entities.EffortDescription; +import fr.ifremer.isisfish.entities.Gear; +import fr.ifremer.isisfish.entities.Metier; +import fr.ifremer.isisfish.entities.MetierSeasonInfo; +import fr.ifremer.isisfish.entities.Population; +import fr.ifremer.isisfish.entities.PopulationGroup; +import fr.ifremer.isisfish.entities.PopulationSeasonInfo; +import fr.ifremer.isisfish.entities.Selectivity; +import fr.ifremer.isisfish.entities.SetOfVessels; +import fr.ifremer.isisfish.entities.Strategy; +import fr.ifremer.isisfish.entities.StrategyMonthInfo; +import fr.ifremer.isisfish.entities.Zone; +import fr.ifremer.isisfish.entities.ZoneDAO; +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.types.Month; +import java.util.Arrays; +import java.util.Set; + +/** + * @author poussin + * + */ + +public class SiMatrix { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(SiMatrix.class); + + protected SimulationContext context = null; + protected TopiaContext db = null; + + /** + * Method used to get SiMatrix used for simulation + * @param context context simulation + * @return SiMatrix or null if no SiMatrix created for simulation + */ + public static SiMatrix getSiMatrix(SimulationContext context) throws TopiaException { + SiMatrix result = (SiMatrix)context.getValue(SiMatrix.class.getName()); + if (result == null) { + result = new SiMatrix(context); + } + return result; + } + + private static void setSiMatrix(SimulationContext context, SiMatrix siMatrix) { + context.setValue(SiMatrix.class.getName(), siMatrix); + } + + /** + * + * @param context Simulation context + * @param db TopiaContext with transaction opened. You must used this + * TopiaContext and not used + * SimulationContext.getSimulationStorage().getStorage() + * @throws TopiaException + */ + public SiMatrix(SimulationContext context) throws TopiaException { + this.context = context; + this.db = context.getDB(); + setSiMatrix(context, this); + } + + /** + * @return + * @throws TopiaException + */ + public List<Zone> getZones(Date date) throws TopiaException { + ZoneDAO dao = IsisFishDAOHelper.getZoneDAO(db); + List<Zone> result = dao.findAll(); + return result; + } + + /** + * @return + * @throws TopiaException + */ + public List<Population> getPopulations(Date date) throws TopiaException { + List<Population> populations = new ArrayList<Population>(); + for (Population pop : context.getSimulationStorage().getParameter().getPopulations()) { + Population tmp = (Population)db.findByTopiaId(pop.getTopiaId()); + populations.add(tmp); + } + return populations; + } + + /** + * @return + * @throws TopiaException + */ + public List<Strategy> getStrategies(Date date) throws TopiaException { +// if (strategies == null) { + List<Strategy> strategies = new ArrayList<Strategy>(); + for (Strategy str : context.getSimulationStorage().getParameter().getStrategies()) { + Strategy tmp = (Strategy)db.findByTopiaId(str.getTopiaId()); + strategies.add(tmp); + } +// } + return strategies; + } + + public List<Metier> getMetiers(Date date) throws TopiaException { +// if (metiers == null) { + List<Metier> metiers = new ArrayList<Metier>(); + HashSet<Metier> tmp = new HashSet<Metier>(); + for (Strategy str : getStrategies(date)) { + SetOfVessels sov = str.getSetOfVessels(); + for (EffortDescription effort : sov.getPossibleMetiers()) { + Metier metier = effort.getPossibleMetiers(); + if (tmp.add(metier)) { + metiers.add(metier); + } + } + } +// } + return metiers; + } + + /** + * Retourne les metiers pratiqu?s par une Strategie ? une date donn?e + * Un metier est pratiqu? si le PropStrMet est diff?rent de 0 + * + * @param str + * @param date + * @return + */ + public List<Metier> getMetiers(Strategy str, Date date) { + StrategyMonthInfo info = str.getStrategyMonthInfo(date.getMonth()); + MatrixND props = info.getProportionMetier(); + + List<Metier> result = new ArrayList<Metier>(); + + for (MatrixIterator i=props.iterator(); i.hasNext();) { + i.next(); + if (i.getValue() != 0) { + Metier metier = (Metier)i.getSemanticsCoordinates()[0]; + result.add(metier); + } + } + return result; + } + + /** + * Retourne la matrix Metier x Zone qui correspond au zone utilis? par + * un m?tier pour une date donn?e. Si la valeur de la matrice est 1 alors + * la zone est utilis? par le m?tier, si elle vaut 0 alors elle n'est pas + * utilis?e. + * + * @param date + * @return + * @throws TopiaException + */ + public MatrixND getMetierZone(Date date) throws TopiaException { + List<Metier> metiers = getMetiers(date); + List<Zone> zones = getZones(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_METIER_ZONE, + new List[]{metiers, zones}, + new String[]{n_("Metiers"), n_("Zones")}); + + for (Metier metier : metiers) { + Collection<Zone> zoneMetier = metier.getMetierSeasonInfo(date.getMonth()).getZone(); + for (Zone zone : zoneMetier) { + result.setValue(metier, zone, 1); + } + } + return result; + } + + public MatrixND matrixPrice(Date date, Population pop) { + List<PopulationGroup> groups = pop.getPopulationGroup(); + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_PRICE, + new List[]{groups}, + new String[]{n_("PopulationGroup")}); + + for (PopulationGroup group : groups) { + result.setValue(group, group.getPrice()); + } + + return result; + } + + /////////////////////////////////////////////////////////////////////////// + // + // Toutes les methodes suivantes ne sont utiles que pour + // matrixCatchPerStrategyMet + // + /////////////////////////////////////////////////////////////////////////// + + public MatrixND matrixCatchWeightPerStrategyMetPerZoneMet(Date date, Population pop, MatrixND matrixCatchPerStrategyMetPerZoneMet) throws TopiaException, IsisFishException { + List<PopulationGroup> groups = pop.getPopulationGroup(); + + MatrixND result = matrixCatchPerStrategyMetPerZoneMet.copy(); + result.setName(ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_MET); + + for (PopulationGroup group : groups) { + MatrixND sub = result.getSubMatrix(2, group, 1); + double meanWeight = group.getMeanWeight(); + sub.mults(meanWeight); + } + + return result; + } + + public MatrixND matrixCatchPerStrategyMetPerZoneMet(MatrixND N, Population pop, Date date) throws TopiaException, IsisFishException { + + MatrixND matrixFishingMortalityPerCell = matrixFishingMortalityPerCell(date, pop); + MatrixND matrixCatchRatePerStrategyMetPerCell = matrixCatchRatePerStrategyMetPerCell(pop, date, matrixFishingMortalityPerCell); + MatrixND matrixCatchPerStrategyMetPerCell = matrixCatchPerStrategyMetPerCell(N, pop, date, matrixCatchRatePerStrategyMetPerCell); + + List<Strategy> strategies = getStrategies(date); + List<Metier> metiers = getMetiers(date); + List<PopulationGroup> groups = matrixCatchPerStrategyMetPerCell.getSemantics(2); + List<Zone> zones = getZones(date); + + Set<Cell> cellPops = new HashSet(matrixCatchPerStrategyMetPerCell.getSemantics(4)); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_MET, + new List[]{strategies, metiers, groups, zones}, + new String[]{n_("Strategies"), n_("Metiers"), n_("Groups"), n_("Zones")}); + + // matrice temporaire ou les zones pops sont sommees + MatrixND tmp = matrixCatchPerStrategyMetPerCell.sumOverDim(3); + tmp = tmp.reduceDims(3); + + for (int s = 0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + for(int g = 0; g<groups.size(); g++) { + PopulationGroup group = groups.get(g); + for (int m = 0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + MetierSeasonInfo infoMet = metier.getMetierSeasonInfo(date.getMonth()); + Collection<Zone> zoneMet = infoMet.getZone(); + for (Zone z : zoneMet) { + double value = 0; + List<Cell> cells = z.getCell(); + for (int c = 0; c < cells.size(); c++) { + Cell cell = cells.get(c); + if (cellPops.contains(cell)) { + // les cells de la matrice sont les cells des + // zones pops, donc seul les intersections avec + // les cells des metiers sont des cells valides + value += tmp.getValue(str, metier, group, cell); + } + } + result.setValue(str, metier, group, z, value); + } + } + } + } + + return result; + } + + public MatrixND matrixCatchPerStrategyMetPerZonePop(MatrixND N, Population pop, Date date) throws TopiaException, IsisFishException { + MatrixND matrixFishingMortalityPerCell = matrixFishingMortalityPerCell(date, pop); + MatrixND matrixCatchRatePerStrategyMetPerCell = matrixCatchRatePerStrategyMetPerCell(pop, date, matrixFishingMortalityPerCell); + MatrixND matrixCatchPerStrategyMetPerCell = matrixCatchPerStrategyMetPerCell(N, pop, date, matrixCatchRatePerStrategyMetPerCell); + + // on somme sur les cellules + MatrixND result = matrixCatchPerStrategyMetPerCell.sumOverDim(4); + result = result.reduceDims(4); + result.setName(ResultName.MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_POP); + + return result; + } + + public MatrixND matrixCatchWeightPerStrategyMetPerZonePop(Date date, + Population pop, MatrixND matrixCatchPerStrategyMetPerZonePop) throws TopiaException, IsisFishException { + List<PopulationGroup> groups = pop.getPopulationGroup(); + + MatrixND result = matrixCatchPerStrategyMetPerZonePop.copy(); + result.setName(ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP); + + for (PopulationGroup group : groups) { + MatrixND sub = result.getSubMatrix(2, group, 1); + double meanWeight = group.getMeanWeight(); + sub.mults(meanWeight); + } + + return result; + } + + + /** + * Utilise pour le calcul en Zone + * + * Matrice des captures en nombre + * dim [ Strategy x Metier x Classe x zonePop ] + * + * @param N l'abondance sous forme de matrice 2D [class x zone] + * @param pop + * @param date + * @return + * @throws TopiaException + * @throws IsisFishException + */ + public MatrixND matrixCatchPerStrategyMetPerZone(MatrixND N, Population pop, + Date date, MatrixND matrixCatchRatePerStrategyMet) throws TopiaException, IsisFishException { + List<PopulationGroup> groups = pop.getPopulationGroup(); + List<Zone> zones = pop.getPopulationZone(); + + // on le passe en argument ce qui evite de le calculer 2 fois +// MatrixND matrixCatchRatePerStrategyMet = matrixCatchRatePerStrategyMet(pop, date); + MatrixND result = matrixCatchRatePerStrategyMet.copy(); + result.setName(ResultName.MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_POP); + + for(PopulationGroup group : groups) { + MatrixND sub = result.getSubMatrix(2, group, 1); + for(Zone zone : zones){ + MatrixND subsub = sub.getSubMatrix(3, zone, 1); + double val = N.getValue(group, zone); + subsub.mults(val); + } + } + return result; + } + + /** + * Utilise pour le calcul en Zone + * Matrice des captures en poids + * dim [ Strategy x Metier x Classe x zonePop ] + * + * @param pop + * @param date + * @return + * @throws TopiaException + * @throws IsisFishException + */ + public MatrixND matrixCatchRatePerStrategyMetPerZone(Population pop, Date date, MatrixND matrixFishingMortality) throws TopiaException, IsisFishException { + List<Strategy> strategies = getStrategies(date); + List<Metier> metiers = getMetiers(date); + List<PopulationGroup> groups = pop.getPopulationGroup(); + List<Zone> zones = pop.getPopulationZone(); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_CATCH_RATE_PER_STRATEGY_MET_PER_ZONE_POP, + new List[]{strategies, metiers, groups, zones}, + new String[]{n_("Strategies"), n_("Metiers"), n_("Groups"), n_("Zones")}); + + // Optimisation Hilaire + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + for (int z=0; z < zones.size(); z++) { + Zone zone = zones.get(z); + double effort = effortPerZonePop(str,metier,date,zone); + if (effort > 0){ + for (int g=0; g < groups.size(); g++) { + PopulationGroup group = groups.get(g); + double value = catchRatePerStrategyMet(str, metier, date, group, zone, matrixFishingMortality); + result.setValue(str, metier, group, zone, value); + } + } + } + } + } + return result; + } + + /** + * @param str + * @param metier + * @param date + * @param zone + * @return + */ + private double effortPerZonePop(Strategy str, Metier metier, Date date, Zone zonePop) { + Month month = date.getMonth(); + Collection<Zone> zoneMet = metier.getMetierSeasonInfo(month).getZone(); + double inter = nbCellInter(zoneMet, zonePop); + + double effortPerStrategyPerCell = effortPerStrategyPerCell(str, metier, date); + + if(log.isDebugEnabled()) { + log.debug( + " strategy=" + str + + " metier=" + metier + + " inter=" + inter + + " effortPerStrategyPerCell=" + effortPerStrategyPerCell + ); + } + + double result = effortPerStrategyPerCell * inter; + return result; + } + + // Optimisation Hilaire + private double catchRatePerStrategyMet(Strategy str, Metier metier, Date date, PopulationGroup group, Zone zone, MatrixND matrixFishingMortality) throws TopiaException, IsisFishException { + double totalFishingMortality = totalFishingMortality(date, matrixFishingMortality).getValue(group, zone); + + if(totalFishingMortality == 0){ + if(log.isDebugEnabled()) {log.debug("pas de totalFishingMortality pour (" + group + ", " + zone +")");} + return 0; + } + + double fishingMortality = matrixFishingMortality.getValue(str, metier, group, zone); + double totalCatchRate = totalCatchRate(date, group, zone, totalFishingMortality); + + if(log.isDebugEnabled()) { + log.debug( + " totalFishingMortality=" + totalFishingMortality + + " fishingMortality=" + fishingMortality + + " totalCatchRate=" + totalCatchRate); + } + double result = fishingMortality / totalFishingMortality * totalCatchRate; + + return result; + } + + + /** + * @param date + * @param group + * @param zone + * @param totalFishingMortality + * @return + * @throws TopiaException + */ + private double totalCatchRate(Date date, PopulationGroup group, + Zone zone, double totalFishingMortality) throws TopiaException { + double M = group.getNaturalDeathRate(zone) / Month.NUMBER_OF_MONTH; + if(M == 0){ + // normalement il devrait y avoir de la mortalite naturelle + if (log.isWarnEnabled()) { + log.warn("Pas de mortalit? naturelle pour: " + group); + } + } + double F = totalFishingMortality; + + double result = 0; + if( M != 0 || F != 0){ + result = F/(F+M) * (1 - Math.exp(-(F+M))); + } + + return result; + } + + /** + * Returne une matrice de mortalite group x zone, donc somme sur str et metier + * + * @param date + * @param matrixFishingMortality + * @param group + * @param zone + * @return + */ + private MatrixND totalFishingMortality(Date date, MatrixND matrixFishingMortality) { + MatrixND result = matrixFishingMortality.sumOverDim(0); + result = result.sumOverDim(1); + result = result.reduceDims(0, 1); + return result; + } + + /** + * Matrice fishing mortality + * dim [ Strategy x Metier x Classe x zonePop ] + * + * @param pop + * @param date + * @return + * @throws TopiaException + * @throws IsisFishException + */ + public MatrixND matrixFishingMortality(Date date, Population pop) throws TopiaException, IsisFishException { + List<Strategy> strategies = getStrategies(date); + List<Metier> metiers = getMetiers(date); + List<PopulationGroup> groups = pop.getPopulationGroup(); + List<Zone> zones = pop.getPopulationZone(); + + // default value in matrix is 0 + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_FISHING_MORTALITY, + new List[]{strategies, metiers, groups, zones}, + new String[]{n_("Strategies"), n_("Metiers"), n_("Groups"), n_("Zones")}); + + Month month = date.getMonth(); + PopulationSeasonInfo infoPop = pop.getPopulationSeasonInfo(month); + + for (int g = 0; g < groups.size(); g++) { + PopulationGroup group = groups.get(g); + + // getCapturability is check matrix validity and create matrix if needed and get one value in + double capturability = infoPop.getCapturability(group); + if (capturability != 0) { // check 0, this prevent next call, for default value + + for (int m = 0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + + MetierSeasonInfo infoMet = metier.getMetierSeasonInfo(month); + // getTargetFactor seem to be simple + double ciblage = infoMet.getTargetFactor(group); + + if (ciblage != 0) { // check 0, this prevent next call, for default value + + Gear gear = metier.getGear(); + Selectivity selectivity = gear.getPopulationSelectivity(pop); + if (selectivity != null) { + + // getCoefficient is equation evaluation + double coeff = selectivity.getCoefficient(pop, group, metier); + if (coeff != 0) { // check 0, this prevent next call, for default value + + for (int s = 0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + for (int z = 0; z < zones.size(); z++) { + Zone zone = zones.get(z); + double effort = effortPerZonePop(str, metier, date, zone); + if (effort > 0) { // put value only if <> 0 + double value = coeff * capturability * ciblage * effort; + result.setValue(str, metier, group, zone, value); + } + } + } + } + } + } + } + } + } + return result; + } + + /** + * Matrice des captures en nombre + * dim [ Strategy x Metier x Classe x zonePop ] + * + * @param N l'abondance sous forme de matrice 2D [class x zone] + * @param pop + * @param date + * @return + * @throws TopiaException + * @throws IsisFishException + */ + private MatrixND matrixCatchPerStrategyMetPerCell(MatrixND N, Population pop, + Date date, MatrixND matrixCatchRatePerStrategyMetPerCell) throws TopiaException, IsisFishException { + List<PopulationGroup> groups = pop.getPopulationGroup(); + List<Zone> zones = pop.getPopulationZone(); + + // on le passe en argument ce qui evite de le calculer 2 fois +// MatrixND matrixCatchRatePerStrategyMet = matrixCatchRatePerStrategyMet(pop, date); + MatrixND result = matrixCatchRatePerStrategyMetPerCell.copy(); + result.setName("matrixCatchPerStrategyMetPerCell"); + + for(PopulationGroup group : groups) { + MatrixND sub = result.getSubMatrix(2, group, 1); + for(Zone zone : zones){ + MatrixND subsub = sub.getSubMatrix(3, zone, 1); + double val = N.getValue(group, zone) / (double)zone.sizeCell(); + subsub.mults(val); + } + } + return result; + } + + /** + * Matrice des captures en poids + * dim [ Strategy x Metier x Classe x zonePop ] + * + * @param pop + * @param date + * @return + * @throws TopiaException + * @throws IsisFishException + */ + private MatrixND matrixCatchRatePerStrategyMetPerCell(Population pop, Date date, MatrixND matrixFishingMortalityPerCell) throws TopiaException, IsisFishException { + List<Strategy> strategies = getStrategies(date); + List<Metier> metiers = getMetiers(date); + List<PopulationGroup> groups = pop.getPopulationGroup(); + List<Zone> zones = pop.getPopulationZone(); + List<Cell> cells = getCells(zones); + + MatrixND result = MatrixFactory.getInstance().create( + "matrixCatchRatePerStrategyMetPerCell", + new List[]{strategies, metiers, groups, zones, cells}, + new String[]{n_("Strategies"), n_("Metiers"), n_("Groups"), n_("Zones"), n_("Cells")}); + +// for (int s=0; s < strategies.size(); s++) { +// Strategy str = strategies.get(s); +// metiers = getMetiers(str, date); +// for (int m=0; m < metiers.size(); m++) { +// Metier metier = metiers.get(m); +// for (int g=0; g < groups.size(); g++) { +// PopulationGroup group = groups.get(g); +// for (int z=0; z < zones.size(); z++) { +// Zone zone = zones.get(z); +// double value = catchRatePerStrategyMet(str, metier, date, group, zone); +// result.setValue(str, metier, group, zone, value); +// } +// } +// } +// } + +// if(totalFishingMortality == 0){ +// if(log.isDebugEnabled()) {log.debug("pas de totalFishingMortality pour (" + pop + ")");} +// } else { + // Optimisation Hilaire + + MatrixND matrixFishingMortalityPerCellSumOverGroup = matrixFishingMortalityPerCell.sumOverDim(2); + matrixFishingMortalityPerCellSumOverGroup = matrixFishingMortalityPerCellSumOverGroup.reduceDims(2); + + for (int s = 0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = getMetiers(str, date); + for (int m = 0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + for (int z = 0; z < zones.size(); z++) { + Zone zone = zones.get(z); + List<Cell> cellZones = zone.getCell(); + for (int c = 0; c < cellZones.size(); c++) { + Cell cell = cellZones.get(c); + double effort = matrixFishingMortalityPerCellSumOverGroup.getValue( + str, metier, zone, cell); + if (effort > 0) { + for (int g = 0; g < groups.size(); g++) { + PopulationGroup group = groups.get(g); + double value = catchRatePerStrategyMetPerCell( + str, metier, date, group, zone, cell, + matrixFishingMortalityPerCell); + result.setValue(new Object[]{str, metier, group, + zone, cell}, value); + } + } + } + } + } + } +// } + +// for (Strategy str : strategies) { +// List<Metier> metierStr = getMetiers(str, date); +// for (Metier metier : metierStr) { +// for (PopulationGroup group : groups) { +// for (Zone zone : zones) { +// double val = catchRatePerStrategyMet(str, metier, date, group, zone); +// result.setValue(str, metier, group, zone, val); +// } +// } +// } +// } + return result; + } + + /** + * @param str + * @param metier + * @param date + * @param group + * @param zone + * @return + * @throws TopiaException + * @throws IsisFishException + */ +// private double catchRatePerStrategyMet(Strategy str, Metier metier, Date date, PopulationGroup group, Zone zone) throws TopiaException, IsisFishException { +// double totalFishingMortality = totalFishingMortality(date, group, zone); +// +// if(totalFishingMortality == 0){ +// if(log.isDebugEnabled()) {log.debug("pas de totalFishingMortality pour (" + group + ", " + zone +")");} +// return 0; +// } +// +// double fishingMortality = fishingMortality(str, metier, date, group, zone); +// double totalCatchRate = totalCatchRate(date, group, zone, totalFishingMortality); +// +// if(log.isDebugEnabled()) { +// log.debug( +// " totalFishingMortality=" + totalFishingMortality + +// " fishingMortality=" + fishingMortality + +// " totalCatchRate=" + totalCatchRate); +// } +// double result = fishingMortality / totalFishingMortality * totalCatchRate; +// +// return result; +// } + + // Optimisation Hilaire + private double catchRatePerStrategyMetPerCell(Strategy str, Metier metier, + Date date, PopulationGroup group, Zone zone, Cell cell, + MatrixND matrixFishingMortalityPerCell) throws TopiaException, IsisFishException { + + double totalFishingMortality = totalFishingMortalityPerCell(date, + matrixFishingMortalityPerCell).getValue(group, zone); + + if(totalFishingMortality == 0){ + if(log.isDebugEnabled()) {log.debug("pas de totalFishingMortality pour (" + group + ", " + zone +")");} + return 0; + } + + double fishingMortalityPerCell = matrixFishingMortalityPerCell.getValue( + new Object[]{str, metier, group, zone, cell}); + double totalCatchRatePerCell = + totalCatchRatePerCell(date, group, zone, totalFishingMortality); + + if(log.isDebugEnabled()) { + log.debug( + " totalFishingMortality=" + totalFishingMortality + + " fishingMortality=" + fishingMortalityPerCell + + " totalCatchRate=" + totalCatchRatePerCell); + } + double result = + fishingMortalityPerCell / totalFishingMortality * totalCatchRatePerCell; + + return result; + } + + + /** + * @param date + * @param group + * @param zone + * @param totalFishingMortality + * @return + * @throws TopiaException + */ + private double totalCatchRatePerCell(Date date, PopulationGroup group, + Zone zone, double totalFishingMortalityPerCell) throws TopiaException { + double M = group.getNaturalDeathRate(zone) / Month.NUMBER_OF_MONTH; + if(M == 0){ + // normalement il devrait y avoir de la mortalite naturelle + if (log.isWarnEnabled()) { + log.warn("Pas de mortalit? naturelle pour: " + group); + } + } + double F = totalFishingMortalityPerCell; + + double result = 0; + if( M != 0 || F != 0){ + result = F/(F+M) * (1 - Math.exp(-(F+M))); + } + + return result; + } + + /** + * Returne une matrice de mortalite group x zone, donc somme sur str et metier + * + * @param date + * @param matrixFishingMortality + * @param group + * @param zone + * @return + */ + private MatrixND totalFishingMortalityPerCell(Date date, MatrixND matrixFishingMortalityPerCell) { + MatrixND result = matrixFishingMortalityPerCell.sumOverDim(0); + result = result.sumOverDim(1); + result = result.reduceDims(0, 1); + return result; + } + + + // Nouvelle implantation suite a demande Steph et Sigrid: 20080208 (NouvellesEquationsfev2008ParCelluleAvecAlgo.odt) + /** + * Matrice fishing mortality + * dim [ Strategy x Metier x Classe x zonePop x cellPop] + * + * @param pop + * @param date + * @return + * @throws TopiaException + * @throws IsisFishException + */ + public MatrixND matrixFishingMortalityPerCell(Date date, Population pop) throws TopiaException, IsisFishException { + List<Strategy> strategies = getStrategies(date); + List<Metier> metiers = getMetiers(date); + List<PopulationGroup> groups = pop.getPopulationGroup(); + List<Zone> zones = pop.getPopulationZone(); + List<Cell> cells = getCells(zones); + + // default value in matrix is 0 + MatrixND result = MatrixFactory.getInstance().create( + "matrixFishingMortalityPerCell", + new List[]{strategies, metiers, groups, zones, cells}, + new String[]{n_("Strategies"), n_("Metiers"), n_("Groups"), n_("Zones"), n_("Cells")}); + + Month month = date.getMonth(); + PopulationSeasonInfo infoPop = pop.getPopulationSeasonInfo(month); + + for (int g = 0; g < groups.size(); g++) { + PopulationGroup group = groups.get(g); + + // getCapturability is check matrix validity and create matrix + // if needed and get one value in + double capturability = infoPop.getCapturability(group); + if (capturability != 0) { // check 0, this prevent next call, for default value + for (int m = 0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + + MetierSeasonInfo infoMet = metier.getMetierSeasonInfo(month); + // getTargetFactor seem to be simple + double ciblage = infoMet.getTargetFactor(group); + + if (ciblage != 0) { // check 0, this prevent next call, for default value + + Gear gear = metier.getGear(); + Selectivity selectivity = gear.getPopulationSelectivity(pop); + if (selectivity != null) { + + // getCoefficient is equation evaluation + double coeff = selectivity.getCoefficient(pop, group, metier); + if (coeff != 0) { // check 0, this prevent next call, for default value + + for (int s = 0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + // l'effort d'une cellule du metier + double effort = effortPerStrategyPerCell(str, metier, date); + if (effort > 0) { // put value only if <> 0 + for (int z = 0; z < zones.size(); z++) { + Zone zone = zones.get(z); + Set<Cell> cellPops = new HashSet<Cell>(zone.getCell()); + for (Cell cellMet : infoMet.getCells()) { + if (cellPops.contains(cellMet)) { + double value = coeff * capturability * ciblage * effort; + result.setValue(new Object[]{str, metier, group, zone, cellMet}, value); + } + } + } + } + } + } + } + } + } + } + } + return result; + } + + // Supprimee suite a demande Steph et Sigrid: 20080208 (NouvellesEquationsfev2008ParCelluleAvecAlgo.odt) +// /** +// * Matrice fishing mortality +// * dim [ Strategy x Metier x Classe x zonePop ] +// * +// * @param pop +// * @param date +// * @return +// * @throws TopiaException +// * @throws IsisFishException +// */ +// public MatrixND matrixFishingMortalityPerCell(Date date, Population pop) throws TopiaException, IsisFishException { +// List<Strategy> strategies = getStrategies(date); +// List<Metier> metiers = getMetiers(date); +// List<PopulationGroup> groups = pop.getPopulationGroup(); +// List<Zone> zones = pop.getPopulationZone(); +// +// // default value in matrix is 0 +// MatrixND result = MatrixFactory.getInstance().create( +// ResultName.MATRIX_FISHING_MORTALITY, +// new List[]{strategies, metiers, groups, zones}, +// new String[]{n_("Strategies"), n_("Metiers"), n_("Groups"), n_("Zones")}); +// +// Month month = date.getMonth(); +// PopulationSeasonInfo infoPop = pop.getPopulationSeasonInfo(month); +// +// for (int g=0; g < groups.size(); g++) { +// PopulationGroup group = groups.get(g); +// +// // getCapturability is check matrix validity and create matrix if needed and get one value in +// double capturability = infoPop.getCapturability(group); +// if (capturability != 0) { // check 0, this prevent next call, for default value +// +// for (int m=0; m < metiers.size(); m++) { +// Metier metier = metiers.get(m); +// +// MetierSeasonInfo infoMet = metier.getMetierSeasonInfo(month); +// // getTargetFactor seem to be simple +// double ciblage = infoMet.getTargetFactor(group); +// +// if (ciblage != 0) { // check 0, this prevent next call, for default value +// +// Gear gear = metier.getGear(); +// Selectivity selectivity = gear.getPopulationSelectivity(pop); +// if (selectivity != null) { +// +// // getCoefficient is equation evaluation +// double coeff = selectivity.getCoefficient(pop, group, metier); +// if (coeff != 0) { // check 0, this prevent next call, for default value +// +// for (int s=0; s < strategies.size(); s++) { +// Strategy str = strategies.get(s); +// for (int z=0; z < zones.size(); z++) { +// Zone zone = zones.get(z); +// double effort = effortPerZonePop(str,metier,date,zone); +// if (effort > 0){ // put value only if <> 0 +// double value = coeff * capturability * ciblage * effort; +// result.setValue(str, metier, group, zone, value); +// } +// } +// } +// } +// } +// } +// } +// } +// } +// return result; +// } + + // ne prendre que les metiers pratiqu? semble une bonne idee, mais en fait non, car cela oblige l'ordre des boucles + // et donc ne permet pas autant d'optimisation que souhait? +// public MatrixND matrixFishingMortality2(Date date, Population pop) throws TopiaException, IsisFishException { +// List<Strategy> strategies = getStrategies(date); +// List<Metier> metiers = getMetiers(date); +// List<PopulationGroup> groups = pop.getPopulationGroup(); +// List<Zone> zones = pop.getPopulationZone(); + +// // default value in matrix is 0 +// MatrixND result = MatrixFactory.getInstance().create( +// ResultName.MATRIX_FISHING_MORTALITY, +// new List[]{strategies, metiers, groups, zones}, +// new String[]{n_("Strategies"), n_("Metiers"), n_("Groups"), n_("Zones")}); + +// Month month = date.getMonth(); +// PopulationSeasonInfo infoPop = pop.getPopulationSeasonInfo(month); + +// for (int s=0; s < strategies.size(); s++) { +// Strategy str = strategies.get(s); +// metiers = getMetiers(str, date); +// for (int m=0; m < metiers.size(); m++) { +// Metier metier = metiers.get(m); +// Gear gear = metier.getGear(); +// Selectivity selectivity = gear.getPopulationSelectivity(pop); +// if (selectivity != null) { +// MetierSeasonInfo infoMet = metier.getMetierSeasonInfo(month); +// for (int z=0; z < zones.size(); z++) { +// Zone zone = zones.get(z); +// double effort = effortPerZonePop(str,metier,date,zone); +// if (effort > 0){ // put value only if <> 0 +// for (int g=0; g < groups.size(); g++) { +// PopulationGroup group = groups.get(g); + +// // getTargetFactor seem to be simple +// double ciblage = infoMet.getTargetFactor(group); +// if (ciblage != 0) { // check 0, this prevent next call, for default value +// // getCapturability is check matrix validity and create matrix if needed and get one value in +// double capturability = infoPop.getCapturability(group); +// if (capturability != 0) { // check 0, this prevent next call, for default value +// // getCoefficient is equation evaluation +// double coeff = selectivity.getCoefficient(pop, group, metier); +// if (coeff != 0) { // check 0, this prevent next call, for default value +// double value = coeff * capturability * ciblage * effort; +// result.setValue(str, metier, group, zone, value); +// } +// } +// } +// } +// } +// } +// } +// } +// } +// return result; +// } + +// /** +// * @param date +// * @param group +// * @param zone +// * @return +// * @throws TopiaException +// * @throws IsisFishException +// */ +// private double totalFishingMortality(Date date, PopulationGroup group, Zone zone) throws TopiaException, IsisFishException { +// List<Strategy> strategies = getStrategies(date); +// +// float result = 0; +// +//// for(Strategy str : strategies){ +//// List<Metier> metierStr = getMetiers(str, date); +//// for (Metier metier : metierStr) { +//// // TODO peut etre ne pas le faire si classe.pop n'est pas +//// /// peche par le metier +//// result += fishingMortality(str, metier, date, group, zone); +//// } +//// } +// +// // Optimisation Hilaire +// for(Strategy str : strategies){ +// List<Metier> metierStr = getMetiers(str, date); +// for (Metier metier : metierStr) { +// double effort=effortPerZonePop(str,metier,date,zone); +// if (effort>0) +// result += fishingMortality(str, metier, date, group, zone, effort); +// } +// } +// +// return result; +// } + + + // fusion fishingMortality and matrixFishingMortality for performance reason +// /** +// * @param str +// * @param metier +// * @param date +// * @param group +// * @param zone +// * @return +// * @throws IsisFishException +// */ +// private double fishingMortality(Strategy str, Metier metier, Date date, PopulationGroup group, Zone zone, double effort) throws IsisFishException { +// Month month = date.getMonth(); +// Population pop = group.getPopulation(); +// Gear gear = metier.getGear(); +// +// Selectivity selectivity = gear.getPopulationSelectivity(pop); +// +// double result = 0; +// +// if (selectivity != null) { +// MetierSeasonInfo infoMet = metier.getMetierSeasonInfo(month); +// double ciblage = infoMet.getTargetFactor(group); +// +// PopulationSeasonInfo infoPop = pop.getPopulationSeasonInfo(month); +// double capturability = infoPop.getCapturability(group); +// +// double coeff = selectivity.getCoefficient(pop, group, metier); +// +// // Optimisation Hilaire +//// double effort = effortPerZonePop(str, metier, date, zone); +// +// // la methode est appeler des millions de fois, donc meme si +// // on ne perd pas beaucoup de temps avec le if, on en perd deja +// // trop +//// if(log.isDebugEnabled()) { +//// log.debug( +//// " strategy=" + str + +//// " metier=" + metier + +//// " ciblage=" + ciblage + +//// " capturabilite=" + capturability + +//// " selectivity=" + coeff + +//// " effort=" + effort); +//// } +// +// result = coeff * capturability * ciblage * effort; +// } +// +// return result; +// } + + // Supprimee suite a demande Steph et Sigrid: 20080208 (NouvellesEquationsfev2008ParCelluleAvecAlgo.odt) +// /** +// * @param str +// * @param metier +// * @param date +// * @param zone +// * @return +// */ +// private double effortPerZonePop(Strategy str, Metier metier, Date date, Zone zonePop) { +// Month month = date.getMonth(); +// Collection<Zone> zoneMet = metier.getMetierSeasonInfo(month).getZone(); +// double inter = nbCellInter(zoneMet, zonePop); +// +// double effortPerStrategyPerCell = effortPerStrategyPerCell(str, metier, date); +// +// if(log.isDebugEnabled()) { +// log.debug( +// " strategy=" + str + +// " metier=" + metier + +// " inter=" + inter + +// " effortPerStrategyPerCell=" + effortPerStrategyPerCell +// ); +// } +// +// double result = effortPerStrategyPerCell * inter; +// return result; +// } + + /** + * @param str + * @param metier + * @param date + * @return + */ + private double effortPerStrategyPerCell(Strategy str, Metier metier, Date date) { + Month month = date.getMonth(); + StrategyMonthInfo smi = str.getStrategyMonthInfo(month); + Collection<Zone> zones = metier.getMetierSeasonInfo(month).getZone(); + double nbCell = getCells(zones).size(); + + if(nbCell == 0){ + // normalement il devrait y avoir des mailles, mais pour les + // ancienne zone AuPort, il n'y en avait pas + if(log.isWarnEnabled()) log.warn("Calcul d'une distance pour le metier "+metier+" pour le mois "+month+" avec une zone sans maille: " + zones); + return 0; + } + + + double effortPerStrategy = effortPerStrategyMet(str, metier, date); + + if(log.isDebugEnabled()) { + log.debug( + " strategy=" + str + + " metier=" + metier + + " nbCell=" + nbCell + + " effortPerStrategy=" + effortPerStrategy + ); + } + + double result = effortPerStrategy/nbCell; + + return result; + } + + /** + * @param str + * @param metier + * @param date + * @return + */ + private double effortPerStrategyMet(Strategy str, Metier metier, Date date) { + Month month = date.getMonth(); + StrategyMonthInfo smi = str.getStrategyMonthInfo(month); + + double propSetOfVessels = str.getProportionSetOfVessels(); + int nbOfVessels = str.getSetOfVessels().getNumberOfVessels(); + double propStrMet = smi.getProportionMetier(metier); + double effortPerVessel = effortPerStrategyPerVessel(str, metier, date); + + if(log.isDebugEnabled()) { + log.debug( + " strategy=" + str + + " metier=" + metier + + " propSetOfVessels=" + propSetOfVessels + + " nbOfVessels=" + nbOfVessels + + " propStrMet=" + propStrMet + + " effortPerVessel=" + effortPerVessel + ); + } + + double result = propSetOfVessels * nbOfVessels * propStrMet * effortPerVessel; + + return result; + } + + /** + * @param str + * @param metier + * @param date + * @return + */ + private double effortPerStrategyPerVessel(Strategy str, Metier metier, Date date) { + Month month = date.getMonth(); + StrategyMonthInfo smi = str.getStrategyMonthInfo(month); + double nbTrips = smi.getNumberOfTrips(); + double fishingTime = fishingTimePerTrip(str, metier, date); + double stdEffortPerHour = stdEffortPerHour(date, str.getSetOfVessels(), metier); + + if(log.isDebugEnabled()) { + log.debug( + " strategy=" + str + + " metier=" + metier + + " nbTrips=" + nbTrips + + " fishingTime=" + fishingTime + + " stdEffortPerHour=" + stdEffortPerHour + ); + } + + double result = nbTrips * fishingTime * stdEffortPerHour; + + return result; + } + + /** + * Used in GravityModel too + * + * @param str + * @param metier + * @param date + * @return + */ + protected double fishingTimePerTrip(Strategy str, Metier metier, Date date) { + Month month = date.getMonth(); + StrategyMonthInfo smi = str.getStrategyMonthInfo(month); + Collection<Zone> zone = metier.getMetierSeasonInfo(month).getZone(); + + if (zone == null) { + if(log.isWarnEnabled()) log.warn( + "missing zone for metier =" + metier + + " for month" + month + ); + } + + double tripDuration = smi.getTripType().getTripDuration().getHour(); + double travelTime = travelTimePerTrip(str.getSetOfVessels(), zone); + + double result = tripDuration - travelTime; + + if (result < 0 ) { + if(log.isWarnEnabled()) log.warn( + " strategy=" + str + + " metier=" + metier + + " tripDuration=" + tripDuration + + " travelTime=" + travelTime + ); + } + return result; + } + + /** + * + * @param setOfVessels + * @param zone + * @return + */ + protected double travelTimePerTrip(SetOfVessels sov, Collection<Zone> zoneMetier) { + Cell maille = sov.getPort().getCell(); + double result = + 2 * distance(zoneMetier, maille) / sov.getVesselType().getSpeed(); + + return result; + } + + /** + * @param zoneMetier + * @param maille + * @return + */ + private double distance(Collection<Zone> zones, Cell cell) { + double result = 0; + List<Cell> cells = getCells(zones); + + if(cells.size() == 0){ + // normalement il devrait y avoir des mailles, mais pour les + // ancienne zone AuPort, il n'y en avait pas + if(log.isWarnEnabled()) { + log.warn("Calcul d'une distance avec une zone sans maille"); + } + return 0; + } + + for(Cell c : cells){ + result += distance(c, cell); + } + + if(log.isDebugEnabled()) { + log.debug(" result=" + result + " nbMaille="+cells.size()); + } + + result = result / (double)cells.size(); + return result; + } + + /** + * @param c + * @param cell + * @return + */ + private double distance(Cell m1, Cell m2) { + double earthRadius = 6378.388; + double p = 180/Math.PI; + + if(log.isDebugEnabled()) log.debug("p: " + p); + + double m1lat = m1.getLatitude(); + double m2lat = m2.getLatitude(); + double m1lon = m1.getLongitude(); + double m2lon = m2.getLongitude(); + + if(log.isDebugEnabled()) log.debug( + " m1lat=" + m1lat + + " m2lat=" + m2lat + + " m1lon=" + m1lon + + " m2lonx=" + m2lon + ); + + double m1lat_div_p = m1lat/p; + double m2lat_div_p = m2lat/p; + double m1lon_div_p = m1lon/p; + double m2lon_div_p = m2lon/p; + + if(log.isDebugEnabled()) log.debug( + " m1lat_div_p=" + m1lat_div_p + + " m2lat_div_p=" + m2lat_div_p + + " m1lon_div_p=" + m1lon_div_p + + " m2lon_div_p=" + m2lon_div_p + ); + + double sin_m1lat_div_p = Math.sin(m1lat_div_p); + double sin_m2lat_div_p = Math.sin(m2lat_div_p); + double cos_m1lat_div_p = Math.cos(m1lat_div_p); + double cos_m2lat_div_p = Math.cos(m2lat_div_p); + + if(log.isDebugEnabled()) log.debug( + " sin_m1lat_div_p=" + sin_m1lat_div_p + + " sin_m2lat_div_p=" + sin_m2lat_div_p + + " cos_m1lat_div_p=" + cos_m1lat_div_p + + " cos_m2lat_div_p=" + cos_m2lat_div_p + ); + + double cos_m1lon_div_p_minus_m2lon_div_p = Math.cos(m1lon_div_p - m2lon_div_p); + + if(log.isDebugEnabled()) log.debug( + " cos_m1lon_div_p_minus_m2lon_div_p=" + cos_m1lon_div_p_minus_m2lon_div_p); + + double acos = Math.acos( + sin_m1lat_div_p + * sin_m2lat_div_p + + + cos_m1lat_div_p + * cos_m2lat_div_p + * cos_m1lon_div_p_minus_m2lon_div_p + ); + + if(log.isDebugEnabled()) log.debug(" acos=" + acos); + + double result = earthRadius * acos; + + return result; + } + + /** + * @param setOfVessels + * @param metier + * @return + */ + private double stdEffortPerHour(Date date, SetOfVessels sov, Metier metier) { + double result = 0; + EffortDescription ed = sov.getPossibleMetiers(metier); + if(ed != null){ + double fstd = metier.getGear().getStandardisationFactor(); + double etp = sov.getTechnicalEfficiency(date, metier); + double val = + fstd * etp * ed.getFishingOperation() * ed.getGearsNumberPerOperation(); + result = val; + } + result = result/24; // 24 heures + + return result; + } + + + /** + * used here and in Rule (CantonnementPreSimu) + * + * @param zones + * @return + */ + public List<Cell> getCells(Collection<Zone> zones) { + List<Cell> result = new ArrayList<Cell>(); + for (Zone zone : zones) { + result.addAll(zone.getCell()); + } + return result; + } + + /** + * used here and in Rule (CantonnementPreSimu) + * + * @param zoneMet + * @param zonePop + * @return + */ + public int nbCellInter(Collection<Zone> zoneMet, Zone zonePop) { + List<Cell> cells = getCells(zoneMet); + List<Cell> tmp = new ArrayList<Cell>(cells); + tmp.retainAll(zonePop.getCell()); + return tmp.size(); + } + + /////////////////////////////////////////////////////////////////////////// + // + // + // + /////////////////////////////////////////////////////////////////////////// + + /** + * @param N + * @param pop + * @param date + * @return + * @throws IsisFishException + * @throws TopiaException + */ + private MatrixND matrixAbundancePerCell(MatrixND N, Population pop, + Date date, MatrixND matrixFishingMortality) throws TopiaException, IsisFishException { + + List<PopulationGroup> groups = pop.getPopulationGroup(); + List<Zone> zones = pop.getPopulationZone(); + List<Cell> allCells = getCells(zones); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_ABUNDANCE + "_PER_CELL", + new List[]{groups, zones, allCells}, + new String[]{n_("Groups"), n_("Zones"), n_("Cells")}); + + for (int g=0; g < groups.size(); g++) { + PopulationGroup group = groups.get(g); + for (int z=0; z < zones.size(); z++) { + Zone zone = zones.get(z); + List<Cell> cells = zone.getCell(); + for (int c=0; c<cells.size(); c++) { + Cell cell = cells.get(c); + double value = survivalRatePerCell(date, group, zone, + cell, matrixFishingMortality); + double n = N.getValue(g, z) / zone.sizeCell(); + value *= n; + result.setValue(g, z, c, value); + } + } + } + + return result; + } + + /** + * Utilise pour le calcule en Cell + * @param N + * @param pop + * @param date + * @return + * @throws IsisFishException + * @throws TopiaException + */ + public MatrixND matrixAbundance(MatrixND N, Population pop, Date date) + throws TopiaException, IsisFishException { + + MatrixND matrixFishingMortalityPerCell = matrixFishingMortalityPerCell(date, pop); + + MatrixND result = matrixAbundancePerCell(N, pop, date, matrixFishingMortalityPerCell); + result = result.sumOverDim(2); + result = result.reduceDims(2); + result.setName(ResultName.MATRIX_ABUNDANCE); + + return result; + } + + /** + * Utilise pour le calcule en Zone + * @param N + * @param pop + * @param date + * @return + * @throws IsisFishException + * @throws TopiaException + */ + public MatrixND matrixAbundance(MatrixND N, Population pop, Date date, MatrixND matrixFishingMortality) throws TopiaException, IsisFishException { + List<PopulationGroup> groups = pop.getPopulationGroup(); + List<Zone> zones = pop.getPopulationZone(); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_ABUNDANCE, + new List[]{groups, zones}, + new String[]{n_("Groups"), n_("Zones")}); + + for (int g=0; g < groups.size(); g++) { + PopulationGroup group = groups.get(g); + for (int z=0; z < zones.size(); z++) { + Zone zone = zones.get(z); + double value = survivalRatePerZone(date, group, zone, matrixFishingMortality); + double n = N.getValue(g, z); + value *= n; + result.setValue(g, z, value); + } + } + + return result; + } + + /** + * Utilise pour la mortalite des poissons, lorsqu'aucune strategie n'est + * selectionnee. + * @param N + * @param pop + * @param date + * @return + * @throws IsisFishException + * @throws TopiaException + */ + public MatrixND matrixAbundanceSsF(MatrixND N, Population pop, Date date) throws TopiaException, IsisFishException { + List<PopulationGroup> groups = pop.getPopulationGroup(); + List<Zone> zones = pop.getPopulationZone(); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_ABUNDANCE, + new List[]{groups, zones}, + new String[]{n_("Groups"), n_("Zones")}); + + for (int g=0; g < groups.size(); g++) { + PopulationGroup group = groups.get(g); + for (int z=0; z < zones.size(); z++) { + Zone zone = zones.get(z); + double M = group.getNaturalDeathRate(zone)/(double)Month.NUMBER_OF_MONTH; + double value = (double)Math.exp(-M);; + double n = N.getValue(g, z); + value *= n; + result.setValue(g, z, value); + } + } + + return result; + } + + /** + * @param date + * @param group + * @param zone + * @return + * @throws IsisFishException + * @throws TopiaException + */ + private double survivalRatePerZone(Date date, PopulationGroup group, Zone zone, MatrixND matrixFishingMortality) throws TopiaException, IsisFishException { + double F = totalFishingMortality(date, matrixFishingMortality).getValue(group, zone); //totalFishingMortality(date, group, zone); // rem perf: totalFishingMortality a deja ete calcul? + double M = group.getNaturalDeathRate(zone)/(double)Month.NUMBER_OF_MONTH; + double result = Math.exp(-(F+M)); + + return result; + } + + + /** + * @param date + * @param group + * @param zone + * @return + * @throws IsisFishException + * @throws TopiaException + */ + private double survivalRatePerCell(Date date, PopulationGroup group, Zone zone, + Cell cell, MatrixND matrixFishingMortalityPerCell) throws TopiaException, IsisFishException { + + double F = totalFishingMortalityPerCell(date, matrixFishingMortalityPerCell) + .getValue(group, zone, cell); //totalFishingMortality(date, group, zone); // rem perf: totalFishingMortality a deja ete calcul? + double M = group.getNaturalDeathRate(zone)/(double)Month.NUMBER_OF_MONTH; + double result = (double)Math.exp(-(F+M)); + + return result; + } + + /////////////////////////////////////////////////////////////////////////// + // + // + // + /////////////////////////////////////////////////////////////////////////// + + /** + * @param n + * @param pop + * @param date + * @return + */ + public MatrixND matrixBiomass(MatrixND N, Population pop, Date date) { + List<PopulationGroup> groups = N.getSemantics(0); + List<Zone> zones = N.getSemantics(1); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_BIOMASS, + new List[]{groups, zones}, + new String[]{n_("Groups"), n_("Zones")}); + + for (int g=0; g < groups.size(); g++) { + PopulationGroup group = groups.get(g); + double meanWeight = group.getMeanWeight(); + for (int z=0; z < zones.size(); z++) { + Zone zone = zones.get(z); + double n = N.getValue(group, zone); + double value = n * meanWeight; + result.setValue(group, zone, value); + } + } + + return result; + } + + public MatrixND matrixBiomassBeginMonth(MatrixND N, Population pop, Date date) { + List<PopulationGroup> groups = N.getSemantics(0); + List<Zone> zones = N.getSemantics(1); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_BIOMASS_BEGIN_MONTH, + new List[]{groups, zones}, + new String[]{n_("Groups"), n_("Zones")}); + + for (int g = 0; g < groups.size(); g++) { + PopulationGroup group = groups.get(g); + double meanWeight = group.getMeanWeight(); + for (int z = 0; z < zones.size(); z++) { + Zone zone = zones.get(z); + double n = N.getValue(group, zone); + double value = n * meanWeight; + result.setValue(group, zone, value); + } + } + return result; + } + + public MatrixND matrixAbondanceBeginMonth(MatrixND N, Population pop, Date date) { + List<PopulationGroup> groups = N.getSemantics(0); + List<Zone> zones = N.getSemantics(1); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_ABONDANCE_BEGIN_MONTH, + new List[]{groups, zones}, + new String[]{n_("Groups"), n_("Zones")}); + + for (int g = 0; g < groups.size(); g++) { + PopulationGroup group = groups.get(g); + for (int z = 0; z < zones.size(); z++) { + Zone zone = zones.get(z); + double value = N.getValue(group, zone); + result.setValue(group, zone, value); + } + } + return result; + } + + + /////////////////////////////////////////////////////////////////////////// + // + // + // + /////////////////////////////////////////////////////////////////////////// + + /** + * @param date + * @return + * @throws TopiaException + */ + public MatrixND matrixEffortPerStrategyMet(Date date) throws TopiaException { + List<Strategy> strategies = getStrategies(date); + List<Metier> metiers = getMetiers(date); + + MatrixND result = MatrixFactory.getInstance().create( + ResultName.MATRIX_EFFORT_PER_STRATEGY_MET, + new List[]{strategies, metiers}, + new String[]{n_("Strategies"), n_("Metiers")}); + + for (int s=0; s < strategies.size(); s++) { + Strategy str = strategies.get(s); + metiers = getMetiers(str, date); + for (int m=0; m < metiers.size(); m++) { + Metier metier = metiers.get(m); + double value = effortPerStrategyMet(str, metier, date); + result.setValue(str, metier, value); + } + } + +// for(Strategy str : strategies){ +// List<Metier> metierStr = getMetiers(str, date); +// for(Metier metier : metierStr) { +// double val = effortPerStrategyMet(str, metier, date); // rem perf: effortPerStrategyMet a deja ete calcul? +// result.setValue(str, metier, val); +// } +// } + + return result; + } + + /////////////////////////////////////////////////////////////////////////// + // + // + // + /////////////////////////////////////////////////////////////////////////// + +// /** +// * @param pop +// * @param date +// * @return +// */ +// public MatrixND matrixCatchWeightPerStrategyMet(Population pop, +// Date date, MatrixND matrixCatchPerStrategyMet) { +// List<PopulationGroup> groups = pop.getPopulationGroup(); +// +// MatrixND result = matrixCatchPerStrategyMet.copy(); +// result.setName(ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET); +// +// for(PopulationGroup group : groups){ +// MatrixND sub = result.getSubMatrix(2, group, 1); +// double meanWeight = group.getMeanWeight(); +// sub.mults(meanWeight); +// } +// +// return result; +// } + + /** + * + * + * @param pop + * @param date + * @return + */ + public MatrixND matrixDiscardWeightPerStrategyMetPerZonePop(Population pop, + Date date, MatrixND matrixDiscardPerStrategyMetPerZonePop) { + List<PopulationGroup> groups = pop.getPopulationGroup(); + + MatrixND result = matrixDiscardPerStrategyMetPerZonePop.copy(); + result.setName(ResultName.MATRIX_DISCARDS_WEIGHT_PER_STR_MET_PER_ZONE_POP); + + for(PopulationGroup group : groups){ + MatrixND sub = result.getSubMatrix(2, group, 1); + double meanWeight = group.getMeanWeight(); + sub.mults(meanWeight); + } + + return result; + } + +} Added: isis-fish/trunk/src/test/resources/test-database/simulators/DefaultSimulator.java =================================================================== --- isis-fish/trunk/src/test/resources/test-database/simulators/DefaultSimulator.java (rev 0) +++ isis-fish/trunk/src/test/resources/test-database/simulators/DefaultSimulator.java 2009-02-27 18:04:56 UTC (rev 1895) @@ -0,0 +1,581 @@ +/* *##% + * Copyright (C) 2006 + * Ifremer, 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. + *##%*/ + +/* * + * DefaultSimulator.java + * + * Created: 21 ao?t 2006 10:57:46 + * + * @author poussin + * @version $Revision: 1.19 $ + * + * Last update: $Date: 2007-11-06 18:16:14 $ + * by : $Author: bpoussin $ + */ + +package simulators; + +import static org.codelutin.i18n.I18n._; +import static org.codelutin.i18n.I18n.n_; + +import java.util.Collection; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.codelutin.math.matrix.MatrixFactory; +import org.codelutin.math.matrix.MatrixND; +import org.codelutin.topia.TopiaContext; +import org.codelutin.topia.TopiaException; + +import scripts.GravityModel; +import scripts.ResultName; +import scripts.SiMatrix; +import fr.ifremer.isisfish.IsisFishException; +import fr.ifremer.isisfish.datastore.ResultStorage; +import fr.ifremer.isisfish.entities.Metier; +import fr.ifremer.isisfish.entities.Population; +import fr.ifremer.isisfish.entities.PopulationSeasonInfo; +import fr.ifremer.isisfish.entities.Strategy; +import fr.ifremer.isisfish.entities.Zone; +import fr.ifremer.isisfish.rule.Rule; +import fr.ifremer.isisfish.simulator.MetierMonitor; +import fr.ifremer.isisfish.simulator.PopulationMonitor; +import fr.ifremer.isisfish.simulator.ResultManager; +import fr.ifremer.isisfish.simulator.RuleMonitor; +import fr.ifremer.isisfish.simulator.SimulationContext; +import fr.ifremer.isisfish.simulator.SimulationControl; +import fr.ifremer.isisfish.simulator.SimulationParameter; +import fr.ifremer.isisfish.simulator.Simulator; +import fr.ifremer.isisfish.types.Date; +import fr.ifremer.isisfish.types.Month; + +/** + * @author poussin + * + */ + +public class DefaultSimulator implements Simulator { + + /** to use log facility, just put in your code: log.info("..."); */ + static private Log log = LogFactory.getLog(DefaultSimulator.class); + + /** + * Called by isis don't modify signature + */ + public void simulate(SimulationContext context) throws Exception { + + SimulationParameter param = context.getSimulationStorage().getParameter(); + SimulationControl control = context.getSimulationControl(); + int lastYear = param.getNumberOfYear(); + int lastDate = lastYear * Month.NUMBER_OF_MONTH; + Date date = control.getDate(); + + ResultManager resManager = context.getResultManager(); + TopiaContext db = context.getDB(); + + SiMatrix siMatrix = SiMatrix.getSiMatrix(context); + GravityModel gravityModel = new GravityModel(context, siMatrix); + + PopulationMonitor populationMonitor = context.getPopulationMonitor(); + MetierMonitor metierMonitor = context.getMetierMonitor(); + RuleMonitor ruleMonitor = context.getRuleMonitor(); + + List<Population> allpops = siMatrix.getPopulations(date); + populationMonitor.init(allpops); + + for (Population pop : allpops) { + MatrixND N = param.getNumberOf(pop); + N.setName(ResultName.MATRIX_ABUNDANCE); + populationMonitor.setN(pop, N); + } + + // + // Rule initialisation + // + List<Rule> rules = param.getRules(); + control.setText("Rules initialisation:" + rules); + for (Rule rule : rules) { + rule.init(context); + log.info("Rule " +rule.getClass().getSimpleName()+ " initialized"); + } + + // + // Commit all change done un init rules methods. + // + context.getDB().commitTransaction(); + + // + // Simulation loop + // + while (date.getDate() < lastDate) { + // + // if user stop simulation before last year + // + if (control.isStopSimulationRequest()) { + break; + } + + control.setDate(date); + control.setProgress(date.getDate()); + control.setText(_("begin step " + date)); + + // raz des metiers interdits et des licences + metierMonitor.clear(); + + if (date.getMonth().equals(Month.JANUARY)) { + populationMonitor.clearCatch(); + } + + // only if there are one or more strategy + if (siMatrix.getStrategies(date).size() > 0) { + if (resManager.isEnabled(ResultName.MATRIX_NO_ACTIVITY)) { + MatrixND mat = metierMonitor.getOrCreateNoActivity(date, + ResultName.MATRIX_NO_ACTIVITY, + siMatrix.getStrategies(date), + siMatrix.getMetiers(date)); + resManager.addResult(date, mat); + } + } + + // + // Rule condition evaluation + // + control.setText("Evalute Rules conditions ("+rules.size()+" rules)"); + for (Rule rule : rules) { + for (Metier metier : siMatrix.getMetiers(date)) { + boolean active = false; + try { + active = rule.condition(context, date, metier); + } catch (Exception eee) { + if (log.isWarnEnabled()) { + log.warn("Can't evaluate rule condition for: " + rule, eee); + } + } + ruleMonitor.setEvaluationCondition(date, rule, metier, active); + if (active) { + log.info("Activate rule: " + rule.getClass().getSimpleName()); + resManager.addActiveRule(date, rule); + } + } + } + + // + // Rule pre action + // + control.setText("Do pre action Rules"); + for (Rule rule : rules) { + for (Metier metier : siMatrix.getMetiers(date)) { + boolean condition = ruleMonitor.getEvalutionCondition(date, rule, metier); + if (condition) { + rule.preAction(context, date, metier); + } + } + } + + // + // Keep modification's information done in rule + // + if (resManager.isEnabled(ResultName.MATRIX_METIER_ZONE)) { + MatrixND metierZone = siMatrix.getMetierZone(date); + resManager.addResult(date, metierZone); + } + + // + // Simulate one step for all pop + // + control.setText("Simulate one month"); + for (Population pop : siMatrix.getPopulations(date)) { + computeMonth(context, siMatrix, date, pop); + } + + // + // Add some result not population dependante + // + + // only if there are one or more strategy + if (siMatrix.getStrategies(date).size() > 0) { + + control.setText("Add some results"); + if (resManager.isEnabled(ResultName.MATRIX_EFFORT_PER_STRATEGY_MET)) { + MatrixND effortPerStrategyMet = siMatrix.matrixEffortPerStrategyMet(date); + resManager.addResult(date, effortPerStrategyMet); + } + + if (resManager.isEnabled(ResultName.MATRIX_STD_TRAVEL_EFFORT_PER_STRATEGY_MET)) { + MatrixND stdTravelEffortPerStrategyMet = siMatrix.matrixEffortPerStrategyMet(date); + resManager.addResult(date, stdTravelEffortPerStrategyMet); + } + + if (resManager.isEnabled(ResultName.MATRIX_EFFORT_PER_ZONE_POP)) { + MatrixND effortPerZonePop = siMatrix.matrixEffortPerStrategyMet(date); + resManager.addResult(date, effortPerZonePop); + } + + + // + // Add economics results + // + if (!"false".equalsIgnoreCase(param.getTagValue().get("ecoResult"))) { + control.setText("Add economics results"); + saveGravityModel(date, resManager, gravityModel); + } + } + + // + // Add economics results + // + if (resManager.isEnabled(ResultName.MATRIX_PRICE)) { + for (Population pop : siMatrix.getPopulations(date)) { + MatrixND matPrice = siMatrix.matrixPrice(date, pop); + resManager.addResult(date, pop, matPrice); + } + } + + + + // + // Rule post action + // + control.setText("Do post action Rules"); + for (Rule rule : rules) { + for (Metier metier : siMatrix.getMetiers(date)) { + if (ruleMonitor.getEvalutionCondition(date, rule, metier)) { + rule.postAction(context, date, metier); + } + } + } + + // discard and landing must be done after post action rules + // only if there are one or more strategy + if (siMatrix.getStrategies(date).size() > 0) { + + control.setText("Compute discard and landing"); + for (Population pop : siMatrix.getPopulations(date)) { + // + // discard computation + // + MatrixND discard = populationMonitor.getDiscard(date, pop); + if (discard != null || date.getDate() == 0) { // force discard for the first month to have discard in result + if (discard == null) { + discard = MatrixFactory.getInstance().create(ResultName.MATRIX_DISCARDS_PER_STR_MET_PER_ZONE_POP, + new List[]{siMatrix.getStrategies(date), + siMatrix.getMetiers(date), + pop.getPopulationGroup(), + pop.getPopulationZone()}, + new String[]{n_("Strategies"), n_("Metiers"), n_("Groups"), n_("Zones")}); + } + resManager.addResult(date, pop, discard); + + if (resManager.isEnabled(ResultName.MATRIX_DISCARDS_WEIGHT_PER_STR_MET_PER_ZONE_POP)) { + MatrixND discardWeightPerStrategyMet = siMatrix.matrixDiscardWeightPerStrategyMetPerZonePop(pop, date, discard); + resManager.addResult(date, pop, discardWeightPerStrategyMet); + } + + } + + // + // add landing result + // + if (resManager.isEnabled(ResultName.MATRIX_LANDING_PER_MET)) { + MatrixND landing = MatrixFactory.getInstance().create(populationMonitor.getCatch(pop)); + if (discard != null) { + landing = landing.minus(discard); + } + landing.setName(ResultName.MATRIX_LANDING_PER_MET); + resManager.addResult(date, pop, landing); + } + } + } + + // + // revert modification for next step + // + control.setText("Rollback rules changes"); + db.rollbackTransaction(); + + // + // commit result + // + control.setText("Commit results"); + TopiaContext tx = context.getDbResult(); + tx.commitTransaction(); + + // + // Go next step + // + date = date.next(); + } + } + + protected boolean isEffortByCell(SimulationContext context) { + boolean result = "true".equalsIgnoreCase(context.getSimulationStorage() + .getParameter().getTagValue().get("effortByCell")); + return result; + } + + protected void computeMonth(SimulationContext context, SiMatrix siMatrix, Date date, Population pop) throws IsisFishException, TopiaException { + // to add result + ResultStorage resManager = context.getSimulationStorage().getResultStorage(); + + PopulationMonitor popMon = context.getPopulationMonitor(); + MatrixND N = popMon.getN(pop); + + if (log.isInfoEnabled()) { + log.info("====================== begin "+ date + " - " + pop +" =========================== " + System.currentTimeMillis()); + log.info("N: " + N); + } + + // add N and biomass result now, before computation + // N is reassigned during computation + resManager.addResult(date, pop, N); + + if (resManager.isEnabled(ResultName.MATRIX_BIOMASS)) { + MatrixND biomass = siMatrix.matrixBiomass(N, pop, date); + resManager.addResult(date, pop, biomass); + } + + Month month = date.getMonth(); + PopulationSeasonInfo info = pop.getPopulationSeasonInfo(month); + + // group change + MatrixND CA = null; + if (date.getDate() == 0) { + CA = MatrixFactory.getInstance().matrixId(pop.sizePopulationGroup()*pop.sizePopulationZone()); + } else { + CA = info.getGroupChangeMatrix(month); + } + + log.debug("CA: " + CA); + + //migration + MatrixND M = info.getMigrationMatrix(month, N); + log.debug("M: " + M); + //emigration + MatrixND EM = info.getEmigrationMatrix(month, N); + log.debug("EM: " + EM); + //immigration + MatrixND IM = info.getImmigrationMatrix(month, N).transpose(); + log.debug("IM: " + IM); + + // pour les premiers calculs on met N en une matrice 1D + MatrixND N1D = pop.N2DToN1D(N); + log.debug("N1D: " + N1D); + + MatrixND tmp0 = N1D.mult(CA); + MatrixND tmp1 = M.minus(EM); + MatrixND tmp2 = tmp0.mult(tmp1); + MatrixND tmp3 = tmp2.add(IM); + + log.debug("N1D after mig: " + tmp3); + + // On reconvertie en une matrice Semantique + N = pop.split2D(tmp3); + + log.debug("N after mig: " + N); + + //Recrutement + MatrixND R = info.getReproductionMatrix(month, N); + log.debug("R: " + R); + + // ajout de la matrice R dans le suivi de la pop comme etant + // la reproduction pour le mois courant. + popMon.setReproduction(date, pop, R); + + // recrutement + MatrixND recruitment = popMon.getRecruitment(date, pop); + log.debug("recruitment: " + recruitment); + + // mortalite de la reproduction + popMon.applyReproductionMortality(pop); + + N = N.add(recruitment); + log.debug("N after recru: " + N); + + if (resManager.isEnabled(ResultName.MATRIX_ABONDANCE_BEGIN_MONTH)) { + MatrixND abondanceBM = siMatrix.matrixAbondanceBeginMonth(N, pop, date); + resManager.addResult(date, pop, abondanceBM); + } + + if (resManager.isEnabled(ResultName.MATRIX_BIOMASS_BEGIN_MONTH)) { + MatrixND biomassBM = siMatrix.matrixBiomassBeginMonth(N, pop, date); + resManager.addResult(date, pop, biomassBM); + } + + + MatrixND abundance = N; + // compute fishing matrix only if there are one or more strategy + if (siMatrix.getStrategies(date).size() > 0) { + // compute some Matrix and add result + + // this matrix is necessary for PopulationMonitor.holdCatch (reused in rule) + MatrixND catchPerStrategyMetPerZonePop; + + if (isEffortByCell(context)) { + abundance = siMatrix.matrixAbundance(N, pop, date); + catchPerStrategyMetPerZonePop = + siMatrix.matrixCatchPerStrategyMetPerZonePop(N, pop, date); + } else { // en zone + MatrixND matrixFishingMortality = siMatrix.matrixFishingMortality(date, pop); + resManager.addResult(date, pop, matrixFishingMortality); + + abundance = siMatrix.matrixAbundance(N, pop, date, matrixFishingMortality); + + // this matrix is necessary for matrixCatchPerStrategyMet + MatrixND catchRatePerStrategyMet = siMatrix.matrixCatchRatePerStrategyMetPerZone(pop, date, matrixFishingMortality); + resManager.addResult(date, pop, catchRatePerStrategyMet); + + catchPerStrategyMetPerZonePop = + siMatrix.matrixCatchPerStrategyMetPerZone(N, pop, date, catchRatePerStrategyMet); + + } + + popMon.holdCatch(pop, catchPerStrategyMetPerZonePop); + resManager.addResult(date, pop, catchPerStrategyMetPerZonePop); + + if (resManager.isEnabled(ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP)) { + MatrixND catchWeightPerStrategyMet = + siMatrix.matrixCatchWeightPerStrategyMetPerZonePop(date, pop, + catchPerStrategyMetPerZonePop); + resManager.addResult(date, pop, catchWeightPerStrategyMet); + } + + if (isEffortByCell(context)) { + MatrixND catchPerStrategyMetPerZoneMet = + siMatrix.matrixCatchPerStrategyMetPerZoneMet(N, pop, date); + resManager.addResult(date, pop, catchPerStrategyMetPerZoneMet); + + if (resManager.isEnabled(ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_MET)) { + MatrixND catchWeightPerStrategyMet = + siMatrix.matrixCatchWeightPerStrategyMetPerZoneMet(date, pop, + catchPerStrategyMetPerZoneMet); + resManager.addResult(date, pop, catchWeightPerStrategyMet); + } + } + + + } else { // no strategies + // compute only if fishing mortality =0 to apply Natural Mortality + abundance = siMatrix.matrixAbundanceSsF(N, pop, date); + } + log.debug("abundance: " + abundance); + + // Keep new N + popMon.setN(pop, abundance); + + log.debug("====================== end " + date + " - " + pop +" ==========================="); + + } + + /** + * @param date + * @param resManager + * @throws IsisFishException + * @throws TopiaException + */ + private void saveGravityModel(Date date, ResultManager resManager, GravityModel gravityModel) throws IsisFishException, TopiaException { + if (resManager.isEnabled(ResultName.MATRIX_FISHING_TIME_PER_MONTH_PER_VESSEL)) { + MatrixND mat = gravityModel.matrixFishingTimePerMonthPerVessel(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_FUEL_COSTS_OF_TRAVEL_PER_VESSEL)) { + MatrixND mat = gravityModel.matrixFuelCostsOfTravelPerVessel(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_COSTS_OF_FISHING_PER_VESSEL)) { + MatrixND mat = gravityModel.matrixCostsOfFishingPerVessel(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_FUEL_COSTS_PER_VESSEL)) { + MatrixND mat = gravityModel.matrixFuelCostsOfTravelPerVessel(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_REPAIR_AND_MAINTENANCE_GEAR_COSTS_PER_VESSEL)) { + MatrixND mat = gravityModel.matrixRepairAndMaintenanceGearCostsPerVessel(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_OTHER_RUNNING_COSTS_PER_VESSEL)) { + MatrixND mat = gravityModel.matrixOtherRunningCostsPerVessel(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_SHARED_NOT_FIXED_COSTS_PER_VESSEL)) { + MatrixND mat = gravityModel.matrixSharedNotFixedCostsPerVessel(date); + resManager.addResult(date, mat); + } +// if (resManager.isEnabled(ResultName.MATRIX_SHARED_FIXED_COSTS_PER_VESSEL_PER_MET)) { +// MatrixND mat = gravityModel.matrixSharedFixedCostsPerVesselPerMet(date); +// resManager.addResult(date, mat); +// } + if (resManager.isEnabled(ResultName.MATRIX_GROSS_VALUE_OF_LANDINGS_PER_SPECIES_PER_STRATEGY_MET)) { + MatrixND mat = gravityModel.matrixGrossValueOfLandingsPerSpeciesPerStrategyMet(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_GROSS_VALUE_OF_LANDINGS_PER_STRATEGY_MET)) { + MatrixND mat = gravityModel.matrixGrossValueOfLandingsPerStrategyMet(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_GROSS_VALUE_OF_LANDINGS_PER_STRATEGY_MET_PER_VESSEL)) { + MatrixND mat = gravityModel.matrixGrossValueOfLandingsPerStrategyMetPerVessel(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET)) { + MatrixND mat = gravityModel.matrixNetValueOfLandingsPerStrategyMet(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET_PER_VESSEL)) { + MatrixND mat = gravityModel.matrixNetValueOfLandingsPerStrategyMetPerVessel(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_NET_RENEVUE_TO_SHARE_PER_STRATEGY_MET_PER_VESSEL)) { + MatrixND mat = gravityModel.matrixNetRenevueToSharePerStrategyMetPerVessel(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_CREW_SHARE_PER_STRATEGY_MET_PER_VESSEL)) { + MatrixND mat = gravityModel.matrixCrewSharePerStrategyMetPerVessel(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_OWNER_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_MET_PER_VESSEL)) { + MatrixND mat = gravityModel.matrixOwnerMarginOverVariableCostsPerStrategyMetPerVessel(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_VESSEL_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_MET_PER_VESSEL)) { + MatrixND mat = gravityModel.matrixVesselMarginOverVariableCostsPerStrategyMetPerVessel(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_OWNER_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_PER_VESSEL)) { + MatrixND mat = gravityModel.matrixOwnerMarginOverVariableCostsPerStrategyPerVessel(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_OWNER_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY)) { + MatrixND mat = gravityModel.matrixOwnerMarginOverVariableCostsPerStrategy(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_VESSEL_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_PER_VESSEL)) { + MatrixND mat = gravityModel.matrixVesselMarginOverVariableCostsPerStrategyPerVessel(date); + resManager.addResult(date, mat); + } + if (resManager.isEnabled(ResultName.MATRIX_VESSEL_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY)) { + MatrixND mat = gravityModel.matrixVesselMarginOverVariableCostsPerStrategy(date); + resManager.addResult(date, mat); + } + } + +} + +