Isis-fish-commits
Threads by month
- ----- 2026 -----
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2010 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2009 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2008 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2007 -----
- December
- November
July 2011
- 2 participants
- 26 discussions
r3446 - isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher
by chatellier@users.labs.libre-entreprise.org 18 Jul '11
by chatellier@users.labs.libre-entreprise.org 18 Jul '11
18 Jul '11
Author: chatellier
Date: 2011-07-18 15:38:28 +0000 (Mon, 18 Jul 2011)
New Revision: 3446
Log:
Launch sub simulations with R args
Modified:
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SubProcessSimulationLauncher.java
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 2011-07-15 13:12:45 UTC (rev 3445)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SubProcessSimulationLauncher.java 2011-07-18 15:38:28 UTC (rev 3446)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2002 - 2010 Ifremer, Code Lutin, Benjamin Poussin
+ * Copyright (C) 2002 - 2011 Ifremer, Code Lutin, Benjamin Poussin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -36,6 +36,7 @@
import java.net.URLClassLoader;
import java.rmi.RemoteException;
import java.util.ArrayList;
+import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
@@ -185,28 +186,50 @@
log.debug("classpath to use : " + classpath);
}
+ // common args
+ List<String> command = new ArrayList<String>();
+ command.add(java);
+ command.add("-Xmx1024M");
+
+ // jri args
+ String libraryPath = System.getProperty("java.library.path");
+ if (StringUtils.isNotBlank(libraryPath)) {
+ command.add("-Djava.library.path=\"" + libraryPath + "\"");
+ }
+ String rType = System.getProperty("R.type");
+ if (StringUtils.isNotBlank(rType)) {
+ command.add("-DR.type=\"" + rType + "\"");
+ }
+
+ // common args
+ command.add("-classpath");
+ command.add(classpath);
+ command.add(IsisFish.class.getName());
+ command.add("--option");
+ command.add("launch.ui");
+ command.add("false");
+
// prepare le process
ProcessBuilder processBuilder = null;
if (tempPrescriptFile != null) {
- processBuilder = new ProcessBuilder(java, "-Xmx1024M", "-classpath",
- classpath, IsisFish.class.getName(), "--option", "launch.ui",
- "false", "--simulateWithSimulationAndScript", simulationId,
- simulationZip.getAbsolutePath(), tempPrescriptFile.getAbsolutePath());
+ command.add("--simulateWithSimulationAndScript");
+ command.add(simulationId);
+ command.add(simulationZip.getAbsolutePath());
+ command.add(tempPrescriptFile.getAbsolutePath());
}
else {
- processBuilder = new ProcessBuilder(java, "-Xmx1024M", "-classpath",
- classpath, IsisFish.class.getName(), "--option", "launch.ui",
- "false", "--simulateWithSimulation", simulationId,
- simulationZip.getAbsolutePath());
+ command.add("--simulateWithSimulation");
+ command.add(simulationId);
+ command.add(simulationZip.getAbsolutePath());
}
+ processBuilder = new ProcessBuilder(command);
processBuilder.redirectErrorStream(true);
// demarrage du process
Process process = processBuilder.start();
if (log.isInfoEnabled()) {
- log.info(_("SubProcess start: %s %s", process, processBuilder
- .command()));
+ log.info(_("SubProcess start: %s %s", process, processBuilder.command()));
}
// prepare de thread de surveillance du process si control n'est pas null
@@ -246,8 +269,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;
1
0
r3445 - in isis-fish/trunk: . doc src/main/java/fr/ifremer/isisfish src/main/java/fr/ifremer/isisfish/actions src/main/java/fr/ifremer/isisfish/aspect src/main/java/fr/ifremer/isisfish/cron src/main/java/fr/ifremer/isisfish/datastore src/main/java/fr/ifremer/isisfish/datastore/migration src/main/java/fr/ifremer/isisfish/equation src/main/java/fr/ifremer/isisfish/mexico src/main/java/fr/ifremer/isisfish/mexico/export src/main/java/fr/ifremer/isisfish/simulator src/main/java/fr/ifremer/isi
by chatellier@users.labs.libre-entreprise.org 15 Jul '11
by chatellier@users.labs.libre-entreprise.org 15 Jul '11
15 Jul '11
Author: chatellier
Date: 2011-07-15 13:12:45 +0000 (Fri, 15 Jul 2011)
New Revision: 3445
Log:
Refactoring :
- analyseplan > simulationplan
- sensitivity > sensitivityanalysis
Removed:
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/ClasspathTemplateLoader.java
Modified:
isis-fish/trunk/changelog.txt
isis-fish/trunk/doc/Todo.rst
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/IsisConfig.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/IsisFish.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/actions/ImportAction.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/aspect/Trace.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/cron/RemoveOldFileTask.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/RuleStorage.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/SimulationPlanStorage.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/migration/DatabaseMigrationClass.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/migration/MigrationV0V32.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/migration/MigrationV32V33.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/equation/PopulationMaturityOgiveEquation.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/mexico/export/package-info.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/mexico/package-info.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationMeta.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameter.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameterCache.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameterImpl.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationPlanContext.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationPreScript.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulatorServerBadIdException.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/SimulationJob.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationMonitor.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/SimulationServiceTableModel.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulatorLauncher.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/package-info.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/MatrixType.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/MonthType.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/RangeOfValuesType.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/TimeStepType.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/TimeUnitType.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/CommonHandler.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/SimulationUI.jaxx
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/WelcomeHandler.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/InputHandler.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckRegion.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckResult.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckResultFrame.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckResultTableModel.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckResultTableRenderer.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/tree/FisheryTreeRenderer.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/tree/FisheryTreeSelectionModel.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/export/ExportListRenderer.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/package-info.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/rule/RuleComboModel.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/rule/RuleParametersFactorTableCellEditor.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/rule/RuleParametersFactorTableCellRenderer.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/sensitivityexport/SensitivityExportListRenderer.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/simulationplan/SimulationPlanComboModel.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/simulationplan/SimulationPlanComboRenderer.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/simulationplan/SimulationPlanListModel.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/simulationplan/SimulationPlanListRenderer.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/MatrixMapRenderer.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/MatrixSummaryRenderer.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/ResultHandler.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/YearSumDimensionAction.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/script/ScriptAction.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/script/ScriptUI.jaxx
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/script/package-info.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity/SensitivitySaveVerifier.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity/SensitivityUI.jaxx
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity/equation/EquationDomainRenderer.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/java/fr/ifremer/isisfish/ui/simulator/SimulUI.jaxx
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/filter/SimulationFilterPanelUI.jaxx
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/widget/editor/EquationTableEditor.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/ssh/ProgressMonitor.java
isis-fish/trunk/src/main/resources/i18n/isis-fish_en_GB.properties
isis-fish/trunk/src/main/resources/i18n/isis-fish_fr_FR.properties
isis-fish/trunk/src/main/resources/log4j.properties
isis-fish/trunk/src/test/java/fr/ifremer/isisfish/AbstractIsisFishTest.java
isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/SimulationParameterTest.java
isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/parameters_basic.properties
isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/parameters_plan.properties
Modified: isis-fish/trunk/changelog.txt
===================================================================
--- isis-fish/trunk/changelog.txt 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/changelog.txt 2011-07-15 13:12:45 UTC (rev 3445)
@@ -1,5 +1,8 @@
-isis-fish (3.4.0.0) test; urgency=low
+isis-fish (4.0.0.0) test; urgency=low
+ * Rename Date to TimeStep
+ * Rename AnalysePlan to SimulationPlan
+ * Rename SensitivityCalculator to SensitivityAnalysis
* Sensitivity calculator parameters are not lost anymore
* Add new community repository with commit access for users
* Remove maturity group unique constraints
Modified: isis-fish/trunk/doc/Todo.rst
===================================================================
--- isis-fish/trunk/doc/Todo.rst 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/doc/Todo.rst 2011-07-15 13:12:45 UTC (rev 3445)
@@ -30,7 +30,7 @@
- expliquer comment debugguer avec NetBeans
- mettre les valeurs pas defaut sur les champs
-Pour la version 4.0.0.0:
+Pour la version 5.0.0.0:
- db4o (test de perf pour simulation, sauvegarde/rendu des resultats)
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/IsisConfig.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/IsisConfig.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/IsisConfig.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -1055,11 +1055,11 @@
public static enum Action {
HELP(n_("Show help"), OtherAction.class.getName() + "#help", "-h", "--help"),
VERSION(n_("Show version"), OtherAction.class.getName() + "#version", "-v", "--version"),
-
- IMPORT_ANALYSE_PLAN(n_(""), ImportAction.class.getName() + "#importAnalysePlan", "--importAnalysePlan"),
+
IMPORT_EXPORT(n_(""), ImportAction.class.getName() + "#importExport", "--importExport"),
IMPORT_RULE(n_(""), ImportAction.class.getName() + "#importRule", "--importRule"),
IMPORT_SCRIPT(n_("Import one java file script source"), ImportAction.class.getName() + "#importScript", "--importScript"),
+ IMPORT_SIMULATION_PLAN(n_(""), ImportAction.class.getName() + "#importSimulationPlan", "--importSimulationPlan"),
IMPORT_SIMULATOR(n_(""), ImportAction.class.getName() + "#importSimulator", "--importSimulator"),
IMPORT_FORMULA(n_(""), ImportAction.class.getName() + "#importFormula", "--importFormula"),
IMPORT_REGION(n_(""), ImportAction.class.getName() + "#importRegion", "--importRegion"),
@@ -1067,19 +1067,19 @@
IMPORT_SIMULATION(n_(""), ImportAction.class.getName() + "#importSimulation", "--importSimulation"),
IMPORT_SCRIPT_MODULE(n_("Import zipped file containing all scripts directory structure"), ImportAction.class.getName() + "#importScriptModule", "--importScriptModule"),
- LIST_ANALYSE_PLAN(n_(""), ExportAction.class.getName() + "#listAnalysePlan", "--listAnalysePlan"),
LIST_EXPORT(n_(""), ExportAction.class.getName() + "#listExport", "--listExport"),
LIST_RULE(n_(""), ExportAction.class.getName() + "#listRule", "--listRule"),
LIST_SCRIPT(n_(""), ExportAction.class.getName() + "#listScript", "--listScript"),
+ LIST_SIMULATION_PLAN(n_(""), ExportAction.class.getName() + "#listSimulationPlan", "--listSimulationPlan"),
LIST_SIMULATOR(n_(""), ExportAction.class.getName() + "#listSimulator", "--listSimulator"),
LIST_FORMULA(n_(""), ExportAction.class.getName() + "#listFormula", "--listFormula"),
LIST_REGION(n_(""), ExportAction.class.getName() + "#listRegion", "--listRegion"),
LIST_SIMULATION(n_(""), ExportAction.class.getName() + "#listSimulation", "--listSimulation"),
- EXPORT_ANALYSE_PLAN(n_(""), ExportAction.class.getName() + "#exportAnalysePlan", "--exportAnalysePlan"),
EXPORT_EXPORT(n_(""), ExportAction.class.getName() + "#exportExport", "--exportExport"),
EXPORT_RULE(n_(""), ExportAction.class.getName() + "#exportRule", "--exportRule"),
EXPORT_SCRIPT(n_(""), ExportAction.class.getName() + "#exportScript", "--exportScript"),
+ EXPORT_SIMULATION_PLAN(n_(""), ExportAction.class.getName() + "#exportSimulationPlan", "--exportSimulationPlan"),
EXPORT_SIMULATOR(n_(""), ExportAction.class.getName() + "#exportSimulator", "--exportSimulator"),
EXPORT_FORMULA(n_(""), ExportAction.class.getName() + "#exportFormula", "--exportFormula"),
EXPORT_REGION(n_(""), ExportAction.class.getName() + "#exportRegion", "--exportRegion"),
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/IsisFish.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/IsisFish.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/IsisFish.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -112,6 +112,16 @@
// permet de faire fonctionner la compilation en webstart
System.setSecurityManager(null);
+ // i18n is not inited here
+ if (log.isInfoEnabled()) {
+ log.info("Starting Isis-Fish " + IsisConfig.getVersion() + " with args : " + java.util.Arrays.toString(args));
+ log.info("Date: " + SimpleDateFormat.getInstance().format(new java.util.Date()));
+ log.info("Java version: " + System.getProperty("java.runtime.version") + ", " + System.getProperty("java.vm.name"));
+ log.info("System arch: " + System.getProperty("os.arch"));
+ log.info("R_HOME: " + System.getenv("R_HOME") + ", R.type: " + System.getProperty("R.type"));
+ log.info("PATH: " + System.getenv("PATH"));
+ }
+
// initialisation de l'application
init(args);
@@ -207,16 +217,6 @@
*/
public static void init(String... args) throws Exception {
- // i18n is not inited here
- if (log.isInfoEnabled()) {
- log.info("Starting Isis-Fish " + IsisConfig.getVersion() + " with args : " + java.util.Arrays.toString(args));
- log.info("Date: " + SimpleDateFormat.getInstance().format(new java.util.Date()));
- log.info("Java version: " + System.getProperty("java.runtime.version") + ", " + System.getProperty("java.vm.name"));
- log.info("System arch: " + System.getProperty("os.arch"));
- log.info("R_HOME: " + System.getenv("R_HOME") + ", R.type: " + System.getProperty("R.type"));
- log.info("PATH: " + System.getenv("PATH"));
- }
-
// parsing des options à partir des arguments passés
config = new IsisConfig();
config.parse(args);
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/actions/ImportAction.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/actions/ImportAction.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/actions/ImportAction.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -58,7 +58,7 @@
this.config = config;
}
- public void importAnalysePlan(boolean force, File file) throws Exception {
+ public void importSimulationPlan(boolean force, File file) throws Exception {
String name = file.getName();
SimulationPlanStorage storage = SimulationPlanStorage.getSimulationPlan(name);
if(!force && storage.exists()) {
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/aspect/Trace.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/aspect/Trace.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/aspect/Trace.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2006 - 2010 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin
+ * Copyright (C) 2006 - 2011 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -68,7 +68,7 @@
@Expression("execution(* scripts..*(..))"
+ " || execution(* simulators..*(..))"
+ " || execution(* rules..*(..)) "
- + " || execution(* analyseplans..*(..)) "
+ + " || execution(* simulationplans..*(..)) "
+ " || execution(* formules..*(..))")
Pointcut executeMethod;
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/cron/RemoveOldFileTask.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/cron/RemoveOldFileTask.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/cron/RemoveOldFileTask.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2009 - 2010 Code Lutin, Chatellier Eric
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
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 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/RuleStorage.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -207,7 +207,7 @@
* <b>Be ware this method require to instanciate a Rule, so
* it would be better to call as often as possible.</b>
*
- * @return the descript of the instanciate AnalysePlan
+ * @return the descript of the instanciate Rule
* @see Doc
* @see Docable
*/
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/SimulationPlanStorage.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/SimulationPlanStorage.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/SimulationPlanStorage.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -43,8 +43,8 @@
import fr.ifremer.isisfish.vcs.VCSException;
/**
- * Class permettant de representer un plan d'analyse.
- * Un plan d'analyse est un fichier Java que l'on compile si besoin.
+ * Class permettant de representer un plan de simulation.
+ * Un plan de simulation est un fichier Java que l'on compile si besoin.
* <p/>
* Gere les fichiers VCS de type {@link SimulationPlan} (package simulationplans)
*
@@ -56,14 +56,14 @@
*
* Last update: $Date$ by : $Author$
*/
-public class SimulationPlanStorage extends JavaSourceStorage { // AnalysePlanStorage
+public class SimulationPlanStorage extends JavaSourceStorage { // SimulationPlanStorage
/** to use log facility, just put in your code: log.info(\"...\"); */
private static Log log = LogFactory.getLog(SimulationPlanStorage.class);
public final static String SIMULATION_PLAN_PATH = "simulationplans";
- /** Template freemarker pour les plans d'analyse . */
+ /** Template freemarker pour les plans de simulation . */
public static final String SIMULATION_PLAN_TEMPLATE = "templates/script/simulationplan.ftl";
@SuppressWarnings("unchecked")
@@ -202,10 +202,10 @@
}
/**
- * <b>Be ware this method require to instanciate a AnalysePlan, so
+ * <b>Be ware this method require to instanciate a SimulationPlan, so
* it would be better to call as often as possible.</b>
*
- * @return the descript of the instanciate AnalysePlan
+ * @return the descript of the instanciate SimulationPlan
* @see Doc
* @see Docable
*/
@@ -220,5 +220,4 @@
return result;
}
-} // AnalysePlanStorage
-
+} // SimulationPlanStorage
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/migration/DatabaseMigrationClass.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/migration/DatabaseMigrationClass.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/migration/DatabaseMigrationClass.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2011 Codelutin, Chatellier Eric
+ * Copyright (C) 2011 Ifremer, Codelutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/migration/MigrationV0V32.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/migration/MigrationV0V32.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/migration/MigrationV0V32.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2011 Codelutin, Chatellier Eric
+ * Copyright (C) 2011 Ifremer, Codelutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/migration/MigrationV32V33.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/migration/MigrationV32V33.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/migration/MigrationV32V33.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2011 Codelutin, Chatellier Eric
+ * Copyright (C) 2011 Ifremer, Codelutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/equation/PopulationMaturityOgiveEquation.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/equation/PopulationMaturityOgiveEquation.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/equation/PopulationMaturityOgiveEquation.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2011 Codelutin, Chatellier Eric
+ * Copyright (C) 2011 Ifremer, Codelutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/mexico/export/package-info.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/mexico/export/package-info.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/mexico/export/package-info.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 1999 - 2011 CodeLutin
+ * Copyright (C) 1999 - 2011 Ifremer, CodeLutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/mexico/package-info.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/mexico/package-info.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/mexico/package-info.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 1999 - 2011 CodeLutin
+ * Copyright (C) 1999 - 2011 Ifremer, CodeLutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationMeta.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationMeta.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationMeta.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -52,13 +52,13 @@
description(String.class),
simulationName(String.class),
simulatorName(String.class),
- analysePlanName(String.class),
+ simulationPlanName(String.class),
regionName(String.class),
otherInfo(String.class),
// int
numberOfYear(Integer.class),
- analysePlanNumber(Integer.class),
+ simulationPlanNumber(Integer.class),
// date interval
simulationInterval(DateInterval.class) {
@@ -75,7 +75,7 @@
// boolean
useOptimization(Boolean.class),
- useAnalysePlan(Boolean.class),
+ useSimulationPlan(Boolean.class),
useStatistic(Boolean.class),
usePreScript(Boolean.class),
onlyExport(Boolean.class),
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 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameter.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -124,7 +124,7 @@
/**
* Add extra rules.
*
- * Appelé par les plan d'analyse, pour ajouter des regles supplémentaires
+ * Appelé par les plan de simulation, pour ajouter des regles supplémentaires
* dans être integrés au zip.
*
* @param extraRules extra rules to add
@@ -329,32 +329,32 @@
List<SensitivityExport> sensitivityExport);
/**
- * Get use analyse plans property.
+ * Get use simulation plans property.
*
- * @return use analyse plan.
+ * @return use simulation plan.
*/
- public abstract boolean getUseAnalysePlan();
+ public abstract boolean getUseSimulationPlan();
/**
- * Set use analyse plans property.
+ * Set use simulation plans property.
*
- * @param useAnalysePlan use analyse plan to set
+ * @param useSimulationPlan use simulation plan to set
*/
- public abstract void setUseAnalysePlan(boolean useAnalysePlan);
+ public abstract void setUseSimulationPlan(boolean useSimulationPlan);
/**
- * Get simulation number in analyse plan.
+ * Get simulation number in simulation plan.
*
- * @return simulation number in analyse plan
+ * @return simulation number in simulation plan
*/
- public abstract int getAnalysePlanNumber();
+ public abstract int getSimulationPlanNumber();
/**
- * Set simulation number in analyse plan.
+ * Set simulation number in simulation plan.
*
- * @param analysePlanNumber analyse plan number to set
+ * @param simulationPlanNumber simulation plan number to set
*/
- public abstract void setAnalysePlanNumber(int analysePlanNumber);
+ public abstract void setSimulationPlanNumber(int simulationPlanNumber);
/**
* Get number of year to run to simulate.
@@ -578,9 +578,9 @@
* <ul>
* <li>strategies</li>
* <li>rules</li>
- * <li>analyseplans</li>
+ * <li>simulationplans</li>
* <li>sensitivityexports</li>
- * <li>calculator</li>
+ * <li>sensitivityanalysis</li>
* </ul>
*
* @return L'objet Properties representant les parametres
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameterCache.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameterCache.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameterCache.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -76,13 +76,13 @@
/** Parameter memory reference. */
protected SoftReference<SimulationParameter> ref;
-
+
/**
*
* @param param param to cache
*/
public SimulationParameterCache(SimulationParameter param) {
-
+
try {
paramFile = File.createTempFile("isis-fish-param", ".properties");
paramFile.deleteOnExit();
@@ -91,10 +91,10 @@
catch (IOException eee) {
throw new IsisFishRuntimeException("Can't cache param to disk", eee);
}
-
+
ref = new SoftReference<SimulationParameter>(param);
}
-
+
protected void store(SimulationParameter param) {
Properties prop = param.toProperties();
Writer writer = null;
@@ -497,41 +497,41 @@
}
/*
- * @see fr.ifremer.isisfish.simulator.SimulationParameter#getUseAnalysePlan()
+ * @see fr.ifremer.isisfish.simulator.SimulationParameter#getUseSimulationPlan()
*/
@Override
- public boolean getUseAnalysePlan() {
+ public boolean getUseSimulationPlan() {
SimulationParameter param = getParam();
- return param.getUseAnalysePlan();
+ return param.getUseSimulationPlan();
}
/*
- * @see fr.ifremer.isisfish.simulator.SimulationParameter#setUseAnalysePlan(boolean)
+ * @see fr.ifremer.isisfish.simulator.SimulationParameter#setUseSimulationPlan(boolean)
*/
@Override
- public void setUseAnalysePlan(boolean useAnalysePlan) {
+ public void setUseSimulationPlan(boolean useSimulationPlan) {
SimulationParameter param = getParam();
- param.setUseAnalysePlan(useAnalysePlan);
+ param.setUseSimulationPlan(useSimulationPlan);
store(param);
}
/*
- * @see fr.ifremer.isisfish.simulator.SimulationParameter#getAnalysePlanNumber()
+ * @see fr.ifremer.isisfish.simulator.SimulationParameter#getSimualtionPlanNumber()
*/
@Override
- public int getAnalysePlanNumber() {
+ public int getSimulationPlanNumber() {
SimulationParameter param = getParam();
- return param.getAnalysePlanNumber();
+ return param.getSimulationPlanNumber();
}
/*
- * @see fr.ifremer.isisfish.simulator.SimulationParameter#setAnalysePlanNumber(int)
+ * @see fr.ifremer.isisfish.simulator.SimulationParameter#setSimulationPlanNumber(int)
*/
@Override
- public void setAnalysePlanNumber(int analysePlanNumber) {
+ public void setSimulationPlanNumber(int simulationPlanNumber) {
SimulationParameter param = getParam();
- param.setAnalysePlanNumber(analysePlanNumber);
+ param.setSimulationPlanNumber(simulationPlanNumber);
store(param);
}
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameterImpl.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameterImpl.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameterImpl.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -123,7 +123,7 @@
/** La liste des regles de gestions a utiliser pour la simulation. */
protected List<Rule> rules;
- /** La liste des regles potentiellement ajoutée par les plans d'analyse. */
+ /** La liste des regles potentiellement ajoutée par les plans de simulation. */
protected List<String> extraRules;
/** La liste des plans a utiliser pour la simulation. */
@@ -138,14 +138,14 @@
/** Le script de pre simulation a utiliser. */
protected String preScript;
- /** Utilisation du plan d'analyse. */
- protected Boolean useAnalysePlan;
+ /** Utilisation du plan de simulation. */
+ protected Boolean useSimulationPlan;
/**
- * Le numero de sequence de la liste des plans d'analyse. Le premier
+ * Le numero de sequence de la liste des plans de simulation. Le premier
* élement du plan doit etre 0. Si la simulation ne fait pas partie d'un
* plan la valeur est -1. */
- protected Integer analysePlanNumber;
+ protected Integer simulationPlanNumber;
/** Export utilisés pour les analyses de sensibilités. */
protected List<SensitivityExport> sensitivityExports;
@@ -464,7 +464,7 @@
}
/*
- * @see fr.ifremer.isisfish.simulator.SimulationParameter#removeAnalysePlan(fr.ifremer.isisfish.simulator.SimulationPlan)
+ * @see fr.ifremer.isisfish.simulator.SimulationParameter#removeSimulationPlan(fr.ifremer.isisfish.simulator.SimulationPlan)
*/
@Override
public boolean removeSimulationPlan(SimulationPlan plan) {
@@ -472,7 +472,7 @@
}
/*
- * @see fr.ifremer.isisfish.simulator.SimulationParameter#getAnalysePlans()
+ * @see fr.ifremer.isisfish.simulator.SimulationParameter#getSimulationPlans()
*/
@Override
public List<SimulationPlan> getSimulationPlans() {
@@ -481,7 +481,7 @@
simulationPlans = new ArrayList<SimulationPlan>();
if (propertiesParameters != null) {
- // analyse plan
+ // simulation plan
String[] planList = propertiesParameters.getProperty("plans",
"").split(",");
int planIndex = 0;
@@ -855,51 +855,51 @@
* @see fr.ifremer.isisfish.simulator.SimulationParameter#getUseAnalysePlan()
*/
@Override
- public boolean getUseAnalysePlan() {
+ public boolean getUseSimulationPlan() {
- if (useAnalysePlan == null) {
+ if (useSimulationPlan == null) {
if (propertiesParameters != null) {
- useAnalysePlan = Boolean.valueOf(propertiesParameters.getProperty("useAnalysePlan", "false"));
+ useSimulationPlan = Boolean.valueOf(propertiesParameters.getProperty("useSimulationPlan", "false"));
} else {
- useAnalysePlan = Boolean.FALSE;
+ useSimulationPlan = Boolean.FALSE;
}
}
- return this.useAnalysePlan;
+ return this.useSimulationPlan;
}
/*
* @see fr.ifremer.isisfish.simulator.SimulationParameter#setUseAnalysePlan(boolean)
*/
@Override
- public void setUseAnalysePlan(boolean useAnalysePlan) {
- this.useAnalysePlan = useAnalysePlan;
+ public void setUseSimulationPlan(boolean useSimulationPlan) {
+ this.useSimulationPlan = useSimulationPlan;
}
/*
- * @see fr.ifremer.isisfish.simulator.SimulationParameter#getAnalysePlanNumber()
+ * @see fr.ifremer.isisfish.simulator.SimulationParameter#getSimulationPlanNumber()
*/
@Override
- public int getAnalysePlanNumber() {
+ public int getSimulationPlanNumber() {
- if (analysePlanNumber == null) {
+ if (simulationPlanNumber == null) {
if (propertiesParameters != null) {
- analysePlanNumber = Integer.valueOf(propertiesParameters.getProperty("analysePlanNumber", "-1"));
+ simulationPlanNumber = Integer.valueOf(propertiesParameters.getProperty("simulationPlanNumber", "-1"));
} else {
- analysePlanNumber = Integer.valueOf(-1);
+ simulationPlanNumber = Integer.valueOf(-1);
}
}
- return this.analysePlanNumber.intValue();
+ return this.simulationPlanNumber.intValue();
}
/*
- * @see fr.ifremer.isisfish.simulator.SimulationParameter#setAnalysePlanNumber(int)
+ * @see fr.ifremer.isisfish.simulator.SimulationParameter#setSimulationPlanNumber(int)
*/
@Override
- public void setAnalysePlanNumber(int analysePlanNumber) {
- this.analysePlanNumber = analysePlanNumber;
+ public void setSimulationPlanNumber(int simulationPlanNumber) {
+ this.simulationPlanNumber = simulationPlanNumber;
}
/*
@@ -1313,8 +1313,8 @@
result.useStatistic = getUseStatistic();
result.usePreScript = getUsePreScript();
result.preScript = getPreScript();
- result.useAnalysePlan = getUseAnalysePlan();
- result.analysePlanNumber = getAnalysePlanNumber();
+ result.useSimulationPlan = getUseSimulationPlan();
+ result.simulationPlanNumber = getSimulationPlanNumber();
if (exportNames != null) {
result.exportNames = new LinkedList<String>(exportNames);
}
@@ -1375,9 +1375,9 @@
result.append(getDescription()).append('\n');
result.append("--------------------\n");
- if (getUseAnalysePlan()) {
+ if (getUseSimulationPlan()) {
result.append(_("isisfish.params.toString.plan.number",
- getAnalysePlanNumber()));
+ getSimulationPlanNumber()));
}
RegionStorage region = getRegion();
@@ -1424,7 +1424,7 @@
}
result.append("\n\n");
- // analyse plans
+ // simulation plans
for (SimulationPlan plan : getSimulationPlans()) {
String name = RuleStorage.getName(plan);
String param = "";
@@ -1571,11 +1571,11 @@
result.setProperty("numberOfSensitivitySimulation", String
.valueOf(getNumberOfSensitivitySimulation()));
- // calculator name
+ // analysis name
if (sensitivityAnalysis != null) {
- String calculatorName = SensitivityAnalysisStorage
+ String analysisName = SensitivityAnalysisStorage
.getName(getSensitivityAnalysis());
- result.setProperty("sensitivitycalculator", calculatorName);
+ result.setProperty("sensitivityanalysis", analysisName);
// calculator parameter
Properties calculatorParams = StorageHelper.getParamsAsProperties(0,
@@ -1583,9 +1583,9 @@
result.putAll(calculatorParams);
} else {
if (propertiesParameters != null
- && propertiesParameters.containsKey("sensitivitycalculator")) {
+ && propertiesParameters.containsKey("sensitivityanalysis")) {
result.setProperty("sensitivitycalculator",
- propertiesParameters.getProperty("sensitivitycalculator"));
+ propertiesParameters.getProperty("sensitivityanalysis"));
for (String key : propertiesParameters.stringPropertyNames()) {
if (key.startsWith("sensitivity.")) {
result.setProperty(key, propertiesParameters.getProperty(key));
@@ -1621,8 +1621,8 @@
result.setProperty("usePreScript", String.valueOf(getUsePreScript()));
result.setProperty("preScript", getPreScript());
- result.setProperty("useAnalysePlan", String.valueOf(getUseAnalysePlan()));
- result.setProperty("analysePlanNumber", String.valueOf(getAnalysePlanNumber()));
+ result.setProperty("useSimulationPlan", String.valueOf(getUseSimulationPlan()));
+ result.setProperty("simulationPlanNumber", String.valueOf(getSimulationPlanNumber()));
String resultList = "";
for (String r : getResultEnabled()) {
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationPlanContext.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationPlanContext.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationPlanContext.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -46,13 +46,13 @@
/** Simulation id. */
protected String id;
- /** Analyse plan number. */
+ /** Simulation plan number. */
protected int number = 0;
/** Simulation parameters. */
protected SimulationParameter param;
- /** Additionnal context values. */
+ /** Additional context values. */
protected Map<String, Object> values = new HashMap<String, Object>();
public SimulationPlanContext(String id, SimulationParameter param) {
@@ -70,7 +70,7 @@
}
/**
- * Get current analyze plan simulation count.
+ * Get current simulation plan simulation count.
*
* Warning, in after simulation, refer to generated simulation count,
* not ended simulation number.
@@ -79,7 +79,7 @@
*
* @return the number
*
- * @deprecated use {@code nextSimulation.getParameter().getAnalysePlanNumber()}
+ * @deprecated use {@code nextSimulation.getParameter().getSimulationPlanNumber()}
*/
public int getNumber() {
return number;
@@ -138,7 +138,7 @@
}
/**
- * Get {@link SimulationStorage} for specified analyse plan number.
+ * Get {@link SimulationStorage} for specified simulation plan number.
*
* @param number number
* @return {@link SimulationStorage}
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationPreScript.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationPreScript.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationPreScript.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -64,7 +64,7 @@
SimulationStorage simulation = context.getSimulationStorage();
SimulationParameter parameters = simulation.getParameter();
String presimulationScript = parameters.getPreScript();
- if ((parameters.getUsePreScript() || parameters.getUseAnalysePlan())
+ if ((parameters.getUsePreScript() || parameters.getUseSimulationPlan())
&& presimulationScript != null
&& !"".equals(presimulationScript)) {
@@ -78,7 +78,6 @@
bsh.eval("import org.nuiton.topia.persistence.*;");
bsh.eval("import fr.ifremer.isisfish.*;");
bsh.eval("import fr.ifremer.isisfish.types.*;");
- bsh.eval("import fr.ifremer.isisfish.types.Date;");
bsh.eval("import fr.ifremer.isisfish.entities.*;");
bsh.eval("import java.util.*;");
bsh.eval(presimulationScript);
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulatorServerBadIdException.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulatorServerBadIdException.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulatorServerBadIdException.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -31,7 +31,6 @@
* Created: Fri Sep 6 2002
*
* @author <poussin at codelutin.com>
- * Copyright Code Lutin
* @version $Revision$
*
* Mise a jour: $Date$
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 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SSHSimulatorLauncher.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -56,14 +56,13 @@
import fr.ifremer.isisfish.IsisFish;
import fr.ifremer.isisfish.datastore.SimulationStorage;
import fr.ifremer.isisfish.simulator.SimulationControl;
-import fr.ifremer.isisfish.util.ClasspathTemplateLoader;
import fr.ifremer.isisfish.util.ssh.InvalidPassphraseException;
import fr.ifremer.isisfish.util.ssh.ProgressMonitor;
import fr.ifremer.isisfish.util.ssh.SSHAgent;
import fr.ifremer.isisfish.util.ssh.SSHException;
import fr.ifremer.isisfish.util.ssh.SSHUserInfo;
import fr.ifremer.isisfish.util.ssh.SSHUtils;
-import freemarker.cache.TemplateLoader;
+import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
@@ -149,7 +148,7 @@
freemarkerConfiguration.setDefaultEncoding("utf-8");
// specific template loader to get template from jars (classpath)
- TemplateLoader templateLoader = new ClasspathTemplateLoader();
+ ClassTemplateLoader templateLoader = new ClassTemplateLoader(SSHSimulatorLauncher.class, "/");
freemarkerConfiguration.setTemplateLoader(templateLoader);
}
@@ -1090,7 +1089,8 @@
* @throws IOException if can't get script content
*/
protected String getSimulationScriptLaunchContent(String templateName,
- String simuationId, String simulationZip, boolean standaloneZip, String simulationZipResult, String preScriptPath, boolean multipleSimulationScript)
+ String simuationId, String simulationZip, boolean standaloneZip,
+ String simulationZipResult, String preScriptPath, boolean multipleSimulationScript)
throws IOException {
String scriptContent = null;
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationJob.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationJob.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationJob.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2002 - 2010 Ifremer, Code Lutin, Benjamin Poussin
+ * Copyright (C) 2002 - 2011 Ifremer, Code Lutin, Benjamin Poussin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -62,7 +62,7 @@
/** Le {@link SimulationService} dans lequel a ete cree ce job */
protected SimulationService simulationService;
/** si non null contient le {@link SimulationJob} qui a genere ce job, ca
- * veut dire que ce job est du a un plan d'analyse*/
+ * veut dire que ce job est du a un plan de simulation*/
protected SimulationJob parentJob;
/** item contenant les infos de la simulation */
protected SimulationItem item;
@@ -190,7 +190,7 @@
/**
* Fait la simulation. La simulation en elle meme est delegue au
* {@link SimulatorLauncher}. Le travail restant ici est le nettoyage,
- * la gestion des erreurs ou l'iteration s'il sagit de plan d'analyse
+ * la gestion des erreurs ou l'iteration s'il sagit de plan de simulation
* dependant.
*/
public void run() {
@@ -211,8 +211,8 @@
simulationService.fireStartEvent(this);
if (!onlyCheckControl && getParentJob() == null
- && param.getUseAnalysePlan() && !param.isIndependentPlan()) {
- // on est sur un plan d'analyse dependant, il faut generer les
+ && param.getUseSimulationPlan() && !param.isIndependentPlan()) {
+ // on est sur un plan de simulation dependant, il faut generer les
// simulation les unes apres les autres
SimulationService.PrepareSimulationJob i = new SimulationService.PrepareSimulationJob(
simulationService, this);
@@ -320,7 +320,7 @@
if (param.getOnlyExport()) {
// pour les plan dependant il faut le faire apres toutes
// les simulations donc pas ici
- if (getParentJob() == null || param.getUseAnalysePlan()
+ if (getParentJob() == null || param.getUseSimulationPlan()
&& param.isIndependentPlan()) {
simulation.delete(false);
}
@@ -350,13 +350,13 @@
}
}
} /*finally {
- simulationService.fireStopEvent(this);
- } */
+ simulationService.fireStopEvent(this);
+ } */
}
/**
* Interface permettant d'implanter des actions a faire apres la simulation.
- * Ces actions ne se declenchent pas pour les job de plan d'analyse pere.
+ * Ces actions ne se declenchent pas pour les job de plan de simulation pere.
*/
public static interface PostAction {
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationMonitor.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationMonitor.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationMonitor.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -619,7 +619,7 @@
}
}
- // sensitivity calculator analyze result call
+ // sensitivity analysis result call
// can't do analyze second pass if simulation
// has been deleted
if (simulationAvailable) {
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 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationService.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2002 - 2010 Ifremer, Code Lutin, Benjamin Poussin
+ * Copyright (C) 2002 - 2011 Ifremer, Code Lutin, Benjamin Poussin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -289,7 +289,7 @@
/**
* Supprime le job de la liste des jobs en cours et l'ajoute le job si
* besoin a la liste des jobs faits (s'il y a une erreur ou qu'il ne sagit
- * pas d'une simulation lancer par un plan d'analyse).
+ * pas d'une simulation lancer par un plan de simulation).
* Les listener sont prevenu par la méthode
* {@link SimulationServiceListener#simulationStop(SimulationService, SimulationJob)}.
* @param job
@@ -374,7 +374,7 @@
SimulatorLauncher launcher, int priority) {
// make deep copy, ui, still work with
- // copy need to be deep for analyze plan to reload
+ // copy need to be deep for simulation plan to reload
SimulationParameter localParameters = param.deepCopy();
// on l'ajoute tout de suite a la liste des simulations demandee
@@ -384,11 +384,11 @@
job.setLauncher(launcher);
fireStartEvent(job);
- // Attention, dans le cas d'un plan d'analyse, le new PrepareSimulationJob
+ // Attention, dans le cas d'un plan de simulation, le new PrepareSimulationJob
// doit etre fait AVANT de faire le prepareSimulationZipFile
// car, il est possible que l'init des plans ajoute des regles !!!
PrepareSimulationJob task = null;
- if (localParameters.getUseAnalysePlan()) {
+ if (localParameters.getUseSimulationPlan()) {
task = new PrepareSimulationJob(this, job);
}
@@ -396,8 +396,8 @@
File zip = prepareSimulationZipFile(control, localParameters, null, true);
item.setSimulationZip(zip);
- if (localParameters.getUseAnalysePlan() && localParameters.isIndependentPlan()) {
- // c un plan d'analyse independant, on construit toute les sous simu
+ if (localParameters.getUseSimulationPlan() && localParameters.isIndependentPlan()) {
+ // c un plan de simulation independant, on construit toute les sous simu
subSimulationComputationExecutor.execute(task);
} else {
// l'item est fini d'etre initialise, on peut l'ajouter a la queue
@@ -423,7 +423,7 @@
SensitivityAnalysis sensitivityAnalysis, DesignPlan designPlan) {
// make deep copy, ui, still work with
- // copy need to be deep for analyse plan to reload
+ // copy need to be deep for simulation plan to reload
SimulationParameter localParameters = param.deepCopy();
try {
@@ -501,9 +501,9 @@
job.setLauncher(launcher);
fireStartEvent(job);
- if (subParam.getUseAnalysePlan()
+ if (subParam.getUseSimulationPlan()
&& subParam.isIndependentPlan()) {
- // c un plan d'analyse independant, on construit toute les sous simu
+ // c un plan de simulation independant, on construit toute les sous simu
Runnable task = new PrepareSimulationJob(this, job);
subSimulationComputationExecutor.execute(task);
} else {
@@ -795,7 +795,7 @@
}
/**
- * Permet de genere les sous simulations d'un plan d'analyse. Pour les
+ * Permet de genere les sous simulations d'un plan de simulation. Pour les
* plan independant, on l'utilise en Runnable pour genere tous les plans
* possible et les soumettre a la queue. Pour les plans dependant
* on l'utilise seulement comme iterator. La methode afterSimulation des plans
@@ -941,7 +941,7 @@
result = false;
} else {
String simId = id + "_" + planNumber;
- param.setAnalysePlanNumber(planNumber);
+ param.setSimulationPlanNumber(planNumber);
File tmpDirectory = FileUtil.createTempDirectory(
"isisfish-simulation-", "-preparation");
@@ -949,7 +949,7 @@
.importAndRenameZip(tmpDirectory, job
.getItem().getSimulationZip(),
simId);
- sim.getParameter().setAnalysePlanNumber(planNumber);
+ sim.getParameter().setSimulationPlanNumber(planNumber);
// appel de tous les plans pour modifier la simulation
for (SimulationPlan plan : param.getSimulationPlans()) {
@@ -1063,7 +1063,7 @@
* <li> exports
* <li> simulators
* <li> export de la database de la region
- * <li> analyseplan
+ * <li> simultionplan
* <p>
* Le tout est zippé et le zip est retourné, il peut-être directement
* importé dans le {@link SimulationStorage} (en le renommant comme
@@ -1076,7 +1076,7 @@
* @param xmlDesignPlan contenu xml des design plan
* @param compile si vrai la version compile des fichiers Java est aussi
* mise dans le fichier zip. Cela peut servir pour les simulations locales
- * pour ne pas recompiler pour chaque simulation avec plan d'analyse
+ * pour ne pas recompiler pour chaque simulation avec plan de simulation
* @return un zip de simulation pour une simulation pret a être faite
* @throws SimulationException pour tout problème rencontré (IO,Topia...)
*/
@@ -1124,7 +1124,7 @@
+ File.separator + name + ".java"));
}
- // copie des regles reclamées par les plans d'analyse
+ // copie des regles reclamées par les plans de simulation
for (String name : param.getExtraRules()) {
File ruleFile = new File(RuleStorage.getRuleDirectory(), name + ".java");
if (!ruleFile.isFile()) {
@@ -1248,7 +1248,7 @@
fileToConvert.addAll(tmp);
tmp = FileUtil.find(new File(directory,
- AnalysePlanStorage.ANALYSE_PLAN_PATH), ".*\\.java$", true);
+ SimulationPlanStorage.SIMULATION_PLAN_PATH), ".*\\.java$", true);
fileToConvert.addAll(tmp);
tmp = FileUtil.find(
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceTableModel.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceTableModel.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceTableModel.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -78,7 +78,7 @@
/** Columns types. */
protected Class<?>[] columnClass = new Class[] {
String.class, // id
- String.class, // analyse plan number
+ String.class, // simulation plan number
String.class, // local, remote, batch
String.class, // text
JProgressBar.class // progress
@@ -235,8 +235,8 @@
result = id;
break;
case 1:
- if (param.getUseAnalysePlan()) {
- int number = param.getAnalysePlanNumber();
+ if (param.getUseSimulationPlan()) {
+ int number = param.getSimulationPlanNumber();
if (number >= 0) {
result = number;
}
@@ -244,7 +244,7 @@
break;
case 2:
if (job.getLauncher() == null) {
- if (param.getUseAnalysePlan()) {
+ if (param.getUseSimulationPlan()) {
result = _("isisfish.queue.masterplan");
} else {
result = _("isisfish.queue.notstarted");
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulatorLauncher.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulatorLauncher.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulatorLauncher.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -83,7 +83,7 @@
*
* @return le storage contenant la simulation qui vient d'etre faite
* ou null en fait au lieu de faire une seul simulation, plusieurs ou ete
- * faite par exemple tout un plan d'analyse. Cette classe est tout de meme
+ * faite par exemple tout un plan de simulation Cette classe est tout de meme
* responsable du stockage de chaque simulation dans des storages.
*
* @throws RemoteException Si pour l'execution de la simulation
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/package-info.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/package-info.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/package-info.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 1999 - 2010 Ifremer, CodeLutin
+ * Copyright (C) 1999 - 2011 Ifremer, CodeLutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -61,10 +61,10 @@
* Les simulations sont soumises au {@link fr.ifremer.isisfish.simulator.launcher.SimulationService} via sa methode
* submit. Un objet {@link fr.ifremer.isisfish.simulator.launcher.SimulationJob} est alors cree et ajoute a la liste
* des simulations presentes ({@link fr.ifremer.isisfish.simulator.launcher.SimulationService#getJobs()}). Si la
- * simulation est une simple simulation ou une simulation avec plan d'analyse
+ * simulation est une simple simulation ou une simulation avec plan de simulation
* dependant, elle est alors directement ajoutee a la queue de simulation
* (simulation a faire). Si
- * la simulation utilise un plan d'analyse independant, un thread est
+ * la simulation utilise un plan de simulation independant, un thread est
* specialement utilise pour generer toutes les simulations du plan, celles-ci
* sont alors ajoutee a la queue, mais n'apparaitront dans la liste des
* simulations qu'au moment ou un thread de simulation executera reellement le
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/MatrixType.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/MatrixType.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/MatrixType.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -56,7 +56,6 @@
* Created: 23 janv. 2006
*
* @author Arnaud Thimel <thimel at codelutin.com>
- * Copyright Code Lutin
* @version $Revision$
*
* Mise a jour: $Date$
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/MonthType.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/MonthType.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/MonthType.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -41,7 +41,6 @@
* Created: 19 janv. 2006
*
* @author Arnaud Thimel <thimel at codelutin.com>
- * Copyright Code Lutin
* @version $Revision$
*
* Mise a jour: $Date$
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/RangeOfValuesType.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/RangeOfValuesType.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/RangeOfValuesType.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -41,7 +41,6 @@
* Created: 19 janv. 2006
*
* @author Arnaud Thimel <thimel at codelutin.com>
- * Copyright Code Lutin
* @version $Revision$
*
* Mise a jour: $Date$
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/TimeStepType.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/TimeStepType.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/TimeStepType.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -41,7 +41,6 @@
* Created: 19 janv. 2006
*
* @author Arnaud Thimel <thimel at codelutin.com>
- * Copyright Code Lutin
* @version $Revision$
*
* Mise a jour: $Date$
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/TimeUnitType.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/TimeUnitType.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/TimeUnitType.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -41,7 +41,6 @@
* Created: 19 janv. 2006
*
* @author Arnaud Thimel <thimel at codelutin.com>
- * Copyright Code Lutin
* @version $Revision$
*
* Mise a jour: $Date$
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/CommonHandler.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/CommonHandler.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/CommonHandler.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2011 Codelutin, Chatellier Eric
+ * Copyright (C) 2011 Ifremer, Codelutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/SimulationUI.jaxx
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/SimulationUI.jaxx 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/SimulationUI.jaxx 2011-07-15 13:12:45 UTC (rev 3445)
@@ -64,9 +64,9 @@
public abstract void setEnabledPrescriptTab(boolean selected);
/**
- * Change analyse plan tab enabled property.
+ * Change simulation plan tab enabled property.
*/
- public abstract void setEnabledAnalysePlanTab(boolean selected);
+ public abstract void setEnabledSimulationPlanTab(boolean selected);
/**
* Open user dialog to selected a parameter file.
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/WelcomeHandler.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/WelcomeHandler.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/WelcomeHandler.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2011 Codelutin, Chatellier Eric
+ * Copyright (C) 2011 Ifremer, Codelutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/InputHandler.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/InputHandler.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/InputHandler.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -3,7 +3,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2011 Codelutin, Chatellier Eric
+ * Copyright (C) 2011 Ifremer, Codelutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckRegion.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckRegion.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckRegion.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -67,7 +67,6 @@
* Created: 9 janv. 2004
*
* @author Benjamin Poussin <poussin at codelutin.com>
- * Copyright Code Lutin
* @version $Revision$
*
* Mise a jour: $Date$
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckResult.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckResult.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckResult.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -39,7 +39,6 @@
* Created: 9 janv. 2004
*
* @author Benjamin Poussin <poussin at codelutin.com>
- * Copyright Code Lutin
* @version $Revision$
*
* Mise a jour: $Date$
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckResultFrame.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckResultFrame.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckResultFrame.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -38,7 +38,6 @@
* Created: 10 janv. 2004
*
* @author Benjamin Poussin <poussin at codelutin.com>
- * Copyright Code Lutin
* @version $Revision$
*
* Mise a jour: $Date$
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckResultTableModel.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckResultTableModel.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckResultTableModel.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -48,7 +48,6 @@
* Created: 10 janv. 2004
*
* @author Benjamin Poussin <poussin at codelutin.com>
- * Copyright Code Lutin
* @version $Revision$
*
* Mise a jour: $Date$
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckResultTableRenderer.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckResultTableRenderer.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/check/CheckResultTableRenderer.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -36,7 +36,6 @@
* Created: 10 janv. 2004
*
* @author Benjamin Poussin <poussin at codelutin.com>
- * Copyright Code Lutin
* @version $Revision$
*
* Mise a jour: $Date$
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/tree/FisheryTreeRenderer.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/tree/FisheryTreeRenderer.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/tree/FisheryTreeRenderer.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -3,7 +3,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2011 Codelutin, Chatellier Eric
+ * Copyright (C) 2011 Ifremer, Codelutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/tree/FisheryTreeSelectionModel.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/tree/FisheryTreeSelectionModel.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/input/tree/FisheryTreeSelectionModel.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -1,9 +1,10 @@
/*
* #%L
+ *
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2011 Codelutin, Chatellier Eric
+ * Copyright (C) 2011 Ifremer, Codelutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/export/ExportListRenderer.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/export/ExportListRenderer.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/export/ExportListRenderer.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -35,7 +35,7 @@
import fr.ifremer.isisfish.export.Export;
/**
- * Renderer pour la liste des plans d'analyse.
+ * Renderer pour la liste des export.
*
* @author chatellier
* @version $Revision$
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/package-info.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/package-info.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/package-info.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 1999 - 2011 CodeLutin
+ * Copyright (C) 1999 - 2011 Ifremer, CodeLutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/rule/RuleComboModel.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/rule/RuleComboModel.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/rule/RuleComboModel.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -43,7 +43,7 @@
/** serialVersionUID. */
private static final long serialVersionUID = -4070846632975105788L;
- /** Analyze plan names. */
+ /** Rule names. */
protected List<String> rulesNames;
/**
@@ -66,7 +66,7 @@
/**
* Get rule names.
*
- * @return the analyze plan names
+ * @return the rule names
*/
public List<String> getExportNames() {
return rulesNames;
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/rule/RuleParametersFactorTableCellEditor.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/rule/RuleParametersFactorTableCellEditor.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/rule/RuleParametersFactorTableCellEditor.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -28,10 +28,8 @@
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
-import java.util.EventObject;
import javax.swing.AbstractCellEditor;
-import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTable;
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/rule/RuleParametersFactorTableCellRenderer.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/rule/RuleParametersFactorTableCellRenderer.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/rule/RuleParametersFactorTableCellRenderer.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -28,7 +28,6 @@
import java.awt.Component;
import javax.swing.JButton;
-import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/sensitivityexport/SensitivityExportListRenderer.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/sensitivityexport/SensitivityExportListRenderer.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/sensitivityexport/SensitivityExportListRenderer.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -35,7 +35,7 @@
import fr.ifremer.isisfish.export.SensitivityExport;
/**
- * Renderer pour la liste des plans d'analyse.
+ * Renderer pour la liste des export d'AS.
*
* @author chatellier
* @version $Revision$
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/simulationplan/SimulationPlanComboModel.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/simulationplan/SimulationPlanComboModel.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/simulationplan/SimulationPlanComboModel.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -30,7 +30,7 @@
import javax.swing.DefaultComboBoxModel;
/**
- * Model pour la liste des plans d'analyse.
+ * Model pour la liste des plans de simulation.
*
* @author chatellier
* @version $Revision$
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/simulationplan/SimulationPlanComboRenderer.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/simulationplan/SimulationPlanComboRenderer.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/simulationplan/SimulationPlanComboRenderer.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -40,7 +40,7 @@
import fr.ifremer.isisfish.ui.util.TooltipHelper;
/**
- * Renderer pour la combo des plans d'analyse.
+ * Renderer pour la combo des plans de simulation.
*
* @author chatellier
* @version $Revision$
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/simulationplan/SimulationPlanListModel.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/simulationplan/SimulationPlanListModel.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/simulationplan/SimulationPlanListModel.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -32,7 +32,7 @@
import fr.ifremer.isisfish.simulator.SimulationPlan;
/**
- * Model pour la liste des instances de plans d'analyse.
+ * Model pour la liste des instances de plans de simulation.
*
* @author chatellier
* @version $Revision$
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/simulationplan/SimulationPlanListRenderer.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/simulationplan/SimulationPlanListRenderer.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/models/simulationplan/SimulationPlanListRenderer.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -35,7 +35,7 @@
import fr.ifremer.isisfish.simulator.SimulationPlan;
/**
- * Renderer pour la liste des plans d'analyse.
+ * Renderer pour la liste des plans de simulation.
*
* @author chatellier
* @version $Revision$
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/MatrixMapRenderer.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/MatrixMapRenderer.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/MatrixMapRenderer.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -3,7 +3,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2011 Codelutin, Chatellier Eric
+ * Copyright (C) 2011 Ifremer, Codelutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/MatrixSummaryRenderer.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/MatrixSummaryRenderer.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/MatrixSummaryRenderer.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -3,7 +3,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2011 Codelutin, Chatellier Eric
+ * Copyright (C) 2011 Ifremer, Codelutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/ResultHandler.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/ResultHandler.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/ResultHandler.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -3,7 +3,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2011 Codelutin, Chatellier Eric
+ * Copyright (C) 2011 Ifremer, Codelutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -61,7 +61,6 @@
import fr.ifremer.isisfish.simulator.launcher.SimulationServiceListener;
import fr.ifremer.isisfish.ui.CommonHandler;
import fr.ifremer.isisfish.ui.models.common.StringComboModel;
-import fr.ifremer.isisfish.ui.models.common.StringListModel;
/**
* Handler for result UIs.
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/YearSumDimensionAction.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/YearSumDimensionAction.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/YearSumDimensionAction.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -3,7 +3,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2011 Codelutin, Chatellier Eric
+ * Copyright (C) 2011 Ifremer, Codelutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/script/ScriptAction.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/script/ScriptAction.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/script/ScriptAction.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -65,15 +65,15 @@
import fr.ifremer.isisfish.IsisFish;
import fr.ifremer.isisfish.IsisFishRuntimeException;
-import fr.ifremer.isisfish.datastore.SimulationPlanStorage;
import fr.ifremer.isisfish.datastore.CodeSourceStorage;
import fr.ifremer.isisfish.datastore.ExportStorage;
import fr.ifremer.isisfish.datastore.FormuleStorage;
import fr.ifremer.isisfish.datastore.JavaSourceStorage;
import fr.ifremer.isisfish.datastore.RuleStorage;
import fr.ifremer.isisfish.datastore.ScriptStorage;
-import fr.ifremer.isisfish.datastore.SensitivityExportStorage;
import fr.ifremer.isisfish.datastore.SensitivityAnalysisStorage;
+import fr.ifremer.isisfish.datastore.SensitivityExportStorage;
+import fr.ifremer.isisfish.datastore.SimulationPlanStorage;
import fr.ifremer.isisfish.datastore.SimulatorStorage;
import fr.ifremer.isisfish.equation.Language;
import fr.ifremer.isisfish.ui.WelcomePanelUI;
@@ -81,11 +81,10 @@
import fr.ifremer.isisfish.ui.script.model.ScriptTreeModel;
import fr.ifremer.isisfish.ui.util.ErrorHelper;
import fr.ifremer.isisfish.ui.vcs.UpdateDialogUI;
-import fr.ifremer.isisfish.util.ClasspathTemplateLoader;
import fr.ifremer.isisfish.util.CompileHelper;
import fr.ifremer.isisfish.util.JavadocHelper;
import fr.ifremer.isisfish.vcs.VCSException;
-import freemarker.cache.TemplateLoader;
+import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
@@ -136,7 +135,7 @@
// fix encoding issue on some systems
freemarkerConfiguration.setDefaultEncoding("utf-8");
// specific template loader to get template from jars (classpath)
- TemplateLoader templateLoader = new ClasspathTemplateLoader();
+ ClassTemplateLoader templateLoader = new ClassTemplateLoader(ScriptAction.class, "/");
freemarkerConfiguration.setTemplateLoader(templateLoader);
}
@@ -1088,9 +1087,6 @@
/** enum to encapsulate a script module */
protected enum ScriptMapping {
- SimulationPlan(
- SimulationPlanStorage.getSimulationPlanDirectory(),
- SimulationPlanStorage.SIMULATION_PLAN_TEMPLATE, true),
Export(
ExportStorage.getExportDirectory(),
ExportStorage.EXPORT_TEMPLATE, true),
@@ -1106,16 +1102,16 @@
SensitivityExport(
SensitivityExportStorage.getSensitivityExportDirectory(),
SensitivityExportStorage.SENSITIVITY_EXPORT_TEMPLATE, true),
+ SimulationPlan(
+ SimulationPlanStorage.getSimulationPlanDirectory(),
+ SimulationPlanStorage.SIMULATION_PLAN_TEMPLATE, true),
Simulator(
SimulatorStorage.getSimulatorDirectory(),
SimulatorStorage.SIMULATOR_TEMPLATE, true),
Formule(
FormuleStorage.getFormuleDirectory(),
FormuleStorage.FORMULE_TEMPLATE, true),
-
- CommunityAnalysePlan(
- SimulationPlanStorage.getCommunitySimulationPlanDirectory(),
- SimulationPlanStorage.SIMULATION_PLAN_TEMPLATE),
+
CommunityExport(
ExportStorage.getCommunityExportDirectory(),
ExportStorage.EXPORT_TEMPLATE),
@@ -1131,6 +1127,9 @@
CommunitySensitivityExport(
SensitivityExportStorage.getCommunitySensitivityExportDirectory(),
SensitivityExportStorage.SENSITIVITY_EXPORT_TEMPLATE),
+ CommunityAnalysePlan(
+ SimulationPlanStorage.getCommunitySimulationPlanDirectory(),
+ SimulationPlanStorage.SIMULATION_PLAN_TEMPLATE),
CommunitySimulator(
SimulatorStorage.getCommunitySimulatorDirectory(),
SimulatorStorage.SIMULATOR_TEMPLATE),
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/script/ScriptUI.jaxx
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/script/ScriptUI.jaxx 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/script/ScriptUI.jaxx 2011-07-15 13:12:45 UTC (rev 3445)
@@ -53,7 +53,7 @@
onActionPerformed='getScriptAction().newScript(ScriptAction.ScriptMapping.Export)' icon="script.png" />
<JMenuItem id="miNewRule" text="isisfish.script.menu.txtNewRule"
onActionPerformed='getScriptAction().newScript(ScriptAction.ScriptMapping.Rule)' icon="script.png" />
- <JMenuItem id="miNewAnalysePlan" text="isisfish.script.menu.txtNewAnalysePlan"
+ <JMenuItem id="miNewSImulationPlan" text="isisfish.script.menu.txtNewSimulationPlan"
onActionPerformed='getScriptAction().newScript(ScriptAction.ScriptMapping.SimulationPlan)' icon="script.png" />
<JMenuItem id="miNewSensitivity" text="isisfish.script.menu.txtNewSensitivity"
onActionPerformed='getScriptAction().newScript(ScriptAction.ScriptMapping.Sensitivity)' icon="script.png" />
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/script/package-info.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/script/package-info.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/script/package-info.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2005 - 2010 CodeLutin
+ * Copyright (C) 2005 - 2010 Ifremer, CodeLutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity/SensitivitySaveVerifier.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity/SensitivitySaveVerifier.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity/SensitivitySaveVerifier.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -3,7 +3,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2011 Codelutin, Chatellier Eric
+ * Copyright (C) 2011 Ifremer, Codelutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity/SensitivityUI.jaxx
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity/SensitivityUI.jaxx 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity/SensitivityUI.jaxx 2011-07-15 13:12:45 UTC (rev 3445)
@@ -61,8 +61,8 @@
}
@Override
- public void setEnabledAnalysePlanTab(boolean selected) {
- // no analyse plan in AS
+ public void setEnabledSimulationPlanTab(boolean selected) {
+ // no simulation plan in AS
}
@Override
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity/equation/EquationDomainRenderer.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity/equation/EquationDomainRenderer.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/sensitivity/equation/EquationDomainRenderer.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -3,7 +3,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2011 Codelutin, Chatellier Eric
+ * Copyright (C) 2011 Ifremer, Codelutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
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 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/ParamsUI.jaxx 2011-07-15 13:12:45 UTC (rev 3445)
@@ -143,9 +143,9 @@
getParentContainer(SimulUI.class).getPreScriptUI().getFieldSimulPreScript().setText(preScript);
}
}
-protected void setAnalysePlan() {
+protected void setSimulationPlan() {
if (!isSensitivity()){
- fieldSimulUseAnalysePlan.setSelected(simulAction.getSimulationParameter().getUseAnalysePlan());
+ fieldSimulUseSimulationPlan.setSelected(simulAction.getSimulationParameter().getUseSimulationPlan());
getParentContainer(SimulUI.class).getSensUI().refresh();
}
}
@@ -200,7 +200,7 @@
// mise a jour des années
fieldSimulParamsNbAnnees.setText(String.valueOf(simulAction.getNumberOfYear()));
setPreScript();
- setAnalysePlan();
+ setSimulationPlan();
setExportSens();
setSensitivityAnalysis();
setFactor();
@@ -242,10 +242,10 @@
SimulationUI simulationUI = getParentContainer(SimulationUI.class);
simulationUI.setEnabledPrescriptTab(fieldUseSimulPreScripts.isSelected());
}
-protected void enableAnalysePlan() {
- simulAction.getSimulationParameter().setUseAnalysePlan(fieldSimulUseAnalysePlan.isSelected());
+protected void enableSimulationPlan() {
+ simulAction.getSimulationParameter().setUseSimulationPlan(fieldSimulUseSimulationPlan.isSelected());
SimulationUI simulationUI = getParentContainer(SimulationUI.class);
- simulationUI.setEnabledAnalysePlanTab(fieldSimulUseAnalysePlan.isSelected());
+ simulationUI.setEnabledSimulationPlanTab(fieldSimulUseSimulationPlan.isSelected());
}
protected void setListSimulParamsStrategiesItems() {
@@ -525,11 +525,11 @@
onItemStateChanged='enablePreScript()' />
</cell>
<cell fill="horizontal" weightx="0.3">
- <JCheckBox text="isisfish.params.useAnalysePlan"
- id="fieldSimulUseAnalysePlan"
- selected='{simulAction.getSimulationParameter().getUseAnalysePlan()}'
+ <JCheckBox text="isisfish.params.useSimulationPlan"
+ id="fieldSimulUseSimulationPlan"
+ selected='{simulAction.getSimulationParameter().getUseSimulationPlan()}'
visible='{!isSensitivity()}'
- onItemStateChanged='enableAnalysePlan()'
+ onItemStateChanged='enableSimulationPlan()'
enabled="{getRegionStorage() != null}" />
</cell>
</row>
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 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/SimulAction.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -88,7 +88,6 @@
import fr.ifremer.isisfish.simulator.sensitivity.Factor;
import fr.ifremer.isisfish.simulator.sensitivity.FactorGroup;
import fr.ifremer.isisfish.simulator.sensitivity.SensitivityAnalysis;
-import fr.ifremer.isisfish.simulator.sensitivity.SensitivityCalculator;
import fr.ifremer.isisfish.simulator.sensitivity.SensitivityException;
import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
import fr.ifremer.isisfish.simulator.sensitivity.domain.DiscreteDomain;
@@ -262,7 +261,7 @@
* Reset some field to empty default values:
* <ul>
* <li>params</li>
- * <li>analyse plans</li>
+ * <li>simulation plans</li>
* <li>factors list</li>
* <ul>
*
@@ -283,7 +282,7 @@
simulStorage = SimulationStorage.getSimulation(simulName);
param = simulStorage.getParameter().copy();
// all time reset number after load
- param.setAnalysePlanNumber(-1);
+ param.setSimulationPlanNumber(-1);
regionStorage = param.getRegion();
// Chargement des facteurs
@@ -637,11 +636,8 @@
SimulationPlan sp = SimulationPlanStorage.getSimulationPlan(name)
.getNewSimulationPlanInstance();
getSimulationParameter().addSimulationPlan(sp);
- } catch (IsisFishException e) {
- if (log.isErrorEnabled()) {
- log.error("Can't add analyse plan", e);
- }
- ErrorHelper.showErrorDialog(_("isisfish.error.simulation.addanalyseplan"), e);
+ } catch (IsisFishException ex) {
+ throw new IsisFishRuntimeException("Can't add simulation plan", ex);
}
}
@@ -666,11 +662,8 @@
if (sp != null) {
try {
result = SimulationPlanStorage.getParameterValue(sp, paramName);
- } catch (IsisFishException e) {
- if (log.isErrorEnabled()) {
- log.error("Can't get analyse plan param value", e);
- }
- ErrorHelper.showErrorDialog(_("isisfish.error.simulation.getparametervalue"), e);
+ } catch (IsisFishException ex) {
+ throw new IsisFishRuntimeException("Can't get simulation plan param value", ex);
}
}
return result;
@@ -679,16 +672,13 @@
public void setSimulationPlanParameterValue(String paramName, SimulationPlan sp,
Object value) {
if (log.isDebugEnabled()) {
- log.debug("paramName : " + paramName + " analysePlanName : " + sp
+ log.debug("paramName : " + paramName + " simulationPlanName : " + sp
+ " value : " + value);
}
try {
SimulationPlanStorage.setParameterValue(sp, paramName, value);
- } catch (IsisFishException e) {
- if (log.isErrorEnabled()) {
- log.error("Can't set analyse plan param value", e);
- }
- ErrorHelper.showErrorDialog(_("isisfish.error.simulation.setparametervalue"), e);
+ } catch (IsisFishException ex) {
+ throw new IsisFishRuntimeException("Can't set simulation plan param value", ex);
}
}
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/SimulUI.jaxx
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/SimulUI.jaxx 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/SimulUI.jaxx 2011-07-15 13:12:45 UTC (rev 3445)
@@ -57,7 +57,7 @@
}
@Override
- public void setEnabledAnalysePlanTab(boolean selected) {
+ public void setEnabledSimulationPlanTab(boolean selected) {
bodyTabbedPane.setEnabledAt(2, selected);
if (selected) {
bodyTabbedPane.setSelectedIndex(2);
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/filter/SimulationFilterPanelUI.jaxx
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/filter/SimulationFilterPanelUI.jaxx 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/simulator/filter/SimulationFilterPanelUI.jaxx 2011-07-15 13:12:45 UTC (rev 3445)
@@ -48,9 +48,9 @@
extractTextFieldParam(SimulationMeta.description.name());
extractTextFieldParam(SimulationMeta.numberOfYear.name());
- extractTextFieldParam(SimulationMeta.analysePlanNumber.name());
+ extractTextFieldParam(SimulationMeta.simulationPlanNumber.name());
- extractCheckBoxParam(SimulationMeta.useAnalysePlan.name());
+ extractCheckBoxParam(SimulationMeta.useSimulationPlan.name());
extractCheckBoxParam(SimulationMeta.useOptimization.name());
extractCheckBoxParam(SimulationMeta.usePreScript.name());
extractCheckBoxParam(SimulationMeta.useStatistic.name());
@@ -126,10 +126,10 @@
toolTipText='isisfish.filter.simulation.tooltip.numberOfYear'/>
<JTextField id="numberOfYear" columns='5'
onKeyReleased="doCheck()" />
- <JLabel labelFor='{analysePlanNumber}'
- text='isisfish.filter.simulation.analysePlanNumber'
- toolTipText='isisfish.filter.simulation.tooltip.analysePlanNumber'/>
- <JTextField id="analysePlanNumber" columns='5'
+ <JLabel labelFor='{simulationPlanNumber}'
+ text='isisfish.filter.simulation.simulationPlanNumber'
+ toolTipText='isisfish.filter.simulation.tooltip.simulationPlanNumber'/>
+ <JTextField id="simulationPlanNumber" columns='5'
onKeyReleased="doCheck()" />
</HBox>
</cell>
@@ -137,9 +137,9 @@
<row>
<cell columns="2" anchor='west' weightx="1" fill='horizontal'>
<HBox>
- <JCheckBox id="useAnalysePlan"
- text='isisfish.filter.simulation.useAnalysePlan'
- toolTipText='isisfish.filter.simulation.tooltip.useAnalysePlan'
+ <JCheckBox id="useSimulationPlan"
+ text='isisfish.filter.simulation.useSimulationPlan'
+ toolTipText='isisfish.filter.simulation.tooltip.useSimulationPlan'
onActionPerformed="doCheck()" />
<JCheckBox id="useOptimization"
text='isisfish.filter.simulation.useOptimization'
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/widget/editor/EquationTableEditor.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/widget/editor/EquationTableEditor.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/widget/editor/EquationTableEditor.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -52,7 +52,6 @@
* Created: 23 mars 2004
*
* @author Benjamin Poussin <poussin at codelutin.com>
- * Copyright Code Lutin
* @version $Revision$
*
* Mise a jour: $Date$
Deleted: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/ClasspathTemplateLoader.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/ClasspathTemplateLoader.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/ClasspathTemplateLoader.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -1,92 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2008 - 2010 Ifremer, Code Lutin, Chatellier Eric
- * %%
- * 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-/* *##%
- * Copyright (C) 2008, 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.util;
-
-import java.net.URL;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.util.Resource;
-import org.nuiton.util.ResourceNotFoundException;
-
-import freemarker.cache.URLTemplateLoader;
-
-/**
- * Freemarker custom template loader.
- * Load template from classpath jars.
- *
- * @author chatellier
- * @version $Revision: 1.0 $
- *
- * Last update : $Date: 1 déc. 2008 $
- * By : $Author: chatellier $
- */
-public class ClasspathTemplateLoader extends URLTemplateLoader {
-
- /** log */
- private static Log log = LogFactory.getLog(ClasspathTemplateLoader.class);
-
- /*
- * @see freemarker.cache.URLTemplateLoader#getURL(java.lang.String)
- */
- @Override
- protected URL getURL(String name) {
-
- if (log.isDebugEnabled()) {
- log.debug("Loading url template " + name);
- }
-
- URL url = null;
-
- try {
- url = Resource.getURL(name);
- } catch (ResourceNotFoundException e) {
- // not big deal
- // freemarker ask for name_fr_FR, name_fr, name
- url = null;
- }
-
- return url;
- }
-
-}
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/ssh/ProgressMonitor.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/ssh/ProgressMonitor.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/ssh/ProgressMonitor.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin, Chatellier Eric
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -22,23 +22,6 @@
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
-/* *##%
- * Copyright (C) 2009 Code Lutin, Chatellier Eric
- *
- * 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.util.ssh;
Modified: isis-fish/trunk/src/main/resources/i18n/isis-fish_en_GB.properties
===================================================================
--- isis-fish/trunk/src/main/resources/i18n/isis-fish_en_GB.properties 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/resources/i18n/isis-fish_en_GB.properties 2011-07-15 13:12:45 UTC (rev 3445)
@@ -44,7 +44,6 @@
Show\ help=
Show\ version=
SimulationExecutor\ started\ with\ %s\ thread\ for\ %s=
-Skip\ data\ migration\ (disabled)=
Ssh\ key\ found\ '%s'\ will\ be\ used\ to\ connect\ to=
Stop\ simulation\ plan,\ because\ can't\ call\ afterSimulation\ correctly\ on\ plan\ %s=
SubProcess\ start\:\ %s\ %s=
@@ -61,7 +60,6 @@
could\ not\ read\ at\ offset\ %1$s\ for\ reason\ %2$s=could not read at offset %1$s for reason %2$s
destination\ already\ exists\ %s\ use\ 'force'\ argument\ to\ force\ overwrite=
destination\ already\ exists\ %s\ use\ \\'force\\'\ argument\ to\ force\ overwrite=
-directory\ %s\ must\ be\ a\ directory=
filter\ loaded\ in\ %1$s\ ms\ \:\ found\ %2$s\ lines.=filter loaded in %1$s ms \: found %2$s lines.
isisfish.about.abouthtmltext=<html><b>Isis-Fish (%s)</b><br /><br />Copyright IFREMER-MAERHA 2000-2011.<br /><br /><a href\="http\://isis-fish.labs.libre-entreprise.org">http\://isis-fish.labs.libre-entreprise.org</a><br /><br />Please, report any bug you can found.<html>
isisfish.about.licensetext=You can modify and redistribute the program under the conditions of the GNU General Public License (version 2 or later). A copy of the GPL is in the file "LICENSE.txt" provided with Isis-Fish. All rights reserved. No guarantees are provided for use of this program.
@@ -141,8 +139,6 @@
isisfish.config.category.misc.description=Miscealenous
isisfish.config.category.officialvcs=Official VCS
isisfish.config.category.officialvcs.description=Official VCS repository
-isisfish.config.category.versioning=
-isisfish.config.category.versioning.description=
isisfish.config.database.lockmode.description=Database lock mode
isisfish.config.main.compileDirectory.description=Script compilation directory
isisfish.config.main.configFileName.description=Configuration filename
@@ -202,12 +198,9 @@
isisfish.config.vcs.hostName.description=Official VCS host name
isisfish.config.vcs.localCommunityDatabasePath.description=Community VCS local storage directory
isisfish.config.vcs.localDatabasePath.description=Official VCS local storage directory
-isisfish.config.vcs.noPassPhrase.description=
-isisfish.config.vcs.passphrase.description=
isisfish.config.vcs.protocol.description=Official VCS protocol
isisfish.config.vcs.remotePath.description=Official VCS remote path
isisfish.config.vcs.type.description=Official VCS type
-isisfish.config.vcs.useSshConnexion.description=
isisfish.config.vcs.userName.description=Official VCS user name
isisfish.config.vcs.userPassword.description=Official VCS password
isisfish.date.toString=%1$s %2$s
@@ -267,7 +260,6 @@
isisfish.error.evaluate.equation=Can't evaluate equation\: %1$s
isisfish.error.evaluate.preplan.script=
isisfish.error.evalute.plan.script=Can't evaluate plan script
-isisfish.error.factor.invalid=
isisfish.error.file.already.exists=The file %1$s already exist
isisfish.error.growth.equation.before.create.group.population=Error, You must input growth equation before create the group population
isisfish.error.immigration.negative=immigration negative
@@ -310,21 +302,16 @@
isisfish.error.no.sector=No sector defined
isisfish.error.no.select.simulation=Could not select simulation
isisfish.error.no.target.species=No target species in %1$s for %2$s
-isisfish.error.not.found.code=Could not found codeclass for %1$s
isisfish.error.not.found.description=Could not found description for %1$s
isisfish.error.not.found.field=Could not found field %1$s doc for %2$s
-isisfish.error.not.found.field.class=Could not found field %1$s for class %2$s
-isisfish.error.not.null.class.grown=Null value for grown class
isisfish.error.not.null.mean.weight=Null mean weight
isisfish.error.not.possible.metier=No metier available
-isisfish.error.not.support.class=this class does not support
isisfish.error.null.semantics=Null semantics for %s
isisfish.error.number.classes.upper.zero=Error, the number of classes must be upper than 0
isisfish.error.out.memory=Out of memory try with more memory (option -mx)
isisfish.error.overlap.season=Cette saison chevauche une autre saison
isisfish.error.parse.date=Can't parse date %1$s
isisfish.error.parse.long=Can't parse long %1$s
-isisfish.error.plan.parameter=Can't get plan parameter from compiled class
isisfish.error.prepare.data=Can't prepare data
isisfish.error.prepare.information.simulation=Can't prepare information for simulation
isisfish.error.read.simulation=Can't read simulation information %1$s
@@ -341,14 +328,11 @@
isisfish.error.rename.region=Can't rename region to %1$s
isisfish.error.save.checkSum.compilation=Can't save checkSum to compilation\: %1$s
isisfish.error.save.script.compilation=Can't save script to compilation\: %1$s
-isisfish.error.save.simulation.parameters=Can't save simulation parameters in file %1$s
isisfish.error.script.create=isisfish.error.script.create
isisfish.error.script.delete=Can't delete file %1$s for reason %2$s
isisfish.error.script.import=Can't import file for reason %1$s
isisfish.error.script.load=Can't load file %1$s for reason %2$s
isisfish.error.script.save=Can't save file %1$s for reason %2$s
-isisfish.error.simulation.addanalyseplan=Can't add analyze plan
-isisfish.error.simulation.getparametervalue=Can't get parameter value
isisfish.error.simulation.getresultname=Can't get result names list
isisfish.error.simulation.importparameter=Can't import simulation parameters
isisfish.error.simulation.initsimulaction=Can't init simulation
@@ -363,7 +347,6 @@
isisfish.error.simulation.resultXml.open=Can't open simulation result XML for reason %1$s
isisfish.error.simulation.resultXml.write=Can't write simulation result XML for reason %1$s
isisfish.error.simulation.savesimulation=Can't save simulation parameters
-isisfish.error.simulation.setparametervalue=Can't set parameter value
isisfish.error.source.parameter=Can't get parameter from source
isisfish.error.strategy.order=Strategy %1$s don't have 12 StrategyMonthInfo but %2$s. Recreate them
isisfish.error.undefined.classes=No classes defined
@@ -405,31 +388,31 @@
isisfish.filter.select=Select
isisfish.filter.select.simulation=Select a simulation
isisfish.filter.simulation=Filter simulations
-isisfish.filter.simulation.analysePlanNumber=Analyse plan number
isisfish.filter.simulation.description=Description
isisfish.filter.simulation.local=Local
isisfish.filter.simulation.numberOfYear=Number of year
isisfish.filter.simulation.regionName=Region name
isisfish.filter.simulation.simulationEnd=Simulation end date (dd/MM/yyyy)
isisfish.filter.simulation.simulationName=Simulation name
+isisfish.filter.simulation.simulationPlanNumber=Simulation plan number
isisfish.filter.simulation.simulationStart=Simulation start date (dd/MM/yyyy)
isisfish.filter.simulation.simulatorName=Simulator name
-isisfish.filter.simulation.tooltip.analysePlanNumber=Filter on analyse number
isisfish.filter.simulation.tooltip.description=Filter on description (regex)
isisfish.filter.simulation.tooltip.local=Filter only local simulations
isisfish.filter.simulation.tooltip.numberOfYear=Filter on number of year (exact sequence)
isisfish.filter.simulation.tooltip.regionName=Filter on region name (regex)
isisfish.filter.simulation.tooltip.simulationEnd=Filter on region end date (format dd/MM/yyyy)
isisfish.filter.simulation.tooltip.simulationName=Filter on simulation name
+isisfish.filter.simulation.tooltip.simulationPlanNumber=Filter on simulation number
isisfish.filter.simulation.tooltip.simulationStart=Filter on simulation start date (format dd/MM/yyyy)
isisfish.filter.simulation.tooltip.simulatorName=Filter on simulator name
-isisfish.filter.simulation.tooltip.useAnalysePlan=Filter on simulations with analyse plan
isisfish.filter.simulation.tooltip.useOptimization=Filter on simulations with optimization
isisfish.filter.simulation.tooltip.usePreScript=Filter on simulations with pre-script
+isisfish.filter.simulation.tooltip.useSimulationPlan=
isisfish.filter.simulation.tooltip.useStatistic=Filter on simulations with statistic
-isisfish.filter.simulation.useAnalysePlan=analyse plan
isisfish.filter.simulation.useOptimization=optimization
isisfish.filter.simulation.usePreScript=pre-script
+isisfish.filter.simulation.useSimulationPlan=Simulation plan
isisfish.filter.simulation.useStatistic=statistic
isisfish.fisheryRegion.addMap=Add map
isisfish.fisheryRegion.area=Fishery area boundaries
@@ -616,7 +599,6 @@
isisfish.metierSeasonInfoZone.title=Seasons / Zones
isisfish.misc.databasemigration.question=Database version is \: %s.\n\nA migration to version %s is needed.\nDo you want to migrate database ?
isisfish.misc.databasemigration.title=Database migration
-isisfish.misc.nuitonmigration=IsisFish has detected some code based on CodeLutin libraries in following user scripts.\nDo you want to migrate those script on new nuiton libraries ?
isisfish.month.april=april
isisfish.month.august=august
isisfish.month.december=december
@@ -649,7 +631,7 @@
isisfish.params.toString.lib.logger.level=Level of libraries' logger \: %1$s
isisfish.params.toString.number.years=Number of years\: %1$s\n\n
isisfish.params.toString.plan=Plan\: %1$s
-isisfish.params.toString.plan.number=Analyse plan sequence number\: %1$s\n\n
+isisfish.params.toString.plan.number=Simulation plan sequence number\: %1$s\n\n
isisfish.params.toString.populations=Populations \:
isisfish.params.toString.rule=Rule\: %1$s
isisfish.params.toString.script.logger.level=Level of scripts' logger \: %1$s
@@ -657,8 +639,8 @@
isisfish.params.toString.simul.logger.level=Level of simulator's logger \: %1$s
isisfish.params.toString.simulation.done=Simulation done with \: %1$s
isisfish.params.toString.strategies=Strategies \:
-isisfish.params.useAnalysePlan=Use simulation plan
isisfish.params.usePreSimulationScript=Use pre simulation script
+isisfish.params.useSimulationPlan=Use simulation plan
isisfish.population.capturability=Capturability
isisfish.population.comments=Comments
isisfish.population.group=Group
@@ -674,7 +656,6 @@
isisfish.populationBasics.geographicID=Geographic identifier
isisfish.populationBasics.growth=Growth
isisfish.populationBasics.growthReverse=Reverse growth
-isisfish.populationBasics.maturityGroup=Maturity group
isisfish.populationBasics.name=Name
isisfish.populationBasics.numberGroup=Number of group
isisfish.populationBasics.plusGroup=Plus group
@@ -828,13 +809,13 @@
isisfish.script.menu.save=Save
isisfish.script.menu.txtExport=Export
isisfish.script.menu.txtImport=Import
-isisfish.script.menu.txtNewAnalysePlan=New analyse plan
isisfish.script.menu.txtNewEquationModel=New equation model
isisfish.script.menu.txtNewExport=New export
isisfish.script.menu.txtNewRule=New rule
isisfish.script.menu.txtNewScript=New script
isisfish.script.menu.txtNewSensitivity=New sensitivity calculator
isisfish.script.menu.txtNewSensitivityExport=New sensitivity export
+isisfish.script.menu.txtNewSimulationPlan=New simulation plan
isisfish.script.menu.txtNewSimulator=New simulator
isisfish.script.menu.txtVCS=Server
isisfish.script.menu.update=Update from server
Modified: isis-fish/trunk/src/main/resources/i18n/isis-fish_fr_FR.properties
===================================================================
--- isis-fish/trunk/src/main/resources/i18n/isis-fish_fr_FR.properties 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/resources/i18n/isis-fish_fr_FR.properties 2011-07-15 13:12:45 UTC (rev 3445)
@@ -44,7 +44,6 @@
Show\ help=
Show\ version=
SimulationExecutor\ started\ with\ %s\ thread\ for\ %s=
-Skip\ data\ migration\ (disabled)=
Ssh\ key\ found\ '%s'\ will\ be\ used\ to\ connect\ to=
Stop\ simulation\ plan,\ because\ can't\ call\ afterSimulation\ correctly\ on\ plan\ %s=
SubProcess\ start\:\ %s\ %s=
@@ -61,7 +60,6 @@
could\ not\ read\ at\ offset\ %1$s\ for\ reason\ %2$s=could not read at offset %1$s for reason %2$s
destination\ already\ exists\ %s\ use\ 'force'\ argument\ to\ force\ overwrite=
destination\ already\ exists\ %s\ use\ \\'force\\'\ argument\ to\ force\ overwrite=
-directory\ %s\ must\ be\ a\ directory=
filter\ loaded\ in\ %1$s\ ms\ \:\ found\ %2$s\ lines.=filter loaded in %1$s ms \: found %2$s lines.
isisfish.about.abouthtmltext=<html><b>Isis-Fish (%s)</b><br /><br />Copyright IFREMER-MAERHA 2000-2011.<br /><br /><a href\="http\://isis-fish.labs.libre-entreprise.org">http\://isis-fish.labs.libre-entreprise.org</a><br /><br />Merci de rapporter les bugs.<html>
isisfish.about.licensetext=Vous pouvez modifier et redistribuer ce programme sous les conditions énoncées par la licence GNU GPL (version 2 ou ultérieure). Une copie de la licence GPL est dans le fichier « LICENSE.txt » fourni avec Isis-Fish. Tous droits réservés. Aucune garantie n'est fournie pour l'utilisation de ce programme.
@@ -141,8 +139,6 @@
isisfish.config.category.misc.description=Divers
isisfish.config.category.officialvcs=VCS Officiel
isisfish.config.category.officialvcs.description=Dépôt contenant les scripts officiels
-isisfish.config.category.versioning=
-isisfish.config.category.versioning.description=
isisfish.config.database.lockmode.description=Méthode de vérouillage à utiliser pour la base de données
isisfish.config.main.compileDirectory.description=le répertoire où sont compilés les scripts
isisfish.config.main.configFileName.description=le fichier de configuration à utiliser
@@ -172,7 +168,7 @@
isisfish.config.main.simulation.ssh.javapath=Emplacement de java
isisfish.config.main.simulation.ssh.javapath.description=Emplacement de java sur le serveur (chemin total, ou relatif au $PATH, par défaut la valeur est celle de caparmor)
isisfish.config.main.simulation.ssh.max.threads=Nombre de thread SSH
-isisfish.config.main.simulation.ssh.max.threads.description=Nombre de simulation simultanée à faire en SSH. Attention, ne doit être utilisé que pour faire plusieurs plans d'analyse dépendants en même temps, sinon laisser '1'.
+isisfish.config.main.simulation.ssh.max.threads.description=Nombre de simulation simultanée à faire en SSH. Attention, ne doit être utilisé que pour faire plusieurs plans de simulation dépendants en même temps, sinon laisser '1'.
isisfish.config.main.simulation.ssh.pbsbinpath=Emplacement des executables PBS
isisfish.config.main.simulation.ssh.pbsbinpath.description=Emplacement des commandes PBS (qsub, qdel...) sur le serveur
isisfish.config.main.simulation.ssh.pbsqsuboptions=Arguments qsub
@@ -202,12 +198,9 @@
isisfish.config.vcs.hostName.description=le nom du serveur vcs à utiliser
isisfish.config.vcs.localCommunityDatabasePath.description=Dossier de stockage local du dépôt communauté
isisfish.config.vcs.localDatabasePath.description=Dossier de stockage local du dépôt officiel
-isisfish.config.vcs.noPassPhrase.description=
-isisfish.config.vcs.passphrase.description=
isisfish.config.vcs.protocol.description=le protocol pour acceder au serveur vcs
isisfish.config.vcs.remotePath.description=le chemin jusqu'au parent du module de données sur le serveur vcs
isisfish.config.vcs.type.description=le type de communication vcs utilisé
-isisfish.config.vcs.useSshConnexion.description=
isisfish.config.vcs.userName.description=le login de l'utilisateur sur le serveur vcs
isisfish.config.vcs.userPassword.description=le mot de passe de l'utilsateur sur le serveur vcs
isisfish.date.toString=%1$s %2$s
@@ -267,7 +260,6 @@
isisfish.error.evaluate.equation=Impossible d'évaluer l'équation\: %1$s
isisfish.error.evaluate.preplan.script=
isisfish.error.evalute.plan.script=Can't evaluate plan script
-isisfish.error.factor.invalid=
isisfish.error.file.already.exists=The file %1$s already exist
isisfish.error.growth.equation.before.create.group.population=Error, You must input growth equation before create the group population
isisfish.error.immigration.negative=immigration negative
@@ -310,21 +302,16 @@
isisfish.error.no.sector=il n'y a pas de secteur de définit
isisfish.error.no.select.simulation=could not select simulation
isisfish.error.no.target.species=no target species in %1$s for %2$s
-isisfish.error.not.found.code=could not found codeclass for %1$s
isisfish.error.not.found.description=could not found description for %1$s
isisfish.error.not.found.field=could not found field %1$s doc for %2$s
-isisfish.error.not.found.field.class=could not found field %1$s for class %2$s
-isisfish.error.not.null.class.grown=classe mature vaut nul
isisfish.error.not.null.mean.weight=poids moyen nul
isisfish.error.not.possible.metier=Pas de métier possible
-isisfish.error.not.support.class=La classe %s ne supporte pas les descritions
isisfish.error.null.semantics=Semantiques nulle pour %s
isisfish.error.number.classes.upper.zero=Error, the number of classes must be upper than 0
isisfish.error.out.memory=Out of memory try with more memory (option -mx)
isisfish.error.overlap.season=Cette saison chevauche une autre saison
isisfish.error.parse.date=Can't parse date %1$s
isisfish.error.parse.long=Can't parse long %1$s
-isisfish.error.plan.parameter=Can't get plan parameter from compiled class
isisfish.error.prepare.data=Can't prepare data
isisfish.error.prepare.information.simulation=Can't prepare information for simulation
isisfish.error.read.simulation=Can't read simulation information %1$s
@@ -341,14 +328,11 @@
isisfish.error.rename.region=Can't rename region to %1$s
isisfish.error.save.checkSum.compilation=Can't save checkSum to compilation\: %1$s
isisfish.error.save.script.compilation=Can't save script to compilation\: %1$s
-isisfish.error.save.simulation.parameters=Can't save simulation parameters in file %1$s
isisfish.error.script.create=isisfish.error.script.create
isisfish.error.script.delete=N'a pas pu supprimer le fichier %1$s pour la raison suivante %2$s
isisfish.error.script.import=N'a pas pu importer pour la raison suivante %1$s
isisfish.error.script.load=N'a pas pu charger le fichier %1$s pour la raison suivante %2$s
isisfish.error.script.save=N'a pas pu sauver le fichier %1$s pour la raison suivante %2$s
-isisfish.error.simulation.addanalyseplan=Impossible d'ajouter un plan d'analyze
-isisfish.error.simulation.getparametervalue=Impossible d'obtenir la valeur du paramètre
isisfish.error.simulation.getresultname=Impossible d'obtenir la liste des résultat
isisfish.error.simulation.importparameter=Impossible d'importer les paramètres de simulation
isisfish.error.simulation.initsimulaction=Impossible d'initialiser la simulation
@@ -363,7 +347,6 @@
isisfish.error.simulation.resultXml.open=Can't open simulation result XML for reason %1$s
isisfish.error.simulation.resultXml.write=Can't write simulation result XML for reason %1$s
isisfish.error.simulation.savesimulation=Impossible de sauver les paramètres de simulation
-isisfish.error.simulation.setparametervalue=Impossible d'affecter la valeur du paramètre
isisfish.error.source.parameter=Can't get parameter from source
isisfish.error.strategy.order=Strategy %1$s don't have 12 StrategyMonthInfo but %2$s. Recreate them
isisfish.error.undefined.classes=pas de classes définies
@@ -405,31 +388,31 @@
isisfish.filter.select=Sélectionner
isisfish.filter.select.simulation=Sélectionner une simulation
isisfish.filter.simulation=Filtrer les simulations
-isisfish.filter.simulation.analysePlanNumber=numéro d'analyse
isisfish.filter.simulation.description=description
isisfish.filter.simulation.local=locale
isisfish.filter.simulation.numberOfYear=nombre d'année(s)
isisfish.filter.simulation.regionName=nom de région
isisfish.filter.simulation.simulationEnd=date de fin (dd/MM/yyyy)
isisfish.filter.simulation.simulationName=nom de simulation
+isisfish.filter.simulation.simulationPlanNumber=Numéro de simulation
isisfish.filter.simulation.simulationStart=date de début (dd/MM/yyyy)
isisfish.filter.simulation.simulatorName=nom du simulateur
-isisfish.filter.simulation.tooltip.analysePlanNumber=filter sur le numéro d'analyse (uniquement pour les simulations avec plan d'analyse)
isisfish.filter.simulation.tooltip.description=filtrer sur la description (format regex)
isisfish.filter.simulation.tooltip.local=filter uniquement les simulations locales
isisfish.filter.simulation.tooltip.numberOfYear=filter sur le nombre d'année(s) (recherche exacte)
isisfish.filter.simulation.tooltip.regionName=filtrer sur le nom de la région (format regex)
isisfish.filter.simulation.tooltip.simulationEnd=filtrer sur la date de fin de simulation (format dd/MM/yyyy)
isisfish.filter.simulation.tooltip.simulationName=filtrer sur le nom de simulation (format regex)
+isisfish.filter.simulation.tooltip.simulationPlanNumber=Filtrer si le numéro de simulation (dans un plan)
isisfish.filter.simulation.tooltip.simulationStart=filtrer sur la date de début de simulation (format dd/MM/yyyy)
isisfish.filter.simulation.tooltip.simulatorName=filter sur le nom du simulateur utilisé (format regex)
-isisfish.filter.simulation.tooltip.useAnalysePlan=filter uniquement les simulations avec plan d'analyse
isisfish.filter.simulation.tooltip.useOptimization=filter uniquement les simulations avec optimisation
isisfish.filter.simulation.tooltip.usePreScript=filter uniquement les simulations avec Prescript
+isisfish.filter.simulation.tooltip.useSimulationPlan=filtrer sur les simulations utilisant un plan de simulation
isisfish.filter.simulation.tooltip.useStatistic=filter uniquement les simulations avec statistiques
-isisfish.filter.simulation.useAnalysePlan=plan d'analyse
isisfish.filter.simulation.useOptimization=optimisation
isisfish.filter.simulation.usePreScript=prescript
+isisfish.filter.simulation.useSimulationPlan=plan de simulation
isisfish.filter.simulation.useStatistic=statistiques
isisfish.fisheryRegion.addMap=Ajouter une carte
isisfish.fisheryRegion.area=Extrémités de la zone de pêche
@@ -616,7 +599,6 @@
isisfish.metierSeasonInfoZone.title=Saison / Zones
isisfish.misc.databasemigration.question=La base de donnée est en version \: %s.\n\nUne migration en version %s est nécessaire.\nVoulez vous migrer la base de données ?
isisfish.misc.databasemigration.title=Migration de base de données
-isisfish.misc.nuitonmigration=IsisFish a détecté l'utilisation de librairies CodeLutin dans les scripts suivants.\nVoulez vous migrer ces scripts vers les nouvelles librairies nuiton ?
isisfish.month.april=avril
isisfish.month.august=août
isisfish.month.december=décembre
@@ -657,8 +639,8 @@
isisfish.params.toString.simul.logger.level=niveau du logger de simulateur \: %1$s
isisfish.params.toString.simulation.done=Simulation réalisée avec \: %1$s
isisfish.params.toString.strategies=Stratégies d'exploitation \:
-isisfish.params.useAnalysePlan=Utiliser le plan de simulation
isisfish.params.usePreSimulationScript=Utiliser un script de pré-simulation
+isisfish.params.useSimulationPlan=Utiliser un plan de simulation
isisfish.population.capturability=Capturabilité
isisfish.population.comments=Commentaires
isisfish.population.group=Groupe
@@ -674,7 +656,6 @@
isisfish.populationBasics.geographicID=Identifiant géographique
isisfish.populationBasics.growth=Croissance
isisfish.populationBasics.growthReverse=Croissance inverse
-isisfish.populationBasics.maturityGroup=Groupe de maturité
isisfish.populationBasics.name=Nom
isisfish.populationBasics.numberGroup=Nombre de groupes
isisfish.populationBasics.plusGroup=Groupe plus
@@ -828,13 +809,13 @@
isisfish.script.menu.save=Sauver
isisfish.script.menu.txtExport=Exporter
isisfish.script.menu.txtImport=Importer
-isisfish.script.menu.txtNewAnalysePlan=Nouveau plan d'analyse
isisfish.script.menu.txtNewEquationModel=Nouvelle formule
isisfish.script.menu.txtNewExport=Nouveau script d'export
isisfish.script.menu.txtNewRule=Nouvelle règle
isisfish.script.menu.txtNewScript=Nouveau script
isisfish.script.menu.txtNewSensitivity=Nouveau calculateur de sensibilité
isisfish.script.menu.txtNewSensitivityExport=Nouvel export de sensibilité
+isisfish.script.menu.txtNewSimulationPlan=Nouveau plan de simulation
isisfish.script.menu.txtNewSimulator=Nouveau simulateur
isisfish.script.menu.txtVCS=Serveur
isisfish.script.menu.update=Synchronisation
Modified: isis-fish/trunk/src/main/resources/log4j.properties
===================================================================
--- isis-fish/trunk/src/main/resources/log4j.properties 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/main/resources/log4j.properties 2011-07-15 13:12:45 UTC (rev 3445)
@@ -24,6 +24,7 @@
###
# Global logging configuration
log4j.rootLogger=ERROR, stdout
+
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
@@ -33,11 +34,11 @@
log4j.logger.fr.ifremer.isisfish=INFO
log4j.logger.org.nuiton.j2r=DEBUG
log4j.logger.org.nuiton=WARN
-log4j.logger.analyseplans=INFO
log4j.logger.exports=INFO
log4j.logger.formules=INFO
log4j.logger.rules=INFO
log4j.logger.scripts=INFO
-log4j.logger.sensitivity=INFO
+log4j.logger.sensitivityanalysis=INFO
log4j.logger.sensitivityexports=INFO
+log4j.logger.simulationplans=INFO
log4j.logger.simulators=INFO
Modified: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/AbstractIsisFishTest.java
===================================================================
--- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/AbstractIsisFishTest.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/AbstractIsisFishTest.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -34,8 +34,7 @@
import org.junit.BeforeClass;
import fr.ifremer.isisfish.datastore.AutoMigrationIsisH2Config;
-import fr.ifremer.isisfish.util.ClasspathTemplateLoader;
-import freemarker.cache.TemplateLoader;
+import freemarker.cache.ClassTemplateLoader;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
@@ -148,7 +147,7 @@
freemarkerConfiguration.setDefaultEncoding("utf-8");
// specific template loader to get template from jars (classpath)
- TemplateLoader templateLoader = new ClasspathTemplateLoader();
+ ClassTemplateLoader templateLoader = new ClassTemplateLoader(AbstractIsisFishTest.class, "/");
freemarkerConfiguration.setTemplateLoader(templateLoader);
freemarkerConfiguration.setObjectWrapper(new BeansWrapper());
Modified: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/SimulationParameterTest.java
===================================================================
--- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/SimulationParameterTest.java 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/SimulationParameterTest.java 2011-07-15 13:12:45 UTC (rev 3445)
@@ -77,8 +77,8 @@
Assert.assertTrue(params.getExportNames().isEmpty());
Assert.assertFalse(params.getUsePreScript());
Assert.assertEquals("", params.getPreScript());
- Assert.assertFalse(params.getUseAnalysePlan());
- Assert.assertEquals(-1, params.getAnalysePlanNumber());
+ Assert.assertFalse(params.getUseSimulationPlan());
+ Assert.assertEquals(-1, params.getSimulationPlanNumber());
Assert.assertTrue(params.getSensitivityExport().isEmpty());
Assert.assertEquals(-1, params.getNumberOfSensitivitySimulation());
Assert.assertNull(params.getSensitivityAnalysis());
@@ -201,13 +201,13 @@
SimulationParameterImpl param2 = new SimulationParameterImpl();
param2.fromProperties(props2);
- // test analyse plans
+ // test simulation plans
Assert.assertNull(param.simulationPlans);
Assert.assertTrue(param2.propertiesParameters.containsKey("plans"));
// ca rend zero parce que l'instanciation doit echouer
Assert.assertEquals(0, param2.getSimulationPlans().size());
}
-
+
/**
* Test toString() method.
*
Modified: isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/parameters_basic.properties
===================================================================
--- isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/parameters_basic.properties 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/parameters_basic.properties 2011-07-15 13:12:45 UTC (rev 3445)
@@ -39,7 +39,7 @@
useOptimization=true
useStatistic=false
exportDirectory=/home/chatellier/isis-export
-useAnalysePlan=false
+useSimulationPlan=false
isisFishVersion=3.2.0.6
rule.1.parameter.endMonth=10
rule.1.parameter.endDate=118
@@ -47,12 +47,12 @@
rule.1.parameter.beginDate=1
populations=Anchois_long
description=Done for unit testing
-analysePlan=
+simulationPlan=
rule.1.parameter.beginMonth=1
population.Anchois_long.number=[[10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 2000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0]]
plans=
simulatorName=DefaultSimulator.java
strategies=Espagnols,BolBretons,PelProfil1
-analysePlanNumber=-1
+simulationPlanNumber=-1
exports=EffortsMetier.java,
resultNames=matrixGrossValueOfLandingsPerStrategyMet,
Modified: isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/parameters_plan.properties
===================================================================
--- isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/parameters_plan.properties 2011-07-11 11:22:25 UTC (rev 3444)
+++ isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/parameters_plan.properties 2011-07-15 13:12:45 UTC (rev 3445)
@@ -39,7 +39,7 @@
useOptimization=true
useStatistic=false
exportDirectory=/home/chatellier/isis-export
-useAnalysePlan=true
+useSimulationPlan=true
isisFishVersion=3.2.0.6
rule.1.parameter.endMonth=11
rule.1.parameter.endDate=119
@@ -47,12 +47,12 @@
rule.1.parameter.beginDate=0
populations=Anchois_long
description=Done for unit testing (plan)
-analysePlan=TestCapturabiliteUnavailable
+simulationPlan=TestCapturabiliteUnavailable
rule.1.parameter.beginMonth=0
population.Anchois_long.number=[[10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 2000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0]]
plans=TestCapturabiliteUnavailable
simulatorName=DefaultSimulator.java
strategies=Espagnols,BolBretons,PelProfil1
-analysePlanNumber=-1
+simulationPlanNumber=-1
exports=EffortsMetier.java,
resultNames=matrixGrossValueOfLandingsPerStrategyMet,
1
0
Author: chatellier
Date: 2011-07-11 11:22:25 +0000 (Mon, 11 Jul 2011)
New Revision: 3444
Log:
Update todo
Modified:
isis-fish/trunk/TODO.txt
Modified: isis-fish/trunk/TODO.txt
===================================================================
--- isis-fish/trunk/TODO.txt 2011-07-11 10:01:13 UTC (rev 3443)
+++ isis-fish/trunk/TODO.txt 2011-07-11 11:22:25 UTC (rev 3444)
@@ -1,11 +1,8 @@
TODO au 18/09/2009
==================
- - refaire les UI des résultats
- tester que les paramêtres d'une simulation sont corrects
(ex:année < 0)
- - Pouvoir modifier les facteurs apres avoir recharger une simulation
- valeur par defaut dans les champs de saisie
- JavaWebStart
- - Synchronisation des script utilisateur (ecriture)
- Voir une version antérieure d'un script
\ No newline at end of file
1
0
r3443 - in isis-fish/trunk/src/main: java/fr/ifremer/isisfish/util xmi
by chatellier@users.labs.libre-entreprise.org 11 Jul '11
by chatellier@users.labs.libre-entreprise.org 11 Jul '11
11 Jul '11
Author: chatellier
Date: 2011-07-11 10:01:13 +0000 (Mon, 11 Jul 2011)
New Revision: 3443
Log:
Fix simulation executions
Modified:
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/EvaluatorHelper.java
isis-fish/trunk/src/main/xmi/isis-fish.properties
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/EvaluatorHelper.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/EvaluatorHelper.java 2011-07-08 14:23:25 UTC (rev 3442)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/EvaluatorHelper.java 2011-07-11 10:01:13 UTC (rev 3443)
@@ -222,10 +222,7 @@
}
content += "import fr.ifremer.isisfish.entities.*;";
content += "import org.nuiton.math.matrix.*;";
- content += "import fr.ifremer.isisfish.types.Date;";
- content += "import fr.ifremer.isisfish.types.Month;";
- content += "import fr.ifremer.isisfish.types.RangeOfValues;";
- content += "import fr.ifremer.isisfish.types.TimeUnit;";
+ content += "import fr.ifremer.isisfish.types.*;";
content += "import org.apache.commons.logging.Log;";
content += "import org.apache.commons.logging.LogFactory;";
content += "import java.util.*;";
Modified: isis-fish/trunk/src/main/xmi/isis-fish.properties
===================================================================
--- isis-fish/trunk/src/main/xmi/isis-fish.properties 2011-07-08 14:23:25 UTC (rev 3442)
+++ isis-fish/trunk/src/main/xmi/isis-fish.properties 2011-07-11 10:01:13 UTC (rev 3443)
@@ -25,7 +25,7 @@
model.tagvalue.copyright=/* Copyright (C) 1999 - 2011 Ifremer - Code Lutin */
model.tagvalue.org.nuiton.math.matrix.MatrixND=fr.ifremer.isisfish.types.hibernate.MatrixType(name,dim,dimNames,semantics,data)
model.tagvalue.fr.ifremer.isisfish.types.Month=fr.ifremer.isisfish.types.hibernate.MonthType
-model.tagvalue.fr.ifremer.isisfish.types.Date=fr.ifremer.isisfish.types.hibernate.DateType
+model.tagvalue.fr.ifremer.isisfish.types.TimeStep=fr.ifremer.isisfish.types.hibernate.TimeStepType
model.tagvalue.fr.ifremer.isisfish.types.TimeUnit=fr.ifremer.isisfish.types.hibernate.TimeUnitType
model.tagvalue.fr.ifremer.isisfish.types.RangeOfValues=fr.ifremer.isisfish.types.hibernate.RangeOfValuesType
model.tagvalue.java.lang.String=text
1
0
r3442 - isis-fish/trunk/src/test/resources/test-database/sensitivityexports
by chatellier@users.labs.libre-entreprise.org 08 Jul '11
by chatellier@users.labs.libre-entreprise.org 08 Jul '11
08 Jul '11
Author: chatellier
Date: 2011-07-08 14:23:25 +0000 (Fri, 08 Jul 2011)
New Revision: 3442
Log:
Fix isis test database
Added:
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightReferenceY7.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightRelativeReferenceY10.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightRelativeY4.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightY1.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassReferenceY8.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassRelativeReferenceY11.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassRelativeY5.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassY2.java
Removed:
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCapturesWeightReferenceY7.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCapturesWeightRelativeReferenceY10.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCapturesWeightRelativeY4.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCapturesWeightY1.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityGenitorBiomassReferenceY8.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityGenitorBiomassRelativeReferenceY11.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityGenitorBiomassRelativeY5.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityGenitorBiomassY2.java
Deleted: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCapturesWeightReferenceY7.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCapturesWeightReferenceY7.java 2011-07-08 14:22:36 UTC (rev 3441)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCapturesWeightReferenceY7.java 2011-07-08 14:23:25 UTC (rev 3442)
@@ -1,122 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-package sensitivityexports;
-
-import static org.nuiton.i18n.I18n._;
-
-import java.io.Writer;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.math.matrix.MatrixND;
-import org.nuiton.topia.TopiaContext;
-
-import scripts.ResultName;
-import fr.ifremer.isisfish.datastore.ResultStorage;
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.entities.Population;
-import fr.ifremer.isisfish.export.SensitivityExport;
-import fr.ifremer.isisfish.types.Date;
-import fr.ifremer.isisfish.util.Doc;
-
-public class SensitivityCapturesWeightReferenceY7 implements SensitivityExport {
-
- /** to use log facility, just put in your code: log.info("..."); */
- static private Log log = LogFactory
- .getLog(SensitivityCapturesWeightReferenceY7.class);
-
- protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP };
-
- @Doc("Population")
- public Population param_pop;
-
- @Doc("Name of the reference simulation")
- public String param_referenceSimulation = "";
-
- @Override
- public void export(SimulationStorage simulation, Writer out)
- throws Exception {
- SimulationStorage referenceSimulation = SimulationStorage
- .getSimulation(param_referenceSimulation);
- ResultStorage referenceResultStorage = referenceSimulation
- .getResultStorage();
- ResultStorage resultStorage = simulation.getResultStorage();
- Date lastDate = resultStorage.getLastDate();
- Double capturesWeight = 0.0;
- Double capturesWeightReference = 0.0;
-
- for (Population pop : simulation.getParameter().getPopulations()) {
- if (pop.getName().equals(param_pop.getName())) {
- for (int i = 0; i < 12; i++) {
-
- //Get the captures Weight of each month of the last year
- MatrixND matlastdate = resultStorage
- .getMatrix(
- new Date(lastDate.getDate() - i),
- pop,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
- capturesWeight += matlastdate.sumAll();
-
- //Get the reference captures Weight of each month of the last year
- TopiaContext tx = referenceSimulation.getStorage()
- .beginTransaction();
- MatrixND matlastdatereference = referenceResultStorage
- .getMatrix(
- new Date(lastDate.getDate() - i),
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP
- + " " + pop, tx);
- capturesWeightReference += matlastdatereference.sumAll();
- tx.commitTransaction();
- tx.closeContext();
-
- }
-
- }
- }
-
- out.write(Double.toString(capturesWeight / capturesWeightReference));
- }
-
- @Override
- public String getDescription() {
- return _("Captures in weight for the last year for the popage population. Captures is the sum of zones, groups, metiers and strategies");
- }
-
- @Override
- public String getExportFilename() {
- return "SensitivityCapturesWeightReferenceY7";
- }
-
- @Override
- public String getExtensionFilename() {
- return ".csv";
- }
-
- @Override
- public String[] getNecessaryResult() {
- return this.necessaryResult;
- }
-
-}
\ No newline at end of file
Deleted: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCapturesWeightRelativeReferenceY10.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCapturesWeightRelativeReferenceY10.java 2011-07-08 14:22:36 UTC (rev 3441)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCapturesWeightRelativeReferenceY10.java 2011-07-08 14:23:25 UTC (rev 3442)
@@ -1,142 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-package sensitivityexports;
-
-import static org.nuiton.i18n.I18n._;
-
-import java.io.Writer;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.math.matrix.MatrixND;
-import org.nuiton.topia.TopiaContext;
-
-import scripts.ResultName;
-import fr.ifremer.isisfish.datastore.ResultStorage;
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.entities.Population;
-import fr.ifremer.isisfish.export.SensitivityExport;
-import fr.ifremer.isisfish.types.Date;
-import fr.ifremer.isisfish.util.Doc;
-
-public class SensitivityCapturesWeightRelativeReferenceY10 implements
- SensitivityExport {
-
- /** to use log facility, just put in your code: log.info("..."); */
- static private Log log = LogFactory
- .getLog(SensitivityCapturesWeightRelativeReferenceY10.class);
-
- protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP };
-
- @Doc("Population")
- public Population param_pop;
-
- @Doc("Name of the reference simulation")
- public String param_referenceSimulation = "";
-
- @Override
- public void export(SimulationStorage simulation, Writer out)
- throws Exception {
- SimulationStorage referenceSimulation = SimulationStorage
- .getSimulation(param_referenceSimulation);
- ResultStorage referenceResultStorage = referenceSimulation
- .getResultStorage();
- ResultStorage resultStorage = simulation.getResultStorage();
- Date lastDate = resultStorage.getLastDate();
- Double capturesWeight = 0.0;
- Double capturesWeightfirst = 0.0;
- Double capturesWeightreference = 0.0;
- Double capturesWeightfirstreference = 0.0;
-
- for (Population pop : simulation.getParameter().getPopulations()) {
- if (pop.getName().equals(param_pop.getName())) {
- for (int i = 0; i < 12; i++) {
-
- //Get the captures Weight of each month of the last year
- MatrixND matlastdate = resultStorage
- .getMatrix(
- new Date(lastDate.getDate() - i),
- pop,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
- capturesWeight += matlastdate.sumAll();
-
- //Get the captures Weight of each month of the first year
- MatrixND matfirstdate = resultStorage
- .getMatrix(
- new Date(i),
- pop,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
- capturesWeightfirst += matfirstdate.sumAll();
-
- //Get the reference captures Weight of each month of the last year
-
- TopiaContext tx = referenceSimulation.getStorage()
- .beginTransaction();
-
- MatrixND matlastdatereference = referenceResultStorage
- .getMatrix(
- new Date(lastDate.getDate() - i),
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP
- + " " + pop, tx);
- capturesWeightreference += matlastdatereference.sumAll();
-
- //Get the reference captures Weight of each month of the first year
- MatrixND matfirstdatereference = referenceResultStorage
- .getMatrix(
- new Date(i),
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP
- + " " + pop, tx);
- capturesWeightfirstreference += matfirstdatereference
- .sumAll();
- tx.commitTransaction();
- tx.closeContext();
- }
- }
- }
- out.write(Double.toString((capturesWeight / capturesWeightfirst)
- / (capturesWeightreference / capturesWeightfirstreference)));
- }
-
- @Override
- public String getDescription() {
- return _("Captures in weight for the last year for the popage population. Captures is the sum of zones, groups, metiers and strategies");
- }
-
- @Override
- public String getExportFilename() {
- return "SensitivityCapturesWeightRelativeReferenceY10";
- }
-
- @Override
- public String getExtensionFilename() {
- return ".csv";
- }
-
- @Override
- public String[] getNecessaryResult() {
- return this.necessaryResult;
- }
-
-}
Deleted: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCapturesWeightRelativeY4.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCapturesWeightRelativeY4.java 2011-07-08 14:22:36 UTC (rev 3441)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCapturesWeightRelativeY4.java 2011-07-08 14:23:25 UTC (rev 3442)
@@ -1,109 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-package sensitivityexports;
-
-import static org.nuiton.i18n.I18n._;
-
-import java.io.Writer;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.math.matrix.MatrixND;
-
-import scripts.ResultName;
-import fr.ifremer.isisfish.datastore.ResultStorage;
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.entities.Population;
-import fr.ifremer.isisfish.export.SensitivityExport;
-import fr.ifremer.isisfish.types.Date;
-import fr.ifremer.isisfish.util.Doc;
-
-public class SensitivityCapturesWeightRelativeY4 implements SensitivityExport {
-
- /** to use log facility, just put in your code: log.info("..."); */
- static private Log log = LogFactory
- .getLog(SensitivityCapturesWeightRelativeY4.class);
-
- protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP };
-
- @Doc("Population")
- public Population param_pop;
-
- @Override
- public void export(SimulationStorage simulation, Writer out)
- throws Exception {
- ResultStorage resultStorage = simulation.getResultStorage();
- Date lastDate = resultStorage.getLastDate();
- Double capturesWeight = 0.0;
- Double capturesWeightfirst = 0.0;
-
- for (Population pop : simulation.getParameter().getPopulations()) {
- if (pop.getName().equals(param_pop.getName())) {
- for (int i = 0; i < 12; i++) {
-
- //Get the captures Weight of each month of the last year
- MatrixND matlastdate = resultStorage
- .getMatrix(
- new Date(lastDate.getDate() - i),
- pop,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
- capturesWeight += matlastdate.sumAll();
-
- //Get the captures Weight of each month of the first year
- MatrixND matfirstdate = resultStorage
- .getMatrix(
- new Date(i),
- pop,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
- capturesWeightfirst += matfirstdate.sumAll();
- }
-
- }
- }
-
- out.write(Double.toString(capturesWeight / capturesWeightfirst));
- }
-
- @Override
- public String getDescription() {
- return _("Captures in weight for the last year for the popage population. Captures is the sum of zones, groups, metiers and strategies");
- }
-
- @Override
- public String getExportFilename() {
- return "SensitivityCapturesWeightRelativeY4";
- }
-
- @Override
- public String getExtensionFilename() {
- return ".csv";
- }
-
- @Override
- public String[] getNecessaryResult() {
- return this.necessaryResult;
- }
-
-}
Deleted: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCapturesWeightY1.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCapturesWeightY1.java 2011-07-08 14:22:36 UTC (rev 3441)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCapturesWeightY1.java 2011-07-08 14:23:25 UTC (rev 3442)
@@ -1,100 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-package sensitivityexports;
-
-import static org.nuiton.i18n.I18n._;
-
-import java.io.Writer;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.math.matrix.MatrixND;
-
-import scripts.ResultName;
-import fr.ifremer.isisfish.datastore.ResultStorage;
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.entities.Population;
-import fr.ifremer.isisfish.export.SensitivityExport;
-import fr.ifremer.isisfish.types.Date;
-import fr.ifremer.isisfish.util.Doc;
-
-public class SensitivityCapturesWeightY1 implements SensitivityExport {
-
- /** to use log facility, just put in your code: log.info("..."); */
- static private Log log = LogFactory
- .getLog(SensitivityCapturesWeightY1.class);
-
- protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP };
-
- @Doc("Population")
- public Population param_pop;
-
- @Override
- public void export(SimulationStorage simulation, Writer out)
- throws Exception {
- ResultStorage resultStorage = simulation.getResultStorage();
- Date lastDate = resultStorage.getLastDate();
- Double capturesWeight = 0.0;
-
- for (Population pop : simulation.getParameter().getPopulations()) {
- if (pop.getName().equals(param_pop.getName())) {
- for (int i = 0; i < 12; i++) {
-
- //Get the captures Weight of each month of the last year
- MatrixND matlastdate = resultStorage
- .getMatrix(
- new Date(lastDate.getDate() - i),
- pop,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
- capturesWeight += matlastdate.sumAll();
- }
-
- }
- }
-
- out.write(Double.toString(capturesWeight));
- }
-
- @Override
- public String getDescription() {
- return _("Captures in weight for the last year for the popage population. Captures is the sum of zones, groups, metiers and strategies");
- }
-
- @Override
- public String getExportFilename() {
- return "SensitivityCapturesWeightY1";
- }
-
- @Override
- public String getExtensionFilename() {
- return ".csv";
- }
-
- @Override
- public String[] getNecessaryResult() {
- return this.necessaryResult;
- }
-
-}
Added: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightReferenceY7.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightReferenceY7.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightReferenceY7.java 2011-07-08 14:23:25 UTC (rev 3442)
@@ -0,0 +1,137 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+package sensitivityexports;
+
+import static org.nuiton.i18n.I18n._;
+
+import java.io.File;
+import java.io.Writer;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.math.matrix.MatrixND;
+
+import org.nuiton.util.ReverseFileReader;
+import scripts.ResultName;
+import fr.ifremer.isisfish.datastore.ResultStorage;
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.entities.Population;
+import fr.ifremer.isisfish.export.SensitivityExport;
+import fr.ifremer.isisfish.types.TimeStep;
+import fr.ifremer.isisfish.util.Doc;
+
+public class SensitivityCatchWeightReferenceY7 implements SensitivityExport {
+
+ /** to use log facility, just put in your code: log.info("..."); */
+ static private Log log = LogFactory
+ .getLog(SensitivityCatchWeightReferenceY7.class);
+
+ protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP };
+
+ @Doc("Population")
+ public Population param_pop;
+
+ @Doc("Path of the CapturesPoids.csv file")
+ public String param_referenceCatchWeightCSV ="";
+
+ @Override
+ public void export(SimulationStorage simulation, Writer out)
+ throws Exception {
+ ResultStorage resultStorage = simulation.getResultStorage();
+ TimeStep lastStep = resultStorage.getLastStep();
+ Double capturesWeight = 0.0;
+ Double capturesWeightReference = 0.0;
+
+ File referenceFile = new File(param_referenceCatchWeightCSV);
+
+ //instantiate a reader that starts reading from the file end.
+ ReverseFileReader reader = new ReverseFileReader(referenceFile);
+
+ //read the last line of the file (should be empty)
+ String line = reader.readLine();
+
+ //read the next line (the last written line)
+ line = reader.readLine();
+
+ Integer lastMonth = 0;
+
+ while (line != null ) {
+
+ String[] items = line.split(";");
+
+ //If we did not initiate the last date (we are on the last line of
+ // the file), we do it now with the value of the date.
+ if (lastMonth == 0) {
+ lastMonth = Integer.parseInt(items[4]);
+ }
+
+ Integer month = Integer.parseInt(items[4]);
+
+ if ((items[0].equals(param_pop.getName())) && (month>lastMonth-12)){
+ capturesWeightReference += Double.parseDouble(items[5]);
+ }
+ line = reader.readLine();
+ }
+
+ for (Population pop : simulation.getParameter().getPopulations()) {
+ if (pop.getName().equals(param_pop.getName())) {
+ for (int i = 0; i < 12; i++) {
+
+ //Get the captures Weight of each month of the last year
+ MatrixND matlastdate = resultStorage.getMatrix(
+ new TimeStep(lastStep.getStep() - i),
+ pop,
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ capturesWeight += matlastdate.sumAll();
+ }
+ }
+ }
+
+ log.info("capturesWeight value : " + capturesWeight);
+ log.info("capturesWeightReference value : " + capturesWeightReference);
+
+ out.write(Double.toString(capturesWeight / capturesWeightReference));
+ }
+
+ @Override
+ public String getDescription() {
+ return _("Captures in weight for the last year for the popage " +
+ "population. Captures is the sum of zones, groups, metiers " +
+ "and strategies");
+ }
+
+ @Override
+ public String getExportFilename() {
+ return "SensitivityCapturesWeightReferenceY7";
+ }
+
+ @Override
+ public String getExtensionFilename() {
+ return ".csv";
+ }
+
+ @Override
+ public String[] getNecessaryResult() {
+ return this.necessaryResult;
+ }
+
+}
Property changes on: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightReferenceY7.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightRelativeReferenceY10.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightRelativeReferenceY10.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightRelativeReferenceY10.java 2011-07-08 14:23:25 UTC (rev 3442)
@@ -0,0 +1,150 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+package sensitivityexports;
+
+import static org.nuiton.i18n.I18n._;
+
+import java.io.File;
+import java.io.Writer;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.math.matrix.MatrixND;
+
+import org.nuiton.util.ReverseFileReader;
+import scripts.ResultName;
+import fr.ifremer.isisfish.datastore.ResultStorage;
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.entities.Population;
+import fr.ifremer.isisfish.export.SensitivityExport;
+import fr.ifremer.isisfish.types.TimeStep;
+import fr.ifremer.isisfish.util.Doc;
+
+public class SensitivityCatchWeightRelativeReferenceY10 implements
+ SensitivityExport {
+
+ /** to use log facility, just put in your code: log.info("..."); */
+ static private Log log = LogFactory
+ .getLog(SensitivityCatchWeightRelativeReferenceY10.class);
+
+ protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP };
+
+ @Doc("Population")
+ public Population param_pop;
+
+ @Doc("Path of the CapturesPoids.csv file")
+ public String param_referenceCatchWeightCSV = "";
+
+ @Override
+ public void export(SimulationStorage simulation, Writer out)
+ throws Exception {
+ ResultStorage resultStorage = simulation.getResultStorage();
+ TimeStep lastStep = resultStorage.getLastStep();
+ Double capturesWeight = 0.0;
+ Double capturesWeightFirst = 0.0;
+ Double capturesWeightReference = 0.0;
+ Double capturesWeightFirstReference = 0.0;
+
+ File referenceFile = new File(param_referenceCatchWeightCSV);
+
+ //instantiate a reader that starts reading from the file end.
+ ReverseFileReader reader = new ReverseFileReader(referenceFile);
+
+ //read the last line of the file (should be empty)
+ String line = reader.readLine();
+
+ //read the next line (the last written line)
+ line = reader.readLine();
+
+
+ Integer lastMonth = 0;
+
+ while (line!=null ){
+
+ String[] items = line.split(";");
+
+ //If we did not initiate the last date (we are on the last line of
+ // the file), we do it now with the value of the date.
+ if (lastMonth == 0) {
+ lastMonth = Integer.parseInt(items[4]);
+ }
+
+ Integer month = Integer.parseInt(items[4]);
+
+ if ((items[0].equals(param_pop.getName())) && (month>lastMonth-12)){
+ capturesWeightReference += Double.parseDouble(items[5]);
+ }
+
+ if ((items[0].equals(param_pop.getName())) && (month<12)){
+ capturesWeightFirstReference += Double.parseDouble(items[5]);
+ }
+ line = reader.readLine();
+ }
+
+ for (Population pop : simulation.getParameter().getPopulations()) {
+ if (pop.getName().equals(param_pop.getName())) {
+ for (int i = 0; i < 12; i++) {
+
+ //Get the captures Weight of each month of the last year
+ MatrixND matlastdate = resultStorage
+ .getMatrix(
+ new TimeStep(lastStep.getStep() - i),
+ pop,
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ capturesWeight += matlastdate.sumAll();
+
+ //Get the captures Weight of each month of the first year
+ MatrixND matfirstdate = resultStorage
+ .getMatrix(
+ new TimeStep(i),
+ pop,
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ capturesWeightFirst += matfirstdate.sumAll();
+
+ }
+ }
+ }
+ out.write(Double.toString((capturesWeight / capturesWeightFirst)
+ / (capturesWeightReference / capturesWeightFirstReference)));
+ }
+
+ @Override
+ public String getDescription() {
+ return _("Captures in weight for the last year for the popage population. Captures is the sum of zones, groups, metiers and strategies");
+ }
+
+ @Override
+ public String getExportFilename() {
+ return "SensitivityCapturesWeightRelativeReferenceY10";
+ }
+
+ @Override
+ public String getExtensionFilename() {
+ return ".csv";
+ }
+
+ @Override
+ public String[] getNecessaryResult() {
+ return this.necessaryResult;
+ }
+
+}
Property changes on: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightRelativeReferenceY10.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightRelativeY4.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightRelativeY4.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightRelativeY4.java 2011-07-08 14:23:25 UTC (rev 3442)
@@ -0,0 +1,106 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+package sensitivityexports;
+
+import static org.nuiton.i18n.I18n._;
+
+import java.io.Writer;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.math.matrix.MatrixND;
+
+import scripts.ResultName;
+import fr.ifremer.isisfish.datastore.ResultStorage;
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.entities.Population;
+import fr.ifremer.isisfish.export.SensitivityExport;
+import fr.ifremer.isisfish.types.TimeStep;
+import fr.ifremer.isisfish.util.Doc;
+
+public class SensitivityCatchWeightRelativeY4 implements SensitivityExport {
+
+ /** to use log facility, just put in your code: log.info("..."); */
+ static private Log log = LogFactory
+ .getLog(SensitivityCatchWeightRelativeY4.class);
+
+ protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP };
+
+ @Doc("Population")
+ public Population param_pop;
+
+ @Override
+ public void export(SimulationStorage simulation, Writer out)
+ throws Exception {
+ ResultStorage resultStorage = simulation.getResultStorage();
+ TimeStep lastStep = resultStorage.getLastStep();
+ Double capturesWeight = 0.0;
+ Double capturesWeightfirst = 0.0;
+
+ for (Population pop : simulation.getParameter().getPopulations()) {
+ if (pop.getName().equals(param_pop.getName())) {
+ for (int i = 0; i < 12; i++) {
+
+ //Get the captures Weight of each month of the last year
+ MatrixND matlastdate = resultStorage
+ .getMatrix(
+ new TimeStep(lastStep.getStep() - i),
+ pop,
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ capturesWeight += matlastdate.sumAll();
+
+ //Get the captures Weight of each month of the first year
+ MatrixND matfirstdate = resultStorage
+ .getMatrix(
+ new TimeStep(i),
+ pop,
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ capturesWeightfirst += matfirstdate.sumAll();
+ }
+
+ }
+ }
+
+ out.write(Double.toString(capturesWeight / capturesWeightfirst));
+ }
+
+ @Override
+ public String getDescription() {
+ return _("Captures in weight for the last year for the popage population. Captures is the sum of zones, groups, metiers and strategies");
+ }
+
+ @Override
+ public String getExportFilename() {
+ return "SensitivityCapturesWeightRelativeY4";
+ }
+
+ @Override
+ public String getExtensionFilename() {
+ return ".csv";
+ }
+
+ @Override
+ public String[] getNecessaryResult() {
+ return this.necessaryResult;
+ }
+
+}
Property changes on: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightRelativeY4.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightY1.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightY1.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightY1.java 2011-07-08 14:23:25 UTC (rev 3442)
@@ -0,0 +1,97 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+package sensitivityexports;
+
+import static org.nuiton.i18n.I18n._;
+
+import java.io.Writer;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.math.matrix.MatrixND;
+
+import scripts.ResultName;
+import fr.ifremer.isisfish.datastore.ResultStorage;
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.entities.Population;
+import fr.ifremer.isisfish.export.SensitivityExport;
+import fr.ifremer.isisfish.types.TimeStep;
+import fr.ifremer.isisfish.util.Doc;
+
+public class SensitivityCatchWeightY1 implements SensitivityExport {
+
+ /** to use log facility, just put in your code: log.info("..."); */
+ static private Log log = LogFactory
+ .getLog(SensitivityCatchWeightY1.class);
+
+ protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP };
+
+ @Doc("Population")
+ public Population param_pop;
+
+ @Override
+ public void export(SimulationStorage simulation, Writer out)
+ throws Exception {
+ ResultStorage resultStorage = simulation.getResultStorage();
+ TimeStep lastStep = resultStorage.getLastStep();
+ Double capturesWeight = 0.0;
+
+ for (Population pop : simulation.getParameter().getPopulations()) {
+ if (pop.getName().equals(param_pop.getName())) {
+ for (int i = 0; i < 12; i++) {
+
+ //Get the captures Weight of each month of the last year
+ MatrixND matlastdate = resultStorage
+ .getMatrix(
+ new TimeStep(lastStep.getStep() - i),
+ pop,
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ capturesWeight += matlastdate.sumAll();
+ }
+
+ }
+ }
+
+ out.write(Double.toString(capturesWeight));
+ }
+
+ @Override
+ public String getDescription() {
+ return _("Captures in weight for the last year for the popage population. Captures is the sum of zones, groups, metiers and strategies");
+ }
+
+ @Override
+ public String getExportFilename() {
+ return "SensitivityCapturesWeightY1";
+ }
+
+ @Override
+ public String getExtensionFilename() {
+ return ".csv";
+ }
+
+ @Override
+ public String[] getNecessaryResult() {
+ return this.necessaryResult;
+ }
+
+}
Property changes on: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityCatchWeightY1.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Deleted: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityGenitorBiomassReferenceY8.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityGenitorBiomassReferenceY8.java 2011-07-08 14:22:36 UTC (rev 3441)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityGenitorBiomassReferenceY8.java 2011-07-08 14:23:25 UTC (rev 3442)
@@ -1,131 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-package sensitivityexports;
-
-import static org.nuiton.i18n.I18n._;
-
-import java.io.Writer;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.math.matrix.MatrixIterator;
-import org.nuiton.math.matrix.MatrixND;
-import org.nuiton.topia.TopiaContext;
-
-import scripts.ResultName;
-import fr.ifremer.isisfish.datastore.ResultStorage;
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.entities.Population;
-import fr.ifremer.isisfish.entities.PopulationGroup;
-import fr.ifremer.isisfish.export.SensitivityExport;
-import fr.ifremer.isisfish.types.Date;
-import fr.ifremer.isisfish.util.Doc;
-
-public class SensitivityGenitorBiomassReferenceY8 implements SensitivityExport {
-
- /** to use log facility, just put in your code: log.info("..."); */
- static private Log log = LogFactory
- .getLog(SensitivityGenitorBiomassReferenceY8.class);
-
- protected String[] necessaryResult = { ResultName.MATRIX_BIOMASS };
-
- @Doc("Population")
- public Population param_pop;
-
- @Doc("Name of the reference simulation")
- public String param_referenceSimulation = "";
-
- @Override
- public void export(SimulationStorage simulation, Writer out)
- throws Exception {
- SimulationStorage referenceSimulation = SimulationStorage
- .getSimulation(param_referenceSimulation);
- ResultStorage referenceResultStorage = referenceSimulation
- .getResultStorage();
- ResultStorage resultStorage = simulation.getResultStorage();
- Date lastDate = resultStorage.getLastDate();
- Double biomass = 0.0;
- Double referenceBiomass = 0.0;
-
- for (Population pop : simulation.getParameter().getPopulations()) {
- if (pop.getName().equals(param_pop.getName())) {
-
- //Get the biomass of the last time step
- MatrixND matlastdate = resultStorage.getMatrix(pop,
- ResultName.MATRIX_BIOMASS);
- for (MatrixIterator i = matlastdate.iterator(); i.hasNext();) {
- i.next();
- Object[] sems = i.getSemanticsCoordinates();
- PopulationGroup group = (PopulationGroup) sems[1];
- Date date = (Date) sems[0];
- if (date.equals(lastDate)) {
- biomass += i.getValue() * group.getReproductionRate();
- }
- }
-
- //Get the reference biomass of the last time step
- TopiaContext tx = referenceSimulation.getStorage()
- .beginTransaction();
- MatrixND matlastdatereference = referenceResultStorage
- .getMatrix(ResultName.MATRIX_BIOMASS + " " + pop, tx);
- for (MatrixIterator i = matlastdatereference.iterator(); i
- .hasNext();) {
- i.next();
- Object[] sems = i.getSemanticsCoordinates();
- PopulationGroup group = (PopulationGroup) sems[1];
- Date date = (Date) sems[0];
- if (date.equals(lastDate)) {
- referenceBiomass += i.getValue()
- * group.getReproductionRate();
- }
- }
- tx.commitTransaction();
- tx.closeContext();
- }
- }
- out.write(Double.toString(biomass / referenceBiomass));
- }
-
- @Override
- public String getDescription() {
- return _("Biomass of the genitors for the last time step. Biomass is the sum on the groups and zones");
- }
-
- @Override
- public String getExportFilename() {
- return "SensitivityGenitorBiomassReferenceY8";
- }
-
- @Override
- public String getExtensionFilename() {
- return ".csv";
- }
-
- @Override
- public String[] getNecessaryResult() {
- return this.necessaryResult;
- }
-
-}
Deleted: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityGenitorBiomassRelativeReferenceY11.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityGenitorBiomassRelativeReferenceY11.java 2011-07-08 14:22:36 UTC (rev 3441)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityGenitorBiomassRelativeReferenceY11.java 2011-07-08 14:23:25 UTC (rev 3442)
@@ -1,166 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-package sensitivityexports;
-
-import static org.nuiton.i18n.I18n._;
-
-import java.io.Writer;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.math.matrix.MatrixIterator;
-import org.nuiton.math.matrix.MatrixND;
-import org.nuiton.topia.TopiaContext;
-
-import scripts.ResultName;
-import fr.ifremer.isisfish.datastore.ResultStorage;
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.entities.Population;
-import fr.ifremer.isisfish.entities.PopulationGroup;
-import fr.ifremer.isisfish.export.SensitivityExport;
-import fr.ifremer.isisfish.types.Date;
-import fr.ifremer.isisfish.util.Doc;
-
-public class SensitivityGenitorBiomassRelativeReferenceY11 implements
- SensitivityExport {
-
- /** to use log facility, just put in your code: log.info("..."); */
- static private Log log = LogFactory
- .getLog(SensitivityGenitorBiomassRelativeReferenceY11.class);
-
- protected String[] necessaryResult = { ResultName.MATRIX_BIOMASS };
-
- @Doc("Population")
- public Population param_pop;
-
- @Doc("Name of the reference simulation")
- public String param_referenceSimulation = "";
-
- @Override
- public void export(SimulationStorage simulation, Writer out)
- throws Exception {
- SimulationStorage referenceSimulation = SimulationStorage
- .getSimulation(param_referenceSimulation);
- ResultStorage resultStorage = simulation.getResultStorage();
- ResultStorage referenceResultStorage = referenceSimulation
- .getResultStorage();
- Date lastDate = resultStorage.getLastDate();
- Date firstDate = new Date(11);
- double biomass = 0.0;
- double firstbiomass = 0.0;
- double biomassReference = 0.0;
- double firstbiomassReference = 0.0;
-
- for (Population pop : simulation.getParameter().getPopulations()) {
- if (pop.getName().equals(param_pop.getName())) {
-
- //Get the biomass of the first time step
- MatrixND matfirstdate = resultStorage.getMatrix(pop,
- ResultName.MATRIX_BIOMASS);
- for (MatrixIterator i = matfirstdate.iterator(); i.hasNext();) {
- i.next();
- Object[] sems = i.getSemanticsCoordinates();
- PopulationGroup group = (PopulationGroup) sems[1];
- Date date = (Date) sems[0];
- if (date.equals(firstDate)) {
- firstbiomass += i.getValue()
- * group.getReproductionRate();
- }
- }
-
- //Get the biomass of the last time step
- MatrixND matlastdate = resultStorage.getMatrix(pop,
- ResultName.MATRIX_BIOMASS);
- for (MatrixIterator i = matlastdate.iterator(); i.hasNext();) {
- i.next();
- Object[] sems = i.getSemanticsCoordinates();
- PopulationGroup group = (PopulationGroup) sems[1];
- Date date = (Date) sems[0];
- if (date.equals(lastDate)) {
- biomass = biomass + i.getValue()
- * group.getReproductionRate();
- }
- }
-
- //Get the reference biomass of the first time step
- TopiaContext tx = referenceSimulation.getStorage()
- .beginTransaction();
- MatrixND matfirstdatereference = referenceResultStorage
- .getMatrix(ResultName.MATRIX_BIOMASS + " " + pop, tx);
- for (MatrixIterator i = matfirstdatereference.iterator(); i
- .hasNext();) {
- i.next();
- Object[] sems = i.getSemanticsCoordinates();
- PopulationGroup group = (PopulationGroup) sems[1];
- Date date = (Date) sems[0];
- if (date.equals(firstDate)) {
- firstbiomassReference += i.getValue()
- * group.getReproductionRate();
- }
- }
-
- //Get the reference biomass of the last time step
- MatrixND matlastdatereference = referenceResultStorage
- .getMatrix(ResultName.MATRIX_BIOMASS + " " + pop, tx);
- for (MatrixIterator i = matlastdatereference.iterator(); i
- .hasNext();) {
- i.next();
- Object[] sems = i.getSemanticsCoordinates();
- PopulationGroup group = (PopulationGroup) sems[1];
- Date date = (Date) sems[0];
- if (date.equals(lastDate)) {
- biomassReference += i.getValue()
- * group.getReproductionRate();
- }
- }
- tx.commitTransaction();
- tx.closeContext();
- }
- }
- out.write(Double.toString((biomass / firstbiomass)
- / (biomassReference / firstbiomassReference)));
- }
-
- @Override
- public String getDescription() {
- return _("Biomass of the genitors for the last time step. Biomass is the sum on the groups and zones");
- }
-
- @Override
- public String getExportFilename() {
- return "SensitivityGenitorBiomassRelativeReferenceY11";
- }
-
- @Override
- public String getExtensionFilename() {
- return ".csv";
- }
-
- @Override
- public String[] getNecessaryResult() {
- return this.necessaryResult;
- }
-
-}
\ No newline at end of file
Deleted: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityGenitorBiomassRelativeY5.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityGenitorBiomassRelativeY5.java 2011-07-08 14:22:36 UTC (rev 3441)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityGenitorBiomassRelativeY5.java 2011-07-08 14:23:25 UTC (rev 3442)
@@ -1,118 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-package sensitivityexports;
-
-import static org.nuiton.i18n.I18n._;
-
-import java.io.Writer;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.math.matrix.MatrixIterator;
-import org.nuiton.math.matrix.MatrixND;
-
-import scripts.ResultName;
-import fr.ifremer.isisfish.datastore.ResultStorage;
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.entities.Population;
-import fr.ifremer.isisfish.entities.PopulationGroup;
-import fr.ifremer.isisfish.export.SensitivityExport;
-import fr.ifremer.isisfish.types.Date;
-import fr.ifremer.isisfish.util.Doc;
-
-public class SensitivityGenitorBiomassRelativeY5 implements SensitivityExport {
-
- /** to use log facility, just put in your code: log.info("..."); */
- static private Log log = LogFactory
- .getLog(SensitivityGenitorBiomassRelativeY5.class);
-
- protected String[] necessaryResult = { ResultName.MATRIX_BIOMASS };
-
- @Doc("Population")
- public Population param_pop;
-
- @Override
- public void export(SimulationStorage simulation, Writer out)
- throws Exception {
- Date lastDate = simulation.getResultStorage().getLastDate();
- Date firstDate = new Date(11);
- double biomass = 0.0;
- double firstbiomass = 0.0;
-
- for (Population pop : simulation.getParameter().getPopulations()) {
- if (pop.getName().equals(param_pop.getName())) {
- ResultStorage resultStorage = simulation.getResultStorage();
-
- //Get the biomass of the first time step
- MatrixND matfirstdate = resultStorage.getMatrix(pop,
- ResultName.MATRIX_BIOMASS);
- for (MatrixIterator i = matfirstdate.iterator(); i.hasNext();) {
- i.next();
- Object[] sems = i.getSemanticsCoordinates();
- PopulationGroup group = (PopulationGroup) sems[1];
- Date date = (Date) sems[0];
- if (date.equals(firstDate)) {
- firstbiomass += i.getValue()
- * group.getReproductionRate();
- }
- }
-
- //Get the biomass of the last time step
- MatrixND matlastdate = resultStorage.getMatrix(pop,
- ResultName.MATRIX_BIOMASS);
- for (MatrixIterator i = matlastdate.iterator(); i.hasNext();) {
- i.next();
- Object[] sems = i.getSemanticsCoordinates();
- PopulationGroup group = (PopulationGroup) sems[1];
- Date date = (Date) sems[0];
- if (date.equals(lastDate))
- biomass += i.getValue() * group.getReproductionRate();
- }
- }
- }
- out.write(Double.toString(biomass / firstbiomass));
- }
-
- @Override
- public String getDescription() {
- return _("Biomass of the genitors for the last time step. Biomass is the sum on the groups and zones");
- }
-
- @Override
- public String getExportFilename() {
- return "SensitivityGenitorBiomassRelativeY5";
- }
-
- @Override
- public String getExtensionFilename() {
- return ".csv";
- }
-
- @Override
- public String[] getNecessaryResult() {
- return this.necessaryResult;
- }
-
-}
\ No newline at end of file
Deleted: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityGenitorBiomassY2.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityGenitorBiomassY2.java 2011-07-08 14:22:36 UTC (rev 3441)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityGenitorBiomassY2.java 2011-07-08 14:23:25 UTC (rev 3442)
@@ -1,103 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-package sensitivityexports;
-
-import static org.nuiton.i18n.I18n._;
-
-import java.io.Writer;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.math.matrix.MatrixIterator;
-import org.nuiton.math.matrix.MatrixND;
-
-import scripts.ResultName;
-import fr.ifremer.isisfish.datastore.ResultStorage;
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.entities.Population;
-import fr.ifremer.isisfish.entities.PopulationGroup;
-import fr.ifremer.isisfish.export.SensitivityExport;
-import fr.ifremer.isisfish.types.Date;
-import fr.ifremer.isisfish.util.Doc;
-
-public class SensitivityGenitorBiomassY2 implements SensitivityExport {
-
- /** to use log facility, just put in your code: log.info("..."); */
- static private Log log = LogFactory
- .getLog(SensitivityGenitorBiomassY2.class);
-
- protected String[] necessaryResult = { ResultName.MATRIX_BIOMASS };
-
- @Doc("Population")
- public Population param_pop;
-
- @Override
- public void export(SimulationStorage simulation, Writer out)
- throws Exception {
- Date lastDate = simulation.getResultStorage().getLastDate();
- double biomass = 0.0;
-
- for (Population pop : simulation.getParameter().getPopulations()) {
- if (pop.getName().equals(param_pop.getName())) {
- ResultStorage resultStorage = simulation.getResultStorage();
-
- //Get the biomass of the last time step
- MatrixND matlastdate = resultStorage.getMatrix(pop,
- ResultName.MATRIX_BIOMASS);
- for (MatrixIterator i = matlastdate.iterator(); i.hasNext();) {
- i.next();
- Object[] sems = i.getSemanticsCoordinates();
- Date date = (Date) sems[0];
- PopulationGroup group = (PopulationGroup) sems[1];
- if (date.equals(lastDate)) {
- biomass += i.getValue() * group.getReproductionRate();
- }
- }
- }
- }
- out.write(Double.toString(biomass));
- }
-
- @Override
- public String getDescription() {
- return _("Biomass of the genitors for the last time step. Biomass is the sum on the groups and zones");
- }
-
- @Override
- public String getExportFilename() {
- return "SensitivityGenitorBiomassY2";
- }
-
- @Override
- public String getExtensionFilename() {
- return ".csv";
- }
-
- @Override
- public String[] getNecessaryResult() {
- return this.necessaryResult;
- }
-
-}
Added: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassReferenceY8.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassReferenceY8.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassReferenceY8.java 2011-07-08 14:23:25 UTC (rev 3442)
@@ -0,0 +1,154 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+package sensitivityexports;
+
+import static org.nuiton.i18n.I18n._;
+
+import java.io.File;
+import java.io.Writer;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.math.matrix.MatrixIterator;
+import org.nuiton.math.matrix.MatrixND;
+
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.util.ReverseFileReader;
+import scripts.ResultName;
+import fr.ifremer.isisfish.datastore.ResultStorage;
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.entities.Population;
+import fr.ifremer.isisfish.entities.PopulationGroup;
+import fr.ifremer.isisfish.export.SensitivityExport;
+import fr.ifremer.isisfish.types.TimeStep;
+import fr.ifremer.isisfish.util.Doc;
+
+public class SensitivitySpawningBiomassReferenceY8 implements SensitivityExport {
+
+ /** to use log facility, just put in your code: log.info("..."); */
+ static private Log log = LogFactory
+ .getLog(SensitivitySpawningBiomassReferenceY8.class);
+
+ protected String[] necessaryResult = { ResultName.MATRIX_BIOMASS };
+
+ @Doc("Population")
+ public Population param_pop;
+
+ @Doc("URL of the Biomasses.csv reference export file")
+ public String param_referenceBiomassCSV ="";
+
+ @Override
+ public void export(SimulationStorage simulation, Writer out)
+ throws Exception {
+ ResultStorage resultStorage = simulation.getResultStorage();
+ TimeStep lastStep = resultStorage.getLastStep();
+ Double biomass = 0.0;
+ Double referenceBiomass = 0.0;
+
+ File referenceFile = new File(param_referenceBiomassCSV);
+
+ TopiaContext tx = simulation.getStorage().beginTransaction();
+
+ Population tempPop = (Population)tx.findByTopiaId(param_pop.getTopiaId());
+
+ List<PopulationGroup> groups = tempPop.getPopulationGroup();
+
+ Map<Integer, Double> map =new HashMap<Integer,Double>();
+
+ for (PopulationGroup group:groups) {
+ map.put(group.getId(),group.getReproductionRate());
+ }
+
+ tx.closeContext();
+
+ //instantiate a reader that starts reading from the file end.
+ ReverseFileReader reader = new ReverseFileReader(referenceFile);
+
+ //read the last line of the file (should be empty)
+ String line = reader.readLine();
+
+ //read the next line (the last written line)
+ line = reader.readLine();
+
+
+ String lastMonth="";
+
+ while (line!=null ){
+
+ String[] items = line.split(";");
+
+ //If we did not initiate the last date (we are on the last line of
+ // the file), we do it now with the value of the date.
+ if ("".equals(lastMonth)) {
+ lastMonth = items[3];
+ }
+
+ if ((items[0].equals(param_pop.getName())) && (items[3].equals(lastMonth))){
+ referenceBiomass += Double.parseDouble(items[4]) * map.get(Integer.parseInt(items[1]));
+ }
+ line = reader.readLine();
+ }
+
+ for (Population pop : simulation.getParameter().getPopulations()) {
+ if (pop.getName().equals(param_pop.getName())) {
+
+ //Get the biomass of the last time step
+ MatrixND matlastdate = resultStorage.getMatrix(pop,
+ ResultName.MATRIX_BIOMASS);
+ for (MatrixIterator i = matlastdate.iterator(); i.hasNext();) {
+ i.next();
+ Object[] sems = i.getSemanticsCoordinates();
+ PopulationGroup group = (PopulationGroup) sems[1];
+ TimeStep step = (TimeStep) sems[0];
+ if (step.equals(lastStep)) {
+ biomass += i.getValue() * group.getReproductionRate();
+ }
+ }
+ }
+ }
+ out.write(Double.toString(biomass / referenceBiomass));
+ }
+
+ @Override
+ public String getDescription() {
+ return _("Biomass of the genitors for the last time step. Biomass is the sum on the groups and zones");
+ }
+
+ @Override
+ public String getExportFilename() {
+ return "SensitivitySpawningBiomassReferenceY8";
+ }
+
+ @Override
+ public String getExtensionFilename() {
+ return ".csv";
+ }
+
+ @Override
+ public String[] getNecessaryResult() {
+ return this.necessaryResult;
+ }
+
+}
Property changes on: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassReferenceY8.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassRelativeReferenceY11.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassRelativeReferenceY11.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassRelativeReferenceY11.java 2011-07-08 14:23:25 UTC (rev 3442)
@@ -0,0 +1,180 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+package sensitivityexports;
+
+import static org.nuiton.i18n.I18n._;
+
+import java.io.File;
+import java.io.Writer;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.math.matrix.MatrixIterator;
+import org.nuiton.math.matrix.MatrixND;
+import org.nuiton.topia.TopiaContext;
+
+import org.nuiton.util.ReverseFileReader;
+import scripts.ResultName;
+import fr.ifremer.isisfish.datastore.ResultStorage;
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.entities.Population;
+import fr.ifremer.isisfish.entities.PopulationGroup;
+import fr.ifremer.isisfish.export.SensitivityExport;
+import fr.ifremer.isisfish.types.TimeStep;
+import fr.ifremer.isisfish.util.Doc;
+
+public class SensitivitySpawningBiomassRelativeReferenceY11 implements
+ SensitivityExport {
+
+ /** to use log facility, just put in your code: log.info("..."); */
+ static private Log log = LogFactory
+ .getLog(SensitivitySpawningBiomassRelativeReferenceY11.class);
+
+ protected String[] necessaryResult = { ResultName.MATRIX_BIOMASS };
+
+ @Doc("Population")
+ public Population param_pop;
+
+ @Doc("URL of the Biomasses.csv reference export file")
+ public String param_referenceBiomassCSV ="";
+
+ @Override
+ public void export(SimulationStorage simulation, Writer out)
+ throws Exception {
+
+ ResultStorage resultStorage = simulation.getResultStorage();
+ TimeStep lastStep = resultStorage.getLastStep();
+ TimeStep firstStep = new TimeStep(11);
+ double biomass = 0.0;
+ double firstbiomass = 0.0;
+ double biomassReference = 0.0;
+ double firstBiomassReference = 0.0;
+
+ File referenceFile = new File(param_referenceBiomassCSV);
+
+ TopiaContext tx = simulation.getStorage().beginTransaction();
+
+ Population tempPop = (Population)tx.findByTopiaId(param_pop.getTopiaId());
+
+ List<PopulationGroup> groups = tempPop.getPopulationGroup();
+
+ Map<Integer, Double> map =new HashMap<Integer,Double>();
+
+ for (PopulationGroup group:groups) {
+ map.put(group.getId(),group.getReproductionRate());
+ }
+
+ tx.closeContext();
+
+ //instantiate a reader that starts reading from the file end.
+ ReverseFileReader reader = new ReverseFileReader(referenceFile);
+
+ //read the last line of the file (should be empty)
+ String line = reader.readLine();
+
+ //read the next line (the last written line)
+ line = reader.readLine();
+
+
+ String lastMonth="";
+
+ while (line != null ) {
+
+ String[] items = line.split(";");
+
+ //If we did not initiate the last date (we are on the last line of
+ // the file), we do it now with the value of the date.
+ if ("".equals(lastMonth)) {
+ lastMonth = items[3];
+ }
+
+ if ((items[0].equals(param_pop.getName())) && (items[3].equals(lastMonth))){
+ biomassReference += Double.parseDouble(items[4]) * map.get(Integer.parseInt(items[1]));
+ }
+
+ if ((items[0].equals(param_pop.getName())) && (items[3].equals("11"))){
+ firstBiomassReference += Double.parseDouble(items[4]) * map.get(Integer.parseInt(items[1]));
+ }
+
+ line = reader.readLine();
+ }
+
+ for (Population pop : simulation.getParameter().getPopulations()) {
+ if (pop.getName().equals(param_pop.getName())) {
+
+ //Get the biomass of the first time step
+ MatrixND matfirstdate = resultStorage.getMatrix(pop,
+ ResultName.MATRIX_BIOMASS);
+ for (MatrixIterator i = matfirstdate.iterator(); i.hasNext();) {
+ i.next();
+ Object[] sems = i.getSemanticsCoordinates();
+ PopulationGroup group = (PopulationGroup) sems[1];
+ TimeStep step = (TimeStep) sems[0];
+ if (step.equals(firstStep)) {
+ firstbiomass += i.getValue()
+ * group.getReproductionRate();
+ }
+ }
+
+ //Get the biomass of the last time step
+ MatrixND matlastdate = resultStorage.getMatrix(pop,
+ ResultName.MATRIX_BIOMASS);
+ for (MatrixIterator i = matlastdate.iterator(); i.hasNext();) {
+ i.next();
+ Object[] sems = i.getSemanticsCoordinates();
+ PopulationGroup group = (PopulationGroup) sems[1];
+ TimeStep step = (TimeStep) sems[0];
+ if (step.equals(lastStep)) {
+ biomass = biomass + i.getValue()
+ * group.getReproductionRate();
+ }
+ }
+ }
+ }
+ out.write(Double.toString((biomass / firstbiomass)
+ / (biomassReference / firstBiomassReference)));
+ }
+
+ @Override
+ public String getDescription() {
+ return _("Biomass of the genitors for the last time step. Biomass is the sum on the groups and zones");
+ }
+
+ @Override
+ public String getExportFilename() {
+ return "SensitivitySpawningBiomassRelativeReferenceY11";
+ }
+
+ @Override
+ public String getExtensionFilename() {
+ return ".csv";
+ }
+
+ @Override
+ public String[] getNecessaryResult() {
+ return this.necessaryResult;
+ }
+
+}
Property changes on: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassRelativeReferenceY11.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassRelativeY5.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassRelativeY5.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassRelativeY5.java 2011-07-08 14:23:25 UTC (rev 3442)
@@ -0,0 +1,115 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+package sensitivityexports;
+
+import static org.nuiton.i18n.I18n._;
+
+import java.io.Writer;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.math.matrix.MatrixIterator;
+import org.nuiton.math.matrix.MatrixND;
+
+import scripts.ResultName;
+import fr.ifremer.isisfish.datastore.ResultStorage;
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.entities.Population;
+import fr.ifremer.isisfish.entities.PopulationGroup;
+import fr.ifremer.isisfish.export.SensitivityExport;
+import fr.ifremer.isisfish.types.TimeStep;
+import fr.ifremer.isisfish.util.Doc;
+
+public class SensitivitySpawningBiomassRelativeY5 implements SensitivityExport {
+
+ /** to use log facility, just put in your code: log.info("..."); */
+ static private Log log = LogFactory
+ .getLog(SensitivitySpawningBiomassRelativeY5.class);
+
+ protected String[] necessaryResult = { ResultName.MATRIX_BIOMASS };
+
+ @Doc("Population")
+ public Population param_pop;
+
+ @Override
+ public void export(SimulationStorage simulation, Writer out)
+ throws Exception {
+ TimeStep lastStep = simulation.getResultStorage().getLastStep();
+ TimeStep firstStep = new TimeStep(11);
+ double biomass = 0.0;
+ double firstbiomass = 0.0;
+
+ for (Population pop : simulation.getParameter().getPopulations()) {
+ if (pop.getName().equals(param_pop.getName())) {
+ ResultStorage resultStorage = simulation.getResultStorage();
+
+ //Get the biomass of the first time step
+ MatrixND matfirstdate = resultStorage.getMatrix(pop,
+ ResultName.MATRIX_BIOMASS);
+ for (MatrixIterator i = matfirstdate.iterator(); i.hasNext();) {
+ i.next();
+ Object[] sems = i.getSemanticsCoordinates();
+ PopulationGroup group = (PopulationGroup) sems[1];
+ TimeStep step = (TimeStep) sems[0];
+ if (step.equals(firstStep)) {
+ firstbiomass += i.getValue()
+ * group.getReproductionRate();
+ }
+ }
+
+ //Get the biomass of the last time step
+ MatrixND matlastdate = resultStorage.getMatrix(pop,
+ ResultName.MATRIX_BIOMASS);
+ for (MatrixIterator i = matlastdate.iterator(); i.hasNext();) {
+ i.next();
+ Object[] sems = i.getSemanticsCoordinates();
+ PopulationGroup group = (PopulationGroup) sems[1];
+ TimeStep step = (TimeStep) sems[0];
+ if (step.equals(lastStep))
+ biomass += i.getValue() * group.getReproductionRate();
+ }
+ }
+ }
+ out.write(Double.toString(biomass / firstbiomass));
+ }
+
+ @Override
+ public String getDescription() {
+ return _("Biomass of the genitors for the last time step. Biomass is the sum on the groups and zones");
+ }
+
+ @Override
+ public String getExportFilename() {
+ return "SensitivityGenitorBiomassRelativeY5";
+ }
+
+ @Override
+ public String getExtensionFilename() {
+ return ".csv";
+ }
+
+ @Override
+ public String[] getNecessaryResult() {
+ return this.necessaryResult;
+ }
+
+}
Property changes on: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassRelativeY5.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassY2.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassY2.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassY2.java 2011-07-08 14:23:25 UTC (rev 3442)
@@ -0,0 +1,100 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+package sensitivityexports;
+
+import static org.nuiton.i18n.I18n._;
+
+import java.io.Writer;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.math.matrix.MatrixIterator;
+import org.nuiton.math.matrix.MatrixND;
+
+import scripts.ResultName;
+import fr.ifremer.isisfish.datastore.ResultStorage;
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.entities.Population;
+import fr.ifremer.isisfish.entities.PopulationGroup;
+import fr.ifremer.isisfish.export.SensitivityExport;
+import fr.ifremer.isisfish.types.TimeStep;
+import fr.ifremer.isisfish.util.Doc;
+
+public class SensitivitySpawningBiomassY2 implements SensitivityExport {
+
+ /** to use log facility, just put in your code: log.info("..."); */
+ static private Log log = LogFactory
+ .getLog(SensitivitySpawningBiomassY2.class);
+
+ protected String[] necessaryResult = { ResultName.MATRIX_BIOMASS };
+
+ @Doc("Population")
+ public Population param_pop;
+
+ @Override
+ public void export(SimulationStorage simulation, Writer out)
+ throws Exception {
+ TimeStep lastStep = simulation.getResultStorage().getLastStep();
+ double biomass = 0.0;
+
+ for (Population pop : simulation.getParameter().getPopulations()) {
+ if (pop.getName().equals(param_pop.getName())) {
+ ResultStorage resultStorage = simulation.getResultStorage();
+
+ //Get the biomass of the last time step
+ MatrixND matlastdate = resultStorage.getMatrix(pop,
+ ResultName.MATRIX_BIOMASS);
+ for (MatrixIterator i = matlastdate.iterator(); i.hasNext();) {
+ i.next();
+ Object[] sems = i.getSemanticsCoordinates();
+ TimeStep step = (TimeStep) sems[0];
+ PopulationGroup group = (PopulationGroup) sems[1];
+ if (step.equals(lastStep)) {
+ biomass += i.getValue() * group.getReproductionRate();
+ }
+ }
+ }
+ }
+ out.write(Double.toString(biomass));
+ }
+
+ @Override
+ public String getDescription() {
+ return _("Biomass of the genitors for the last time step. Biomass is the sum on the groups and zones");
+ }
+
+ @Override
+ public String getExportFilename() {
+ return "SensitivityGenitorBiomassY2";
+ }
+
+ @Override
+ public String getExtensionFilename() {
+ return ".csv";
+ }
+
+ @Override
+ public String[] getNecessaryResult() {
+ return this.necessaryResult;
+ }
+
+}
Property changes on: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivitySpawningBiomassY2.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
1
0
r3441 - in isis-fish/trunk/src/test/resources/test-database: . exports rules scripts sensitivityanalysis sensitivityexports simulationplans simulators
by chatellier@users.labs.libre-entreprise.org 08 Jul '11
by chatellier@users.labs.libre-entreprise.org 08 Jul '11
08 Jul '11
Author: chatellier
Date: 2011-07-08 14:22:36 +0000 (Fri, 08 Jul 2011)
New Revision: 3441
Log:
Fix isis test database
Added:
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorJavaExpandGrid.java
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRDOptimal.java
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRExpandGrid.java
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRFast.java
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRFrF2.java
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRMorris.java
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorROptimumLHS.java
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRRandomLHS.java
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRSobol.java
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRegularFractions.java
isis-fish/trunk/src/test/resources/test-database/simulationplans/
isis-fish/trunk/src/test/resources/test-database/simulationplans/CalibrationSimplexePasVariable2Capturabilite.java
isis-fish/trunk/src/test/resources/test-database/simulationplans/SimulationNumberRestriction.java
Removed:
isis-fish/trunk/src/test/resources/test-database/analyseplans/
isis-fish/trunk/src/test/resources/test-database/sensitivity/
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorJavaExpandGrid.java
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRFast.java
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRFrF2.java
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRMorris.java
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorROptimumLHS.java
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRRandomLHS.java
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRSobol.java
isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRegularFractions.java
isis-fish/trunk/src/test/resources/test-database/simulationplans/CalibrationSimplexePasVariable2Capturabilite.java
isis-fish/trunk/src/test/resources/test-database/simulationplans/SimulationNumberRestriction.java
Modified:
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/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/EffortReduction.java
isis-fish/trunk/src/test/resources/test-database/rules/GraviteVPUE1.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/TACpoids.java
isis-fish/trunk/src/test/resources/test-database/rules/TailleMin.java
isis-fish/trunk/src/test/resources/test-database/rules/TotalClosure.java
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/sensitivityexports/SensitivityBiomassReferenceY9.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityBiomassRelativeReferenceY12.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityBiomassRelativeY6.java
isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityBiomassY3.java
isis-fish/trunk/src/test/resources/test-database/simulators/DefaultSimulator.java
Modified: isis-fish/trunk/src/test/resources/test-database/exports/Abundances.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/exports/Abundances.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/exports/Abundances.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -36,7 +33,7 @@
import fr.ifremer.isisfish.entities.*;
import fr.ifremer.isisfish.export.Export;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.datastore.SimulationStorage;
/**
@@ -58,75 +55,41 @@
protected String [] necessaryResult = {
ResultName.MATRIX_ABUNDANCE
};
-
+
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
+ @Override
public String getExportFilename() {
return "Abondances";
}
-
+
+ @Override
public String getExtensionFilename() {
return ".csv";
}
-
+
+ @Override
public String getDescription() {
return _("Exporte les abondances en nombre tableau avec des lignes pop;id;zone;date;nombre.");
}
+ @Override
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];
+ TimeStep step = (TimeStep)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");
+ out.write(pop.getName() +";"+ group.getId() +";"+ zone.getName() +";"+ step.getStep() +";"+ 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;
-*/
}
-
}
Modified: isis-fish/trunk/src/test/resources/test-database/exports/Biomasses.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/exports/Biomasses.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/exports/Biomasses.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -37,7 +34,7 @@
import fr.ifremer.isisfish.entities.*;
import fr.ifremer.isisfish.export.Export;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.datastore.SimulationStorage;
/**
@@ -59,75 +56,41 @@
protected String [] necessaryResult = {
ResultName.MATRIX_BIOMASS
};
-
+
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
+ @Override
public String getExportFilename() {
return "Biomasses";
}
-
+
+ @Override
public String getExtensionFilename() {
return ".csv";
}
-
+
+ @Override
public String getDescription() {
return _("Exporte les biomasses tableau avec des lignes pop;id;zone;date;nombre");
}
+ @Override
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];
+ TimeStep step = (TimeStep)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");
+ out.write(pop.getName() +";"+ group.getId() +";"+ zone.getName() +";"+ step.getStep() +";"+ 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;
-*/
}
-
}
Modified: isis-fish/trunk/src/test/resources/test-database/exports/CapturesNombre.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/exports/CapturesNombre.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/exports/CapturesNombre.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -40,7 +37,7 @@
import fr.ifremer.isisfish.entities.PopulationGroup;
import fr.ifremer.isisfish.entities.Zone;
import fr.ifremer.isisfish.export.Export;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* CapturesNombre.java
@@ -59,30 +56,35 @@
protected String[] necessaryResult = { ResultName.MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_POP };
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
+ @Override
public String getExportFilename() {
return "CapturesNombre";
}
+ @Override
public String getExtensionFilename() {
return ".csv";
}
+ @Override
public String getDescription() {
return _("Export les captures en nombre de la simulation. tableau pop;metier;id;zone;nombre");
}
+ @Override
public void export(SimulationStorage simulation, Writer out)
throws Exception {
- Date lastDate = simulation.getResultStorage().getLastDate();
+ TimeStep lastStep = simulation.getResultStorage().getLastStep();
for (Population pop : simulation.getParameter().getPopulations()) {
- for (Date date = new Date(0); !date.after(lastDate); date = date
+ for (TimeStep step = new TimeStep(0); !step.after(lastStep); step = step
.next()) {
- MatrixND mat = simulation.getResultStorage().getMatrix(date,
+ MatrixND mat = simulation.getResultStorage().getMatrix(step,
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
@@ -96,50 +98,10 @@
double val = i.getValue();
out.write(pop.getName() + ";" + metier.getName() + ";"
+ group.getId() + ";" + zone.getName() + ";"
- + date.getDate() + ";" + val + "\n");
+ + step.getStep() + ";" + 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;
-
- */
}
-
}
Modified: isis-fish/trunk/src/test/resources/test-database/exports/CapturesPoids.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/exports/CapturesPoids.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/exports/CapturesPoids.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -40,7 +37,7 @@
import fr.ifremer.isisfish.entities.PopulationGroup;
import fr.ifremer.isisfish.entities.Zone;
import fr.ifremer.isisfish.export.Export;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* CapturesPoids.java
@@ -59,30 +56,35 @@
protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP };
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
+ @Override
public String getExportFilename() {
return "CapturesPoids";
}
+ @Override
public String getExtensionFilename() {
return ".csv";
}
+ @Override
public String getDescription() {
return _("Export les captures en poids de la simulation. tableau pop;metier;id;zone;nombre");
}
+ @Override
public void export(SimulationStorage simulation, Writer out)
throws Exception {
- Date lastDate = simulation.getResultStorage().getLastDate();
+ TimeStep lastStep = simulation.getResultStorage().getLastStep();
for (Population pop : simulation.getParameter().getPopulations()) {
- for (Date date = new Date(0); !date.after(lastDate); date = date
+ for (TimeStep step = new TimeStep(0); !step.after(lastStep); step = step
.next()) {
- MatrixND mat = simulation.getResultStorage().getMatrix(date,
+ MatrixND mat = simulation.getResultStorage().getMatrix(step,
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
@@ -96,46 +98,10 @@
double val = i.getValue();
out.write(pop.getName() + ";" + metier.getName() + ";"
+ group.getId() + ";" + zone.getName() + ";"
- + date.getDate() + ";" + val + "\n");
+ + step.getStep() + ";" + 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;
-
- */
}
-
}
Modified: isis-fish/trunk/src/test/resources/test-database/exports/CellsDefinition.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/exports/CellsDefinition.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/exports/CellsDefinition.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -60,22 +57,27 @@
// ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET,
};
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
+ @Override
public String getExportFilename() {
return "MailleDefinition";
}
-
+
+ @Override
public String getExtensionFilename() {
return ".csv";
}
-
+
+ @Override
public String getDescription() {
return _("Export cell's position(longitute/latitute)");
}
+ @Override
public void export(SimulationStorage simulation, Writer out) throws Exception {
TopiaContext tx = simulation.getStorage().beginTransaction();
List<Cell> cells = SimulationStorage.getFisheryRegion(tx).getCell();
@@ -86,5 +88,4 @@
tx.closeContext();
}
-
}
Modified: isis-fish/trunk/src/test/resources/test-database/exports/EffortsMetier.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/exports/EffortsMetier.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/exports/EffortsMetier.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -37,7 +34,7 @@
import fr.ifremer.isisfish.entities.*;
import fr.ifremer.isisfish.export.Export;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.datastore.SimulationStorage;
/**
@@ -59,63 +56,39 @@
protected String [] necessaryResult = {
ResultName.MATRIX_EFFORT_PER_STRATEGY_MET
};
-
+
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
+ @Override
public String getExportFilename() {
return "EffortsMetier";
}
-
+
+ @Override
public String getExtensionFilename() {
return ".csv";
}
-
+
+ @Override
public String getDescription() {
return _("retourne un tableau strategie;metier;date;effort");
}
+ @Override
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];
+ TimeStep step = (TimeStep)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;
-
-*/
+ out.write(str.getName() +";"+ metier.getName() +";"+ step.getStep() +";"+ val +"\n");
+ }
}
-
}
Modified: isis-fish/trunk/src/test/resources/test-database/exports/MetierZone.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/exports/MetierZone.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/exports/MetierZone.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -35,7 +32,7 @@
import scripts.ResultName;
import fr.ifremer.isisfish.export.Export;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.datastore.SimulationStorage;
/**
@@ -58,38 +55,42 @@
ResultName.MATRIX_METIER_ZONE,
};
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
+ @Override
public String getExportFilename() {
return "MetierZone";
}
-
+
+ @Override
public String getExtensionFilename() {
return ".csv";
}
-
+
+ @Override
public String getDescription() {
return _("Export zone used by metier during simulation");
}
+ @Override
public void export(SimulationStorage simulation, Writer out) throws Exception {
- Date lastDate = simulation.getResultStorage().getLastDate();
+ TimeStep lastStep = simulation.getResultStorage().getLastStep();
- for (Date date = new Date(0); !date.after(lastDate); date = date.next() ) {
- MatrixND mat = simulation.getResultStorage().getMatrix(date, ResultName.MATRIX_METIER_ZONE);
+ for (TimeStep step = new TimeStep(0); !step.after(lastStep); step = step.next() ) {
+ MatrixND mat = simulation.getResultStorage().getMatrix(step, 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");
+ out.write(metier + ";" + zone + ";" + step.getStep() + "\n");
}
}
}
}
}
-
}
Modified: isis-fish/trunk/src/test/resources/test-database/exports/NonActivite.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/exports/NonActivite.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/exports/NonActivite.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -37,9 +34,8 @@
import fr.ifremer.isisfish.entities.*;
import fr.ifremer.isisfish.export.Export;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.datastore.ResultStorage;
/**
* NonActivite.java
@@ -60,65 +56,39 @@
protected String [] necessaryResult = {
ResultName.MATRIX_NO_ACTIVITY
};
-
+
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
+ @Override
public String getExportFilename() {
return "NonActivite";
}
-
+
+ @Override
public String getExtensionFilename() {
return ".csv";
}
-
+
+ @Override
public String getDescription() {
return _("retourne un tableau strategie;metier;date;proportion");
}
+ @Override
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];
+ TimeStep step = (TimeStep)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");
+ out.write(str.getName() +";"+ metier.getName() +";"+ step.getStep() +";"+ 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;
-*/
}
-
}
Modified: isis-fish/trunk/src/test/resources/test-database/exports/OwnerMargin.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/exports/OwnerMargin.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/exports/OwnerMargin.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -37,7 +34,7 @@
import fr.ifremer.isisfish.entities.*;
import fr.ifremer.isisfish.export.Export;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.datastore.SimulationStorage;
/**
@@ -59,60 +56,38 @@
protected String [] necessaryResult = {
ResultName.MATRIX_OWNER_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_PER_VESSEL
};
-
+
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
+ @Override
public String getExportFilename() {
return "PatronProfit";
}
-
+
+ @Override
public String getExtensionFilename() {
return ".csv";
}
-
+
+ @Override
public String getDescription() {
return _("Exporte les profits du patrons, retourne un tableau strategy;date;value");
}
+ @Override
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];
+ TimeStep step = (TimeStep)sems[0];
Strategy str = (Strategy)sems[1];
double val = i.getValue();
- out.write(str.getName() +";"+ date.getDate() +";"+ val +"\n");
+ out.write(str.getName() +";"+ step.getStep() +";"+ 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;
-*/
}
-
}
Modified: isis-fish/trunk/src/test/resources/test-database/exports/RegionDefinition.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/exports/RegionDefinition.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/exports/RegionDefinition.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -59,22 +56,27 @@
// ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET,
};
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
+ @Override
public String getExportFilename() {
return "RegionDefinition";
}
-
+
+ @Override
public String getExtensionFilename() {
return ".csv";
}
-
+
+ @Override
public String getDescription() {
return _("Export region description");
}
+ @Override
public void export(SimulationStorage simulation, Writer out) throws Exception {
// NomRegion LatituteMin LatitudeMax LongitudeMin LongitudeMax PasLatitude PasLongitude
TopiaContext tx = simulation.getStorage().beginTransaction();
@@ -91,5 +93,4 @@
tx.closeContext();
}
-
}
Modified: isis-fish/trunk/src/test/resources/test-database/exports/RejetsNombre.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/exports/RejetsNombre.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/exports/RejetsNombre.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -40,7 +37,7 @@
import fr.ifremer.isisfish.entities.PopulationGroup;
import fr.ifremer.isisfish.entities.Zone;
import fr.ifremer.isisfish.export.Export;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* RejetsNombre.java
@@ -59,30 +56,35 @@
protected String[] necessaryResult = { ResultName.MATRIX_DISCARDS_PER_STR_MET_PER_ZONE_POP };
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
+ @Override
public String getExportFilename() {
return "RejetsNombre";
}
+ @Override
public String getExtensionFilename() {
return ".csv";
}
+ @Override
public String getDescription() {
return _("Export les rejets en nombre de la simulation. tableau pop;metier;id;zone;date;nombre");
}
+ @Override
public void export(SimulationStorage simulation, Writer out)
throws Exception {
- Date lastDate = simulation.getResultStorage().getLastDate();
+ TimeStep lastStep = simulation.getResultStorage().getLastStep();
for (Population pop : simulation.getParameter().getPopulations()) {
- for (Date date = new Date(0); !date.after(lastDate); date = date
+ for (TimeStep step = new TimeStep(0); !step.after(lastStep); step = step
.next()) {
- MatrixND mat = simulation.getResultStorage().getMatrix(date,
+ MatrixND mat = simulation.getResultStorage().getMatrix(step,
pop, ResultName.MATRIX_DISCARDS_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
@@ -96,49 +98,10 @@
double val = i.getValue();
out.write(pop.getName() + ";" + metier.getName() + ";"
+ group.getId() + ";" + zone.getName() + ";"
- + date.getDate() + ";" + val + "\n");
+ + step.getStep() + ";" + 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;
- */
}
-
}
Modified: isis-fish/trunk/src/test/resources/test-database/exports/RejetsPoids.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/exports/RejetsPoids.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/exports/RejetsPoids.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -40,7 +37,7 @@
import fr.ifremer.isisfish.entities.PopulationGroup;
import fr.ifremer.isisfish.entities.Zone;
import fr.ifremer.isisfish.export.Export;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* RejetsPoids.java
@@ -61,30 +58,35 @@
};
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
+ @Override
public String getExportFilename() {
return "RejetsPoids";
}
+ @Override
public String getExtensionFilename() {
return ".csv";
}
+ @Override
public String getDescription() {
return _("Export les rejets en poids de la simulation. tableau pop;metier;id;zone;date;nombre");
}
+ @Override
public void export(SimulationStorage simulation, Writer out)
throws Exception {
- Date lastDate = simulation.getResultStorage().getLastDate();
+ TimeStep lastStep = simulation.getResultStorage().getLastStep();
for (Population pop : simulation.getParameter().getPopulations()) {
- for (Date date = new Date(0); !date.after(lastDate); date = date
+ for (TimeStep step = new TimeStep(0); !step.after(lastStep); step = step
.next()) {
- MatrixND mat = simulation.getResultStorage().getMatrix(date,
+ MatrixND mat = simulation.getResultStorage().getMatrix(step,
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
@@ -98,48 +100,10 @@
double val = i.getValue();
out.write(pop.getName() + ";" + metier.getName() + ";"
+ group.getId() + ";" + zone.getName() + ";"
- + date.getDate() + ";" + val + "\n");
+ + step.getStep() + ";" + 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;
- */
}
-
}
Modified: isis-fish/trunk/src/test/resources/test-database/exports/VesselMargin.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/exports/VesselMargin.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/exports/VesselMargin.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -37,7 +34,7 @@
import fr.ifremer.isisfish.entities.*;
import fr.ifremer.isisfish.export.Export;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.datastore.SimulationStorage;
/**
@@ -59,60 +56,38 @@
protected String [] necessaryResult = {
ResultName.MATRIX_VESSEL_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_PER_VESSEL
};
-
+
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
+ @Override
public String getExportFilename() {
return "BateauProfit";
}
-
+
+ @Override
public String getExtensionFilename() {
return ".csv";
}
-
+
+ @Override
public String getDescription() {
return _("cvs out strategy;date;value");
}
+ @Override
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];
+ TimeStep step = (TimeStep)sems[0];
Strategy str = (Strategy)sems[1];
double val = i.getValue();
- out.write(str.getName() +";"+ date.getDate() +";"+ val +"\n");
+ out.write(str.getName() +";"+ step.getStep() +";"+ 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;
-*/
}
-
}
Modified: isis-fish/trunk/src/test/resources/test-database/exports/ZonesDefinition.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/exports/ZonesDefinition.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/exports/ZonesDefinition.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -35,7 +32,7 @@
import fr.ifremer.isisfish.entities.*;
import fr.ifremer.isisfish.export.Export;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.datastore.SimulationStorage;
/**
@@ -61,37 +58,41 @@
// ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET,
};
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
+ @Override
public String getExportFilename() {
return "ZonesDefinition";
}
-
+
+ @Override
public String getExtensionFilename() {
return ".csv";
}
-
+
+ @Override
public String getDescription() {
return _("Export cell's zone constitution");
}
+ @Override
public void export(SimulationStorage simulation, Writer out) throws Exception {
TopiaContext tx = simulation.getStorage().beginTransaction();
List<Zone> zones = SimulationStorage.getFisheryRegion(tx).getZone();
- Date lastDate = simulation.getResultStorage().getLastDate();
+ TimeStep lastStep = simulation.getResultStorage().getLastStep();
- for (Date date = new Date(0); !date.after(lastDate); date = date.next() ) {
+ for (TimeStep step = new TimeStep(0); !step.after(lastStep); step = step.next() ) {
for (Zone zone : zones) {
for (Cell cell : zone.getCell()) {
- out.write(zone + ";" + cell + ";" + date.getDate() + "\n");
+ out.write(zone + ";" + cell + ";" + step.getStep() + "\n");
}
}
}
tx.closeContext();
}
-
}
Modified: isis-fish/trunk/src/test/resources/test-database/rules/Cantonnement.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/rules/Cantonnement.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/rules/Cantonnement.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -43,7 +40,7 @@
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.TimeStep;
import fr.ifremer.isisfish.types.Month;
import fr.ifremer.isisfish.entities.*;
import fr.ifremer.isisfish.rule.AbstractRule;
@@ -74,10 +71,10 @@
public Zone param_zone = null;
@Doc(value="Engin concernés")
public Gear param_gear = null;
- @Doc(value="Begin date")
- public Date param_beginDate = new Date(0);
- @Doc(value="End date")
- public Date param_endDate = new Date(119);
+ @Doc(value="Begin step")
+ public TimeStep param_beginStep = new TimeStep(0);
+ @Doc(value="End step")
+ public TimeStep param_endStep = new TimeStep(119);
@Doc(value="Begin month")
public Month param_beginMonth = Month.JANUARY;
@Doc(value="End month")
@@ -91,6 +88,7 @@
ResultName.MATRIX_NO_ACTIVITY,
};
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
@@ -99,6 +97,7 @@
* Permet d'afficher a l'utilisateur une aide sur la regle.
* @return L'aide ou la description de la regle
*/
+ @Override
public String getDescription() throws Exception {
// fermeture saisiniere de zone qui peut être réduite à un engin
// et a certaines années de la simulation
@@ -110,25 +109,30 @@
* des valeurs
* @param context La simulation pour lequel on utilise cette regle
*/
+ @Override
public void init(SimulationContext context) throws Exception {
}
/**
- * La condition qui doit etre vrai pour faire les actions
- * @param context La simulation pour lequel on utilise cette regle
+ * La condition qui doit etre vrai pour faire les actions.
+ *
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
* @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)) {
+ @Override
+ public boolean condition(SimulationContext context, TimeStep step, Metier metier) throws Exception {
+ if (step.before(param_beginStep)) {
return false;
- } else if(date.after(param_endDate)) {
- return false;
+ } else if(step.after(param_endStep)) {
+ return false;
}
- if (date.getMonth().before(param_beginMonth)) {
+ if (step.getMonth().before(param_beginMonth)) {
return false;
- } else if (date.getMonth().after(param_endMonth)) {
+ } else if (step.getMonth().after(param_endMonth)) {
return false;
}
if (param_gear != null && !param_gear.equals(metier.getGear())) {
@@ -136,7 +140,7 @@
}
- List<Cell> cellMetiers = metier.getMetierSeasonInfo(date.getMonth()).getCells();
+ List<Cell> cellMetiers = metier.getMetierSeasonInfo(step.getMonth()).getCells();
List<Cell> cells = param_zone.getCell();
cellMetiers.retainAll(cells);
@@ -147,41 +151,21 @@
}
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
+ * Si la condition est vrai alors cette action est executee avant le pas
* de temps de la simulation.
- * @param context La simulation pour lequel on utilise cette regle
+ *
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void preAction(SimulationContext context, Date date, Metier metier) throws Exception {
+ @Override
+ public void preAction(SimulationContext context, TimeStep step, Metier metier) throws Exception {
MetierMonitor metierMon = context.getMetierMonitor();
- MetierSeasonInfo infoMetier = metier.getMetierSeasonInfo(date.getMonth());
+ MetierSeasonInfo infoMetier = metier.getMetierSeasonInfo(step.getMonth());
List<Cell> cellMetiers = infoMetier.getCells();
List<Cell> cells = param_zone.getCell();
@@ -194,7 +178,7 @@
//
// Create new empty zone for cantonnement
//
- String name = "ZoneCantonnement-" + metier.getName()+ "-" + date.getDate();
+ String name = "ZoneCantonnement-" + metier.getName()+ "-" + step.getStep();
Zone zoneCantonnement = dao.findByName(name);
int cpt=0;
while (zoneCantonnement != null) {
@@ -211,7 +195,7 @@
// Remove prohibited zone and add not prohibited cell to zoneCantonnement
//
Collection<Zone> zoneMetiers = infoMetier.getZone();
- for (Iterator<Zone> i=zoneMetiers.iterator(); i.hasNext();) {
+ 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());
@@ -220,7 +204,7 @@
zoneCantonnement.addAllCell(tmpCells);
i.remove();
}
- ArrayList<Zone> newZone = new ArrayList<Zone>();
+ List<Zone> newZone = new ArrayList<Zone>();
newZone.add(zoneCantonnement);
infoMetier.setZone(newZone);
} else {
@@ -228,15 +212,15 @@
// alors metier devient metier-nonactivite
SiMatrix siMatrix = SiMatrix.getSiMatrix(context);
- MatrixND noActivity = metierMon.getOrCreateNoActivity(date,
+ MatrixND noActivity = metierMon.getOrCreateNoActivity(step,
ResultName.MATRIX_NO_ACTIVITY,
- siMatrix.getStrategies(date),
- siMatrix.getMetiers(date));
+ siMatrix.getStrategies(step),
+ siMatrix.getMetiers(step));
metierMon.addforbiddenMetier(metier);
- List<Strategy> strategies = siMatrix.getStrategies(date);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
for(Strategy str : strategies){
- StrategyMonthInfo info = str.getStrategyMonthInfo(date.getMonth());
+ StrategyMonthInfo info = str.getStrategyMonthInfo(step.getMonth());
double prop = info.getProportionMetier(metier);
if (prop != 0){
noActivity.setValue(str , metier, prop);
@@ -244,112 +228,19 @@
}
}
}
- // 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);
+ // fin de preAction
}
- 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 context La simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void postAction(SimulationContext context, Date date, Metier metier) throws Exception {
+ @Override
+ public void postAction(SimulationContext context, TimeStep step, Metier metier) throws Exception {
// nothing
}
Modified: isis-fish/trunk/src/test/resources/test-database/rules/CantonnementPreSimu.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/rules/CantonnementPreSimu.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/rules/CantonnementPreSimu.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -43,7 +40,7 @@
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.TimeStep;
import fr.ifremer.isisfish.types.Month;
import fr.ifremer.isisfish.datastore.RegionStorage;
import fr.ifremer.isisfish.entities.*;
@@ -87,6 +84,7 @@
ResultName.MATRIX_NO_ACTIVITY,
};
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
@@ -95,6 +93,7 @@
* Permet d'afficher a l'utilisateur une aide sur la regle.
* @return L'aide ou la description de la regle
*/
+ @Override
public String getDescription() throws Exception {
return _("Cantonnement: can be used to Cantonnement with gear if you put gear in parameter");
}
@@ -138,14 +137,13 @@
* des valeurs
* @param context La simulation pour lequel on utilise cette regle
*/
+ @Override
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();
@@ -153,9 +151,7 @@
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)){
@@ -232,8 +228,6 @@
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();
@@ -284,9 +278,6 @@
}
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
@@ -318,420 +309,65 @@
}
}
- /*
- 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 context La simulation pour lequel on utilise cette regle
+ * La condition qui doit etre vrai pour faire les actions.
+ *
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
* @return vrai si on souhaite que les actions soit faites
*/
- public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception {
+ @Override
+ public boolean condition(SimulationContext context, TimeStep step, Metier metier) throws Exception {
boolean result = false;
- MatrixND mat = tableNonActivite.get(date.getMonth());
+ MatrixND mat = tableNonActivite.get(step.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
+ * Si la condition est vrai alors cette action est executee avant le pas
* de temps de la simulation.
- * @param context La simulation pour lequel on utilise cette regle
+ *
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void preAction(SimulationContext context, Date date, Metier metier) throws Exception {
+ @Override
+ public void preAction(SimulationContext context, TimeStep step, 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());
+ MatrixND mat = tableNonActivite.get(step.getMonth());
MetierMonitor metierMon = context.getMetierMonitor();
- MatrixND noActivity = metierMon.getNoActivity(date);
+ MatrixND noActivity = metierMon.getNoActivity(step);
if (noActivity == null){
- metierMon.setNoActivity(date, mat.copy());
+ metierMon.setNoActivity(step, 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 context La simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void postAction(SimulationContext context, Date date, Metier metier) throws Exception {
+ @Override
+ public void postAction(SimulationContext context, TimeStep step, Metier metier) throws Exception {
affectNonActivite = false;
-
- /*
- p.affectNonActivite=false;
-return p.gestionMetier;
- */
}
}
Modified: isis-fish/trunk/src/test/resources/test-database/rules/ChangementParamControlablePresimu.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/rules/ChangementParamControlablePresimu.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/rules/ChangementParamControlablePresimu.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -49,7 +46,7 @@
import fr.ifremer.isisfish.entities.Zone;
import fr.ifremer.isisfish.rule.AbstractRule;
import fr.ifremer.isisfish.simulator.SimulationContext;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.types.Month;
import fr.ifremer.isisfish.util.Doc;
@@ -87,6 +84,7 @@
// ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET,
};
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
@@ -95,6 +93,7 @@
* Permet d'afficher a l'utilisateur une aide sur la regle.
* @return L'aide ou la description de la regle
*/
+ @Override
public String getDescription() throws Exception {
return _("Change gear parameter value for all metier with this gear");
}
@@ -104,6 +103,7 @@
* des valeurs
* @param context La simulation pour lequel on utilise cette regle
*/
+ @Override
public void init(SimulationContext context) throws Exception {
SiMatrix siMatrix = SiMatrix.getSiMatrix(context);
@@ -214,137 +214,45 @@
// 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 context La simulation pour lequel on utilise cette regle
+ *
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
* @return vrai si on souhaite que les actions soit faites
*/
- public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception {
+ @Override
+ public boolean condition(SimulationContext context, TimeStep step, Metier metier) throws Exception {
return false;
}
/**
- * Si la condition est vrai alors cette action est executée avant le pas.
+ * Si la condition est vrai alors cette action est executee avant le pas
* de temps de la simulation.
- * @param context La simulation pour lequel on utilise cette regle
+ *
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void preAction(SimulationContext context, Date date, Metier metier) throws Exception {
+ @Override
+ public void preAction(SimulationContext context, TimeStep step, Metier metier) throws Exception {
// nothing
}
/**
- * Si la condition est vrai alors cette action est executée apres le pas.
+ * Si la condition est vrai alors cette action est executée apres le pas
* de temps de la simulation.
+ *
* @param context La simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void postAction(SimulationContext context, Date date, Metier metier) throws Exception {
+ @Override
+ public void postAction(SimulationContext context, TimeStep step, Metier metier) throws Exception {
// nothing
}
Modified: isis-fish/trunk/src/test/resources/test-database/rules/EffortReduction.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/rules/EffortReduction.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/rules/EffortReduction.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -22,142 +19,146 @@
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
-package rules;
-
-import static org.nuiton.i18n.I18n._;
-
-import java.util.List;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import scripts.SiMatrix;
-import fr.ifremer.isisfish.entities.Metier;
-import fr.ifremer.isisfish.entities.Strategy;
-import fr.ifremer.isisfish.rule.AbstractRule;
-import fr.ifremer.isisfish.simulator.SimulationContext;
-import fr.ifremer.isisfish.types.Date;
-import fr.ifremer.isisfish.util.Doc;
-
-/**
- * EffortReduction.java
- *
- * Created: 3 septembre 2008
- *
- * @author anonymous <anonymous at labs.libre-entreprise.org>
- * @version $Revision$
- */
-public class EffortReduction extends AbstractRule {
-
- /** to use log facility, just put in your code: log.info("..."); */
- static private Log log = LogFactory.getLog(EffortReduction.class);
-
- @Doc("Begin date")
- public Date param_beginDate = new Date(0);
- @Doc("End date")
- public Date param_endDate = new Date(59);
-
- @Doc("Pourcentage de reduction d effort applique.")
- public double param_PercentReduction = 0.5;
-
- boolean first = true;
-
- protected String[] necessaryResult = {};
-
- /**
- * @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 _("Reduce monthly effort of each strategy of the percent indicated");
- }
-
- /**
- * Appele au demarrage de la simulation, cette methode permet d'initialiser
- * des valeurs.
- * @param context 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 context 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 = true;
- if (date.before(param_beginDate)) {
- result = false;
- } else if (date.after(param_endDate)) {
- result = false;
- }
- if (result)
- System.out.println("condition vraie");
- return result;
- }
-
- /**
- * Si la condition est vrai alors cette action est executee avant le pas
- * de temps de la simulation.
- * @param context La simulation pour lequel on utilise cette regle
- */
- public void preAction(SimulationContext context, Date date, Metier metier)
- throws Exception {
- // shinte la boucle metier
- if (first) {
- first = false;
- SiMatrix siMatrix = SiMatrix.getSiMatrix(context);
- List<Strategy> strs = siMatrix.getStrategies(date);
- for (Strategy str : strs) {
- System.out.println("strategy evaluee : " + str.getName());
-
- /* Dans un premiere temps tant que l inactivit? est un entier on utilise
- * la proportion du nombre de bateaux de la strategie pour reduire l effort
- * ce qu on ferait aussi pour une mesure de reduction du nombre de bateaux mais
- * comme actuellement on ne tient pas compte de l economie... ca revient au meme
- * En fait passer par l inactivit? n est pas la meilleure facon de modifier
- * l effort le mieux serait d agir sur un autre coeff qui est multipli? a
- * l effort (Fstd ou ciblage) car comme ca le code serait generique mais on
- * ne verrait pas que l effort nominal est modifi?...
- */
-
- double propOld = str.getProportionSetOfVessels();
- double newProp = propOld * (1 - param_PercentReduction);
- str.setProportionSetOfVessels(newProp);
-
- /* int Inact = str.getStrategyMonthInfo(date.getMonth()).getMinInactivityDays();
- System.out.println("inactivity old = "+ Inact);
- int nbDays = date.getMonth().getNumbersOfDays();
- System.out.println("nbDays = "+nbDays);
- double newInact = nbDays-((nbDays-Inact)*(1-param_PercentReduction));
- System.out.println("newInact = "+newInact);
- int ni = (int) newInact ;
- System.out.println("ni = "+ ni);
- str.getStrategyMonthInfo(date.getMonth()).setMinInactivityDays(ni);
- System.out.println("setMinInactivityDays : " + str.getStrategyMonthInfo(date.getMonth()).getMinInactivityDays());
- */
- }
- }
- }
-
- /**
- * Si la condition est vrai alors cette action est executee apres le pas
- * de temps de la simulation.
- * @param context La simulation pour lequel on utilise cette regle
- */
- public void postAction(SimulationContext context, Date date, Metier metier)
- throws Exception {
- first = true;
- }
-
-}
+package rules;
+
+import static org.nuiton.i18n.I18n._;
+
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import scripts.SiMatrix;
+import fr.ifremer.isisfish.entities.Metier;
+import fr.ifremer.isisfish.entities.Strategy;
+import fr.ifremer.isisfish.rule.AbstractRule;
+import fr.ifremer.isisfish.simulator.SimulationContext;
+import fr.ifremer.isisfish.types.TimeStep;
+import fr.ifremer.isisfish.util.Doc;
+
+/**
+ * EffortReduction.java
+ *
+ * Created: 3 septembre 2008
+ *
+ * @author anonymous <anonymous at labs.libre-entreprise.org>
+ * @version $Revision$
+ */
+public class EffortReduction extends AbstractRule {
+
+ /** to use log facility, just put in your code: log.info("..."); */
+ static private Log log = LogFactory.getLog(EffortReduction.class);
+
+ @Doc("Begin step")
+ public TimeStep param_beginStep = new TimeStep(0);
+ @Doc("End step")
+ public TimeStep param_endStep = new TimeStep(59);
+
+ @Doc("Pourcentage de reduction d effort applique.")
+ public double param_PercentReduction = 0.5;
+
+ boolean first = true;
+
+ protected String[] necessaryResult = {};
+
+ /**
+ * @return the necessaryResult
+ */
+ @Override
+ 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
+ */
+ @Override
+ public String getDescription() {
+ return _("Reduce monthly effort of each strategy of the percent indicated");
+ }
+
+ /**
+ * Appele au demarrage de la simulation, cette methode permet d'initialiser
+ * des valeurs.
+ * @param context La simulation pour lequel on utilise cette regle
+ */
+ @Override
+ public void init(SimulationContext context) throws Exception {
+ }
+
+ /**
+ * La condition qui doit etre vrai pour faire les actions.
+ *
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
+ * @return vrai si on souhaite que les actions soit faites
+ */
+ @Override
+ public boolean condition(SimulationContext context, TimeStep step, Metier metier)
+ throws Exception {
+
+ boolean result = true;
+ if (step.before(param_beginStep)) {
+ result = false;
+ } else if (step.after(param_endStep)) {
+ result = false;
+ }
+ if (result) {
+ log.info("condition vraie");
+ }
+ return result;
+ }
+
+ /**
+ * Si la condition est vrai alors cette action est executee avant le pas
+ * de temps de la simulation.
+ *
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
+ */
+ @Override
+ public void preAction(SimulationContext context, TimeStep step, Metier metier)
+ throws Exception {
+ // shinte la boucle metier
+ if (first) {
+ first = false;
+ SiMatrix siMatrix = SiMatrix.getSiMatrix(context);
+ List<Strategy> strs = siMatrix.getStrategies(step);
+ for (Strategy str : strs) {
+ log.info("strategy evaluee : " + str.getName());
+
+ /* Dans un premiere temps tant que l inactivité est un entier on utilise
+ * la proportion du nombre de bateaux de la strategie pour reduire l effort
+ * ce qu on ferait aussi pour une mesure de reduction du nombre de bateaux mais
+ * comme actuellement on ne tient pas compte de l economie... ca revient au meme
+ * En fait passer par l inactivité n est pas la meilleure facon de modifier
+ * l effort le mieux serait d agir sur un autre coeff qui est multiplié a
+ * l effort (Fstd ou ciblage) car comme ca le code serait generique mais on
+ * ne verrait pas que l effort nominal est modifié...
+ */
+
+ double propOld = str.getProportionSetOfVessels();
+ double newProp = propOld * (1 - param_PercentReduction);
+ str.setProportionSetOfVessels(newProp);
+ }
+ }
+ }
+
+ /**
+ * Si la condition est vrai alors cette action est executée apres le pas
+ * de temps de la simulation.
+ *
+ * @param context La simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
+ */
+ @Override
+ public void postAction(SimulationContext context, TimeStep step, Metier metier)
+ throws Exception {
+ first = true;
+ }
+
+}
Modified: isis-fish/trunk/src/test/resources/test-database/rules/GraviteVPUE1.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/rules/GraviteVPUE1.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/rules/GraviteVPUE1.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -39,7 +36,7 @@
import org.nuiton.math.matrix.*;
import fr.ifremer.isisfish.simulator.SimulationContext;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.types.Month;
import fr.ifremer.isisfish.entities.*;
import fr.ifremer.isisfish.rule.AbstractRule;
@@ -79,6 +76,7 @@
};
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
@@ -87,6 +85,7 @@
* Permet d'afficher a l'utilisateur une aide sur la regle.
* @return L'aide ou la description de la regle
*/
+ @Override
public String getDescription() throws Exception {
return _("Calcule les proportion par métier chaque mois en fonction de la VPUE du métier l'année précédante");
/*"HYPOTHESES GRAVITE"
@@ -104,6 +103,7 @@
* function used to initialise MatrixND to NaN double
*/
private MapFunction nanFunction = new MapFunction() {
+ @Override
public double apply(double value) {
return Double.NaN;
}
@@ -114,11 +114,12 @@
* des valeurs
* @param context La simulation pour lequel on utilise cette regle
*/
+ @Override
public void init(SimulationContext context) throws Exception {
- Date date = new Date(0);
+ TimeStep step = new TimeStep(0);
- List<Strategy> strs = SiMatrix.getSiMatrix(context).getStrategies(date);
- List<Metier> metiers = SiMatrix.getSiMatrix(context).getMetiers(date);
+ List<Strategy> strs = SiMatrix.getSiMatrix(context).getStrategies(step);
+ List<Metier> metiers = SiMatrix.getSiMatrix(context).getMetiers(step);
List<Month> months = Arrays.asList(Month.MONTH);
SommePropInitial = MatrixFactory.getInstance().create(
@@ -133,7 +134,7 @@
for (Strategy str : strs) {
List<Metier> strMetiers = SiMatrix.getSiMatrix(context).getMetiers(
- str, date);
+ str, step);
List<StrategyMonthInfo> infos = str.getStrategyMonthInfo();
for (StrategyMonthInfo info : infos) {
double somme = 0;
@@ -149,36 +150,43 @@
}
/**
- * La condition qui doit etre vrai pour faire les actions
- * @param context La simulation pour lequel on utilise cette regle
+ * La condition qui doit etre vrai pour faire les actions.
+ *
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
* @return vrai si on souhaite que les actions soit faites
*/
- public boolean condition(SimulationContext context, Date date, Metier metier)
+ @Override
+ public boolean condition(SimulationContext context, TimeStep step, Metier metier)
throws Exception {
// Il faut etre au moins au deuxieme pas de temps.
- return date.getYear() > 0;
+ return step.getYear() > 0;
}
// Booleen permettant que ne boucler que sur un seul metier dans la preaction :
boolean first = true;
/**
- * Si la condition est vrai alors cette action est executée avant le pas
+ * Si la condition est vrai alors cette action est executee avant le pas
* de temps de la simulation.
- * @param context La simulation pour lequel on utilise cette regle
+ *
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void preAction(SimulationContext context, Date date, Metier metier)
+ @Override
+ public void preAction(SimulationContext context, TimeStep step, Metier metier)
throws Exception {
if (log.isDebugEnabled()) {
- log.debug("first = " + first + "date:" + date);
+ log.debug("first = " + first + "step:" + step);
}
- System.out.println("first = " + first
- + " ,on passe dans la preaction ?");
+ //log.info("first = " + first + " ,on passe dans la preaction ?");
if (first) { // on passe dans preaction pour la premiere fois
- System.out.println("Oui, preaction : ");
+ //log.info("Oui, preaction : ");
List<Strategy> strs = SiMatrix.getSiMatrix(context).getStrategies(
- date);
+ step);
//List<Population> populations = SiMatrix.getSiMatrix(context)
// .getPopulations(date);
ResultStorage resultmanager = context.getSimulationStorage()
@@ -188,19 +196,17 @@
//Calcul de l effort nominal par strategy met
MatrixND EffortNominalPerStrMet = null;
- EffortNominalPerStrMet = resultmanager.getMatrix(date
- .previousYear(),
+ EffortNominalPerStrMet = resultmanager.getMatrix(step.previousYear(),
ResultName.MATRIX_EFFORT_NOMINAL_PER_STRATEGY_MET);
- System.out.println("EffortNominalPerStrMet calculee "
- + EffortNominalPerStrMet);
+ //System.out.println("EffortNominalPerStrMet calculee "
+ // + EffortNominalPerStrMet);
//on commence par creer une matrice de valeurs (somme sur ttes les especes capturees) par strategie met
MatrixND GrossValuePerStrMet = null;
- GrossValuePerStrMet = resultmanager.getMatrix(date.previousYear(),
+ GrossValuePerStrMet = resultmanager.getMatrix(step.previousYear(),
ResultName.MATRIX_GROSS_VALUE_OF_LANDINGS_PER_STRATEGY_MET);
- System.out.println("GrossValuePerStrMet calculee "
- + GrossValuePerStrMet);
+ //System.out.println("GrossValuePerStrMet calculee " + GrossValuePerStrMet);
//ajouter pour tous les métiers les valeurs liées qux autres espèces calculées par modele lineaire
@@ -208,12 +214,9 @@
valuePerUnitOfEffort.map(nanFunction); //réinitialisation avant calcul pour date
for (Strategy str : strs) {
- System.out
- .println("INFO: Boucle creation valuePerUnitEffort : "
- + str.getName());
- // log.info("Boucle creation catchperuniteffort : "+ str.getName());
- StrategyMonthInfo smi = str.getStrategyMonthInfo(date
- .getMonth());
+ //log.info("INFO: Boucle creation valuePerUnitEffort : " + str.getName());
+ // log.info("Boucle creation catchperuniteffort : "+ str.getName());
+ StrategyMonthInfo smi = str.getStrategyMonthInfo(step.getMonth());
Collection<EffortDescription> strMet = str.getSetOfVessels()
.getPossibleMetiers();
//SiMatrix.getSiMatrix(context).getMetiers(str, date);
@@ -223,8 +226,8 @@
double somme = 0;//initialisation de la somme des VPUE des metiers de la strategie
for (EffortDescription ed : strMet) {
Metier strMetier = ed.getPossibleMetiers();
- System.out.println("Pour str=" + str.getName()
- + " et metier=" + strMetier.getName());
+ //log.info("Pour str=" + str.getName()
+ // + " et metier=" + strMetier.getName());
double effort = EffortNominalPerStrMet.getValue(str,
strMetier);
// on teste effort pour le calcul des VPUE
@@ -236,55 +239,54 @@
//on recupere la capture tot
double value = GrossValuePerStrMet.getValue(str,
strMetier);
- System.out.println("DEBUG: value : " + value);
- System.out.println("DEBUG: effort : " + effort);
+ //log.debug("DEBUG: value : " + value);
+ //log.debug("DEBUG: effort : " + effort);
double vpue = value / effort;
valuePerUnitOfEffort.setValue(str, strMetier, vpue);
- System.out.println("value/effort= " + vpue);
+ //log.info("value/effort= " + vpue);
somme += value / effort;
} else if ((effort == 0)
& (smi.getProportionMetier(strMetier) == 0)) {// n'a jamais pêche avec ce metier
valuePerUnitOfEffort.setValue(str, strMetier, 0);
- System.out.println("n'a jamais pêche avec ce metier");
+ //log.info("n'a jamais pêche avec ce metier");
} else {// n'a pas peche au mois, annee -1, mais avait une prop d'effort non nul a l'annee=0
testCondition = true;// ie somme est incomplète mais pas grave car on mettra PropInitiale à tous les metiers
- System.out.println("n'a pas peche au mois, annee -1, mais avait une prop d'effort non nul a l'annee=0");
+ //log.info("n'a pas peche au mois, annee -1, mais avait une prop d'effort non nul a l'annee=0");
}
}
- System.out.println("testCondition pour str" + str.getName()
- + ":" + testCondition);
+ //log.info("testCondition pour str" + str.getName()
+ // + ":" + testCondition);
// A partir des VPUE stockees dans valuePerUnitOfEffort, on calcule la gravité
double newProp = 0;
- System.out
- .println("A partir des VPUE stockees dans valuePerUnitOfEffort, on calcule la gravité");
+ //log.info("A partir des VPUE stockees dans valuePerUnitOfEffort, on calcule la gravité");
if (!testCondition) {
double SommeVPUEstrat = somme;
- System.out.println("SommeVPUEstrat=" + SommeVPUEstrat);
+ //System.out.println("SommeVPUEstrat=" + SommeVPUEstrat);
for (EffortDescription ed : strMet) {
Metier strMetier = ed.getPossibleMetiers();
- System.out.println("PropStrInitiale(metier="
- + strMetier.getName() + ")"
- + smi.getProportionMetier(strMetier));
- System.out.println("SommePropInitial.getValue(str, date.getMonth()="
- + SommePropInitial.getValue(str, date
- .getMonth()));
- System.out.println("valuePerUnitOfEffort.getValue(str, strMetier)"
- + valuePerUnitOfEffort.getValue(str,
- strMetier));
+ //System.out.println("PropStrInitiale(metier="
+ // + strMetier.getName() + ")"
+ // + smi.getProportionMetier(strMetier));
+ //System.out.println("SommePropInitial.getValue(str, date.getMonth()="
+ // + SommePropInitial.getValue(str, date
+ // .getMonth()));
+ //System.out.println("valuePerUnitOfEffort.getValue(str, strMetier)"
+ // + valuePerUnitOfEffort.getValue(str,
+ // strMetier));
if (SommeVPUEstrat == 0) {
newProp = 0;
} else {
- newProp = SommePropInitial.getValue(str, date
+ newProp = SommePropInitial.getValue(str, step
.getMonth())
* valuePerUnitOfEffort.getValue(str,
strMetier) / SommeVPUEstrat;
}
- System.out.println("newProp(metier="
- + strMetier.getName() + ")" + newProp);
+ //System.out.println("newProp(metier="
+ // + strMetier.getName() + ")" + newProp);
smi.setProportionMetier(strMetier, newProp);
- System.out.println("PropStrNouvelle(metier="
- + strMetier.getName() + ")"
- + smi.getProportionMetier(strMetier));
+ //System.out.println("PropStrNouvelle(metier="
+ // + strMetier.getName() + ")"
+ // + smi.getProportionMetier(strMetier));
}
}
// else ie on met propInitiale dans PropStr(str,annee,mois)
@@ -306,9 +308,13 @@
/**
* Si la condition est vrai alors cette action est executée apres le pas
* de temps de la simulation.
+ *
* @param context La simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void postAction(SimulationContext context, Date date, Metier metier)
+ @Override
+ public void postAction(SimulationContext context, TimeStep step, Metier metier)
throws Exception {
first = true;
}
Modified: isis-fish/trunk/src/test/resources/test-database/rules/InterdictionEngin.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/rules/InterdictionEngin.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/rules/InterdictionEngin.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -40,7 +37,7 @@
import fr.ifremer.isisfish.simulator.MetierMonitor;
import fr.ifremer.isisfish.simulator.SimulationContext;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.types.Month;
import fr.ifremer.isisfish.entities.*;
import fr.ifremer.isisfish.rule.AbstractRule;
@@ -66,9 +63,9 @@
@Doc(value="Prohibited gear")
public Gear param_gear = null;
@Doc(value="Begin date")
- public Date param_beginDate = new Date(0);
+ public TimeStep param_beginStep = new TimeStep(0);
@Doc(value="End date")
- public Date param_endDate = new Date(119);
+ public TimeStep param_endStep = new TimeStep(119);
@Doc(value="Begin month")
public Month param_beginMonth = Month.JANUARY;
@Doc(value="do the doc of param endMonth")
@@ -81,6 +78,7 @@
// ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET,
};
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
@@ -89,6 +87,7 @@
* Permet d'afficher a l'utilisateur une aide sur la regle.
* @return L'aide ou la description de la regle
*/
+ @Override
public String getDescription() throws Exception {
// interdiction des metiers utilisant cet engin
return _("Prohibited gear");
@@ -99,28 +98,33 @@
* des valeurs
* @param context La simulation pour lequel on utilise cette regle
*/
+ @Override
public void init(SimulationContext context) throws Exception {
// nothing
}
/**
- * La condition qui doit etre vrai pour faire les actions
- * @param context La simulation pour lequel on utilise cette regle
+ * La condition qui doit etre vrai pour faire les actions.
+ *
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
* @return vrai si on souhaite que les actions soit faites
*/
- public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception {
+ @Override
+ public boolean condition(SimulationContext context, TimeStep step, Metier metier) throws Exception {
log.info("condition fermeture zone");
boolean result = true;
- Month mois = date.getMonth();
+ Month mois = step.getMonth();
log.info("mois:" + mois);
- if(!(param_beginMonth.getMonthNumber()<=mois.getMonthNumber()
- && mois.getMonthNumber()<=param_endMonth.getMonthNumber())) {
+ 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)) {
+ if (step.before(param_beginStep)) {
result = false;
- } else if(date.after(param_endDate)) {
+ } else if (step.after(param_endStep)) {
result = false;
} else if (!metier.getGear().equals(param_gear)) {
result = false;
@@ -129,34 +133,18 @@
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
+ * Si la condition est vrai alors cette action est executee avant le pas
* de temps de la simulation.
- * @param context La simulation pour lequel on utilise cette regle
+ *
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void preAction(SimulationContext context, Date date, Metier metier) throws Exception {
+ @Override
+ public void preAction(SimulationContext context, TimeStep step, Metier metier) throws Exception {
log.info("le metier vise par l'interdiction : " + metier);
MetierMonitor metierMon = context.getMetierMonitor();
@@ -164,18 +152,18 @@
// 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> strs = siMatrix.getStrategies(step);
List<Strategy> ListeStrat = new ArrayList<Strategy>();
for (Strategy str : strs) {
- double prop = str.getStrategyMonthInfo(date.getMonth()).getProportionMetier(metier);
+ double prop = str.getStrategyMonthInfo(step.getMonth()).getProportionMetier(metier);
if (prop != 0) {
ListeStrat.add(str);
}
}
for (Strategy Strat : ListeStrat) {
- StrategyMonthInfo StratMonthInfo = Strat.getStrategyMonthInfo(date.getMonth());
+ StrategyMonthInfo StratMonthInfo = Strat.getStrategyMonthInfo(step.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
@@ -184,12 +172,12 @@
// 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();) {
+ 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())){
+ || metierMon.isForbidden(metier, step.getMonth())){
effort.remove();
}
}
@@ -209,91 +197,29 @@
}
// s'il n'y a pas de metier alternatif, on passe a nonActivite
else {
- MatrixND matNonActivite = metierMon.getOrCreateNoActivity(date,
+ MatrixND matNonActivite = metierMon.getOrCreateNoActivity(step,
ResultName.MATRIX_NO_ACTIVITY,
- siMatrix.getStrategies(date),
- siMatrix.getMetiers(date));
- matNonActivite.setValue(Strat, metier, StratMonthInfo.getProportionMetier(metier));
+ siMatrix.getStrategies(step),
+ siMatrix.getMetiers(step));
+ 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.nuiton.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 context La simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void postAction(SimulationContext context, Date date, Metier metier) throws Exception {
+ @Override
+ public void postAction(SimulationContext context, TimeStep step, Metier metier) throws Exception {
// nothing
}
Modified: isis-fish/trunk/src/test/resources/test-database/rules/InterdictionEnginPreSimu.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/rules/InterdictionEnginPreSimu.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/rules/InterdictionEnginPreSimu.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -42,7 +39,7 @@
import fr.ifremer.isisfish.simulator.MetierMonitor;
import fr.ifremer.isisfish.simulator.SimulationContext;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.types.Month;
import fr.ifremer.isisfish.entities.*;
import fr.ifremer.isisfish.rule.AbstractRule;
@@ -83,6 +80,7 @@
// ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET,
};
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
@@ -91,6 +89,7 @@
* Permet d'afficher a l'utilisateur une aide sur la regle.
* @return L'aide ou la description de la regle
*/
+ @Override
public String getDescription() throws Exception {
return _("Prohibited gear");
}
@@ -100,6 +99,7 @@
* des valeurs
* @param context La simulation pour lequel on utilise cette regle
*/
+ @Override
public void init(SimulationContext context) throws Exception {
MetierMonitor metierMon = context.getMetierMonitor();
@@ -175,148 +175,64 @@
}
// 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 context La simulation pour lequel on utilise cette regle
+ * La condition qui doit etre vrai pour faire les actions.
+ *
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
* @return vrai si on souhaite que les actions soit faites
*/
- public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception {
+ @Override
+ public boolean condition(SimulationContext context, TimeStep step, Metier metier) throws Exception {
boolean result = false;
- MatrixND mat = tableNonActivite.get(date.getMonth());
+ MatrixND mat = tableNonActivite.get(step.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
+ * Si la condition est vrai alors cette action est executee avant le pas
* de temps de la simulation.
- * @param context La simulation pour lequel on utilise cette regle
+ *
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void preAction(SimulationContext context, Date date, Metier metier) throws Exception {
+ @Override
+ public void preAction(SimulationContext context, TimeStep step, 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());
+ MatrixND mat = tableNonActivite.get(step.getMonth());
MetierMonitor metierMon = context.getMetierMonitor();
- MatrixND noActivity = metierMon.getNoActivity(date);
+ MatrixND noActivity = metierMon.getNoActivity(step);
if (noActivity == null) {
- metierMon.setNoActivity(date, mat.copy());
+ metierMon.setNoActivity(step, 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 context La simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void postAction(SimulationContext context, Date date, Metier metier) throws Exception {
+ @Override
+ public void postAction(SimulationContext context, TimeStep step, Metier metier) throws Exception {
affectNonActivite = false;
-
- /*
- p.affectNonActivite=false;
-return p.gestionMetier;
- */
}
}
Modified: isis-fish/trunk/src/test/resources/test-database/rules/TACpoids.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/rules/TACpoids.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/rules/TACpoids.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -49,7 +46,7 @@
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.TimeStep;
import fr.ifremer.isisfish.types.Month;
import fr.ifremer.isisfish.util.Doc;
@@ -78,9 +75,9 @@
@Doc("Affected species")
public Species param_species = null;
@Doc("Debin date")
- public Date param_beginDate = new Date(0);
+ public TimeStep param_beginStep = new TimeStep(0);
@Doc("End date")
- public Date param_endDate = new Date(90);
+ public TimeStep param_endStep = new TimeStep(90);
@Doc("Proportion de survie")
public double param_propSurvie = 0;
@Doc("Proportionnal TAC")
@@ -102,6 +99,7 @@
/**
* @return the necessaryResult
*/
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
@@ -111,6 +109,7 @@
*
* @return L'aide ou la description de la regle
*/
+ @Override
public String getDescription() {
return _("TAC weight in tons.\nIf you want survival discard use propSurvie other than 0.\nIf you wish TAC computed as a proportion of the biomass use propTac other than 0.");
}
@@ -121,16 +120,20 @@
*
* @param context La simulation pour lequel on utilise cette regle
*/
+ @Override
public void init(SimulationContext context) throws Exception {
}
/**
- * La condition qui doit etre vrai pour faire les actions
+ * La condition qui doit etre vrai pour faire les actions.
*
- * @param context La simulation pour lequel on utilise cette regle
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
* @return vrai si on souhaite que les actions soit faites
*/
- public boolean condition(SimulationContext context, Date date, Metier metier)
+ @Override
+ public boolean condition(SimulationContext context, TimeStep step, Metier metier)
throws Exception {
log.info("test si TAC atteint");
@@ -139,22 +142,22 @@
param_species.getTopiaId());
// on fait le calcul du tac si necessaire
- if (param_propTac > 0 && date.getMonth().equals(Month.JANUARY)) {
+ if (param_propTac > 0 && step.getMonth().equals(Month.JANUARY)) {
PopulationMonitor popMon = context.getPopulationMonitor();
param_tacInTons = popMon.getBiomass(param_species) * param_propTac;
}
boolean result = false;
- if (date.before(param_beginDate)) {
+ if (step.before(param_beginStep)) {
result = false;
- } else if (date.after(param_endDate)) {
+ } else if (step.after(param_endStep)) {
result = false;
} else {
- TargetSpecies ts = metier.getMetierSeasonInfo(date.getMonth())
+ TargetSpecies ts = metier.getMetierSeasonInfo(step.getMonth())
.getSpeciesTargetSpecies(param_species);
if (ts != null) {
double catchTons = RuleUtil.getTotalCatchTons(context,
- param_species, date);
+ param_species, step);
log.info("[TAC] catchTons = " + catchTons
+ " >= param_tacInTons:" + param_tacInTons);
if (catchTons >= param_tacInTons) {
@@ -166,34 +169,33 @@
}
/**
- * Si la condition est vrai alors cette action est executee avant le pas de
- * temps de la simulation.
+ * Si la condition est vrai alors cette action est executee avant le pas
+ * de temps de la simulation.
*
- * @param context La simulation pour lequel on utilise cette regle
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void preAction(SimulationContext context, Date date, Metier metier)
+ @Override
+ public void preAction(SimulationContext context, TimeStep step, Metier metier)
throws Exception {
affectation = false;
log.info("[TAC] preAction for: " + metier);
log.info(" TAC atteint [TAC] preAction for: " + metier);
- TargetSpecies ts = metier.getMetierSeasonInfo(date.getMonth())
+ TargetSpecies ts = metier.getMetierSeasonInfo(step.getMonth())
.getSpeciesTargetSpecies(param_species);
if (ts != null && ts.getPrimaryCatch()) {
// recupere tous les metiers qui ont l'espece en capture principale =>metiers vises
// aimedMetiers ne fonctionne pas je ne sais pas pourquoi ! mais au final forbiddenMetier aura le meme effet
- /*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);
//recupere toutes les strategies pratiquant le metier 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())
+ for (Strategy str : siMatrix.getStrategies(step)) {
+ double prop = str.getStrategyMonthInfo(step.getMonth())
.getProportionMetier(metier);
if (prop != 0) {
strs.add(str);
@@ -201,7 +203,7 @@
}
for (Strategy str : strs) {
- StrategyMonthInfo smi = str.getStrategyMonthInfo(date
+ StrategyMonthInfo smi = str.getStrategyMonthInfo(step
.getMonth());
// 1er cas de figure: l'effort est reporte sur un metier de la
@@ -274,10 +276,10 @@
// sinon on met tout dans le metier nonActivite
MetierMonitor metierMon = context.getMetierMonitor();
- MatrixND mat = metierMon.getOrCreateNoActivity(date,
+ MatrixND mat = metierMon.getOrCreateNoActivity(step,
ResultName.MATRIX_NO_ACTIVITY, siMatrix
- .getStrategies(date), siMatrix
- .getMetiers(date));
+ .getStrategies(step), siMatrix
+ .getMetiers(step));
mat.setValue(str, metier, smi.getProportionMetier(metier));
smi.getProportionMetier().setValue(metier, 0);
@@ -287,17 +289,20 @@
}
/**
- * Si la condition est vrai alors cette action est executee apres le pas de
- * temps de la simulation.
+ * Si la condition est vrai alors cette action est executée apres le pas
+ * de temps de la simulation.
*
* @param context La simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void postAction(SimulationContext context, Date date, Metier metier)
+ @Override
+ public void postAction(SimulationContext context, TimeStep step, Metier metier)
throws Exception {
ResultStorage resultmanager = context.getSimulationStorage()
.getResultStorage();
log.info("[TAC] postAction for: " + metier);
- TargetSpecies ts = metier.getMetierSeasonInfo(date.getMonth())
+ TargetSpecies ts = metier.getMetierSeasonInfo(step.getMonth())
.getSpeciesTargetSpecies(param_species);
if (ts != null) {
if (!affectation) {
@@ -320,7 +325,7 @@
// 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);
+ MatrixND discard = popMon.getDiscard(step, pop);
log.info("discard : " + discard);
if (discard != null) {
discard.mults(0);
@@ -329,11 +334,11 @@
discard = popMon.getCatch(pop).copy();
// ca ne doit pas pouvoir marcher car MATRIX_DISCARDS_PER_STR_MET est de dimension pop groupe str met - et discard n'a plus la dimension pop
discard.setName(ResultName.MATRIX_DISCARDS_PER_STR_MET_PER_ZONE_POP);
- popMon.addDiscard(date, pop, discard);
+ popMon.addDiscard(step, pop, discard);
log.info("[TAC] add discard for " + pop + ": "
+ discard);
// ne manquerait-il pas
- resultmanager.addResult(date, pop, discard);
+ resultmanager.addResult(step, pop, discard);
if (param_propSurvie > 0) {
MatrixND eff = popMon.getN(pop);
//on réajoute les survivants aux effectifs
Modified: isis-fish/trunk/src/test/resources/test-database/rules/TailleMin.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/rules/TailleMin.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/rules/TailleMin.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -44,7 +41,7 @@
import fr.ifremer.isisfish.rule.AbstractRule;
import fr.ifremer.isisfish.simulator.PopulationMonitor;
import fr.ifremer.isisfish.simulator.SimulationContext;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.util.Doc;
/**
@@ -63,17 +60,21 @@
/** to use log facility, just put in your code: log.info("..."); */
static private Log log = LogFactory.getLog(TailleMin.class);
- @Doc(value = "Begin date")
- public Date param_beginDate = new Date(0);
+ @Doc(value = "Begin step")
+ public TimeStep param_beginStep = new TimeStep(0);
+
@Doc(value = "End date")
- public Date param_endDate = new Date(119);
+ public TimeStep param_endStep = new TimeStep(119);
+
@Doc(value = "Affected species")
public Species param_species = null;
+
@Doc(value = "Taille minimale")
public double param_TailleMin = 27;
+
@Doc(value = "Proportion de survie")
public double param_propSurvie = 0;
-
+
public String[] necessaryResult = {
// put here all necessary result for this rule
// example:
@@ -81,6 +82,7 @@
// ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET,
};
+ @Override
public String[] getNecessaryResult() {
return this.necessaryResult;
}
@@ -90,8 +92,11 @@
*
* @return L'aide ou la description de la regle
*/
+ @Override
public String getDescription() throws Exception {
- return _("");
+ return _("Tous les poissons dont la taille est inférieure à TailleMin" +
+ " ne seront pas capturés. Ils sont placés en rejets et rejetés" +
+ " suivant la proportion de survie.");
}
/**
@@ -100,6 +105,7 @@
*
* @param context La simulation pour lequel on utilise cette regle
*/
+ @Override
public void init(SimulationContext context) throws Exception {
}
@@ -110,81 +116,76 @@
* @param metier
* @return
*/
- private boolean isCaptureDate(Date date, Species species, Metier metier) {
- MetierSeasonInfo info = metier.getMetierSeasonInfo(date.getMonth());
+ private boolean isCaptureDate(TimeStep step, Species species, Metier metier) {
+ MetierSeasonInfo info = metier.getMetierSeasonInfo(step.getMonth());
TargetSpecies target = info.getSpeciesTargetSpecies(species);
- boolean result = target != null;
+ boolean result;
+ if (target != null) {
+ result = true;
+ } else {
+ result = false;
+ }
+
return result;
}
/**
- * La condition qui doit etre vrai pour faire les actions
+ * La condition qui doit etre vrai pour faire les actions.
*
- * @param context La simulation pour lequel on utilise cette regle
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
* @return vrai si on souhaite que les actions soit faites
*/
- public boolean condition(SimulationContext context, Date date, Metier metier)
+ @Override
+ public boolean condition(SimulationContext context, TimeStep step, Metier metier)
throws Exception {
log.info("Recherche si la taille Minimale s'applique");
boolean result = true;
- if (date.before(param_beginDate)) {
+ if (step.before(param_beginStep)) {
result = false;
- } else if (date.after(param_endDate)) {
+ } else if (step.after(param_endStep)) {
result = false;
- } else if (isCaptureDate(date, param_species, metier) != true) {
+ } else if (isCaptureDate(step, 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.
+ * Si la condition est vrai alors cette action est executee avant le pas
+ * de temps de la simulation.
*
- * @param context La simulation pour lequel on utilise cette regle
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void preAction(SimulationContext context, Date date, Metier metier)
+ @Override
+ public void preAction(SimulationContext context, TimeStep step, Metier metier)
throws Exception {
// nothing
}
/**
- * Si la condition est vrai alors cette action est executée apres le pas de
- * temps de la simulation.
+ * Si la condition est vrai alors cette action est executée apres le pas
+ * de temps de la simulation.
*
* @param context La simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void postAction(SimulationContext context, Date date, Metier metier)
+ @Override
+ public void postAction(SimulationContext context, TimeStep step, Metier metier)
throws Exception {
- log.info("*$*$*$* TailleMin.actionApres:" + date + " metapop:"
- + param_species + " metier:" + metier);
+ log.info("*$*$*$* TailleMin.actionApres:" + step + " metapop:" +
+ param_species + " metier:" + metier);
- if (isCaptureDate(date, param_species, metier)) {
- log
- .info("*$*$*$* ok affecte capture infÃ?rieure Ã? TailleMin au rejet");
+ if (isCaptureDate(step, 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
@@ -197,29 +198,30 @@
PopulationMonitor popMon = context.getPopulationMonitor();
SiMatrix siMatrix = SiMatrix.getSiMatrix(context);
- List<Population> pops = siMatrix.getPopulations(date);
+ List<Population> pops = siMatrix.getPopulations(step);
for (Population pop : pops) {
if (pop.getSpecies().equals(param_species)) {
- if (popMon.getDiscard(date, pop) == null) {
+ if (popMon.getDiscard(step, 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];
+ 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);
+ coordonnees[3]) + i.getValue() *
+ param_propSurvie);
}
}
- discard.setName(ResultName.MATRIX_DISCARDS_PER_STR_MET_PER_ZONE_POP);
- popMon.addDiscard(date, pop, discard);
+ discard.setName(
+ ResultName.MATRIX_DISCARDS_PER_STR_MET_PER_ZONE_POP);
+ popMon.addDiscard(step, pop, discard);
}
}
}
@@ -228,64 +230,5 @@
//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;
- */
}
-
}
Modified: isis-fish/trunk/src/test/resources/test-database/rules/TotalClosure.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/rules/TotalClosure.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/rules/TotalClosure.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -22,122 +19,134 @@
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
-package rules;
-
-import static org.nuiton.i18n.I18n._;
-
-import java.util.List;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.math.matrix.MatrixND;
-
-import scripts.ResultName;
-import scripts.SiMatrix;
-import fr.ifremer.isisfish.entities.Metier;
-import fr.ifremer.isisfish.entities.Strategy;
-import fr.ifremer.isisfish.entities.StrategyMonthInfo;
-import fr.ifremer.isisfish.rule.AbstractRule;
-import fr.ifremer.isisfish.simulator.MetierMonitor;
-import fr.ifremer.isisfish.simulator.SimulationContext;
-import fr.ifremer.isisfish.types.Date;
-import fr.ifremer.isisfish.types.Month;
-
-/**
- * Remplace aussi Cantonnement Engin.
- *
- * Created: 29 aout 2007
- * @author sigrid
- * @version $Revision$
- */
-public class TotalClosure extends AbstractRule {
-
- /** to use log facility, just put in your code: log.info("..."); */
- static private Log log = LogFactory.getLog(TotalClosure.class);
-
- public Date param_beginDate = new Date(100);
- public Date param_endDate = new Date(119);
- public Month param_beginMonth = Month.JANUARY;
- public Month param_endMonth = Month.JANUARY;
-
- public String[] necessaryResult = {
- ResultName.MATRIX_NO_ACTIVITY
- };
-
- public String[] getNecessaryResult() {
- return this.necessaryResult;
- }
-
- public String getDescription() throws Exception {
- return _("Total closure of the fishery");
- }
-
- /**
- * Appelé au démarrage de la simulation, cette methode permet d'initialiser des valeurs.
- * @param context 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 context 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 = true;
- if (date.before(param_beginDate)) {
- result = false;
- } else if (date.after(param_endDate)) {
- result = false;
- }
-
- if (date.getMonth().before(param_beginMonth)) {
- result = false;
- } else if (date.getMonth().after(param_endMonth)) {
- result = false;
- }
- return result;
- }
-
- /**
- * Si la condition est vrai alors cette action est executee avant le pas
- * de temps de la simulation.
- * @param context 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());
-
- 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);
- }
- }
- }
-
- /**
- * Si la condition est vrai alors cette action est executee apres le pas
- * de temps de la simulation.
- * @param context La simulation pour lequel on utilise cette regle
- */
- public void postAction(SimulationContext context, Date date, Metier metier)
- throws Exception {
- // nothing
- }
-
-}
+package rules;
+
+import static org.nuiton.i18n.I18n._;
+
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.math.matrix.MatrixND;
+
+import scripts.ResultName;
+import scripts.SiMatrix;
+import fr.ifremer.isisfish.entities.Metier;
+import fr.ifremer.isisfish.entities.Strategy;
+import fr.ifremer.isisfish.entities.StrategyMonthInfo;
+import fr.ifremer.isisfish.rule.AbstractRule;
+import fr.ifremer.isisfish.simulator.MetierMonitor;
+import fr.ifremer.isisfish.simulator.SimulationContext;
+import fr.ifremer.isisfish.types.TimeStep;
+import fr.ifremer.isisfish.types.Month;
+
+/**
+ * Remplace aussi Cantonnement Engin.
+ *
+ * Created: 29 aout 2007
+ * @author sigrid
+ * @version $Revision$
+ */
+public class TotalClosure extends AbstractRule {
+
+ /** to use log facility, just put in your code: log.info("..."); */
+ static private Log log = LogFactory.getLog(TotalClosure.class);
+
+ public TimeStep param_beginStep = new TimeStep(100);
+ public TimeStep param_endStep = new TimeStep(119);
+ public Month param_beginMonth = Month.JANUARY;
+ public Month param_endMonth = Month.JANUARY;
+
+ public String[] necessaryResult = {
+ ResultName.MATRIX_NO_ACTIVITY
+ };
+
+ @Override
+ public String[] getNecessaryResult() {
+ return this.necessaryResult;
+ }
+
+ @Override
+ public String getDescription() throws Exception {
+ return _("Total closure of the fishery");
+ }
+
+ /**
+ * Appelé au démarrage de la simulation, cette methode permet d'initialiser des valeurs.
+ * @param context La simulation pour lequel on utilise cette regle
+ */
+ @Override
+ public void init(SimulationContext context) throws Exception {
+ }
+
+ /**
+ * La condition qui doit etre vrai pour faire les actions.
+ *
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
+ * @return vrai si on souhaite que les actions soit faites
+ */
+ @Override
+ public boolean condition(SimulationContext context, TimeStep step, Metier metier)
+ throws Exception {
+ boolean result = true;
+ if (step.before(param_beginStep)) {
+ result = false;
+ } else if (step.after(param_endStep)) {
+ result = false;
+ }
+
+ if (step.getMonth().before(param_beginMonth)) {
+ result = false;
+ } else if (step.getMonth().after(param_endMonth)) {
+ result = false;
+ }
+ return result;
+ }
+
+ /**
+ * Si la condition est vrai alors cette action est executee avant le pas
+ * de temps de la simulation.
+ *
+ * @param context la simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
+ */
+ @Override
+ public void preAction(SimulationContext context, TimeStep step, Metier metier)
+ throws Exception {
+ MetierMonitor metierMon = context.getMetierMonitor();
+
+ SiMatrix siMatrix = SiMatrix.getSiMatrix(context);
+ MatrixND noActivity = metierMon.getOrCreateNoActivity(step,
+ ResultName.MATRIX_NO_ACTIVITY, siMatrix.getStrategies(step),
+ siMatrix.getMetiers(step));
+ metierMon.addforbiddenMetier(metier);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+
+ for (Strategy str : strategies) {
+ StrategyMonthInfo info = str.getStrategyMonthInfo(step.getMonth());
+ double prop = info.getProportionMetier(metier);
+ if (prop != 0) {
+ noActivity.setValue(str, metier, prop);
+ info.setProportionMetier(metier, 0);
+ }
+ }
+ }
+
+ /**
+ * Si la condition est vrai alors cette action est executée apres le pas
+ * de temps de la simulation.
+ *
+ * @param context La simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
+ */
+ @Override
+ public void postAction(SimulationContext context, TimeStep step, Metier metier)
+ throws Exception {
+ // nothing
+ }
+
+}
Modified: isis-fish/trunk/src/test/resources/test-database/scripts/GravityModel.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/scripts/GravityModel.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/scripts/GravityModel.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 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
@@ -47,7 +44,7 @@
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.TimeStep;
import fr.ifremer.isisfish.types.Month;
import fr.ifremer.isisfish.types.TimeUnit;
@@ -107,10 +104,10 @@
// MatrixFishingTimePerMonthPerVessel
//////////////////////////////////////////////////////////////////////
- public MatrixND matrixFishingTimePerMonthPerVessel(Date date)
+ public MatrixND matrixFishingTimePerMonthPerVessel(TimeStep step)
throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
- List<Metier> metiers = siMatrix.getMetiers(date);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+ List<Metier> metiers = siMatrix.getMetiers(step);
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_FISHING_TIME_PER_MONTH_PER_VESSEL,
@@ -119,10 +116,10 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = siMatrix.getMetiers(str, date);
+ metiers = siMatrix.getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
- double value = fishingTimePerMonthPerVessel(str, metier, date);
+ double value = fishingTimePerMonthPerVessel(str, metier, step);
result.setValue(str, metier, value);
}
}
@@ -137,13 +134,13 @@
*
* @param str
* @param metier
- * @param date
+ * @param step
* @return
*/
private double fishingTimePerMonthPerVessel(Strategy str, Metier metier,
- Date date) {
- Month month = date.getMonth();
- double timePerTrip = siMatrix.fishingTimePerTrip(str, metier, date);
+ TimeStep step) {
+ Month month = step.getMonth();
+ double timePerTrip = siMatrix.fishingTimePerTrip(str, metier, step);
double nbTrip = str.getStrategyMonthInfo(month).getNumberOfTrips();
return timePerTrip * nbTrip;
}
@@ -152,10 +149,10 @@
// matrixFuelCostsOfTravelPerVessel
//////////////////////////////////////////////////////////////////////
- public MatrixND matrixFuelCostsOfTravelPerVessel(Date date)
+ public MatrixND matrixFuelCostsOfTravelPerVessel(TimeStep step)
throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
- List<Metier> metiers = siMatrix.getMetiers(date);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+ List<Metier> metiers = siMatrix.getMetiers(step);
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_FUEL_COSTS_OF_TRAVEL_PER_VESSEL,
@@ -164,10 +161,10 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = siMatrix.getMetiers(str, date);
+ metiers = siMatrix.getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
- double value = fuelCostsOfTravelPerVessel(str, metier, date);
+ double value = fuelCostsOfTravelPerVessel(str, metier, step);
result.setValue(str, metier, value);
}
}
@@ -182,12 +179,12 @@
*
* @param str
* @param metier
- * @param date
+ * @param step
* @return
*/
private double fuelCostsOfTravelPerVessel(Strategy str, Metier metier,
- Date date) {
- Month month = date.getMonth();
+ TimeStep step) {
+ Month month = step.getMonth();
double nbTrip = str.getStrategyMonthInfo(month).getNumberOfTrips();
Collection<Zone> zone = metier.getMetierSeasonInfo(month).getZone();
@@ -204,10 +201,10 @@
// matrixCostsOfFishingPerVessel
//////////////////////////////////////////////////////////////////////
- public MatrixND matrixCostsOfFishingPerVessel(Date date)
+ public MatrixND matrixCostsOfFishingPerVessel(TimeStep step)
throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
- List<Metier> metiers = siMatrix.getMetiers(date);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+ List<Metier> metiers = siMatrix.getMetiers(step);
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_COSTS_OF_FISHING_PER_VESSEL,
@@ -216,10 +213,10 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = siMatrix.getMetiers(str, date);
+ metiers = siMatrix.getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
- double value = costsOfFishingPerVessel(str, metier, date);
+ double value = costsOfFishingPerVessel(str, metier, step);
result.setValue(str, metier, value);
}
}
@@ -235,12 +232,12 @@
*
* @param str
* @param metier
- * @param date
+ * @param step
* @return
*/
private double costsOfFishingPerVessel(Strategy str, Metier metier,
- Date date) {
- double fishingTime = fishingTimePerMonthPerVessel(str, metier, date);
+ TimeStep step) {
+ double fishingTime = fishingTimePerMonthPerVessel(str, metier, step);
EffortDescription effort = str.getSetOfVessels().getPossibleMetiers(
metier);
@@ -259,9 +256,9 @@
// matrixFuelCostsPerVessel
//////////////////////////////////////////////////////////////////////
- public MatrixND matrixFuelCostsPerVessel(Date date) throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
- List<Metier> metiers = siMatrix.getMetiers(date);
+ public MatrixND matrixFuelCostsPerVessel(TimeStep step) throws TopiaException {
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+ List<Metier> metiers = siMatrix.getMetiers(step);
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_FUEL_COSTS_PER_VESSEL,
@@ -270,10 +267,10 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = siMatrix.getMetiers(str, date);
+ metiers = siMatrix.getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
- double value = fuelCostsPerVessel(str, metier, date);
+ double value = fuelCostsPerVessel(str, metier, step);
result.setValue(str, metier, value);
}
}
@@ -288,12 +285,12 @@
*
* @param str
* @param metier
- * @param date
+ * @param step
* @return
*/
- private double fuelCostsPerVessel(Strategy str, Metier metier, Date date) {
- double fuelCosts = fuelCostsOfTravelPerVessel(str, metier, date);
- double costsOfFishing = costsOfFishingPerVessel(str, metier, date);
+ private double fuelCostsPerVessel(Strategy str, Metier metier, TimeStep step) {
+ double fuelCosts = fuelCostsOfTravelPerVessel(str, metier, step);
+ double costsOfFishing = costsOfFishingPerVessel(str, metier, step);
return fuelCosts + costsOfFishing;
}
@@ -302,10 +299,10 @@
// matrixRepairAndMaintenanceGearCostsPerVessel
//////////////////////////////////////////////////////////////////////
- public MatrixND matrixRepairAndMaintenanceGearCostsPerVessel(Date date)
+ public MatrixND matrixRepairAndMaintenanceGearCostsPerVessel(TimeStep step)
throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
- List<Metier> metiers = siMatrix.getMetiers(date);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+ List<Metier> metiers = siMatrix.getMetiers(step);
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_REPAIR_AND_MAINTENANCE_GEAR_COSTS_PER_VESSEL,
@@ -314,18 +311,18 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = siMatrix.getMetiers(str, date);
+ metiers = siMatrix.getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
double value = repairAndMaintenanceGearCostsPerVessel(str,
- metier, date);
+ metier, step);
result.setValue(str, metier, value);
}
}
// for(Strategy str : strategies){
- // metiers = siMatrix.getMetiers(str, date);
+ // metiers = siMatrix.getMetiers(str, step);
// for(Metier metier : metiers) {
- // double value = repairAndMaintenanceGearCostsPerVessel(str, metier, date);
+ // double value = repairAndMaintenanceGearCostsPerVessel(str, metier, step);
// result.setValue(str, metier, value);
// }
// }
@@ -341,12 +338,12 @@
*
* @param str
* @param metier
- * @param date
+ * @param step
* @return
*/
private double repairAndMaintenanceGearCostsPerVessel(Strategy str,
- Metier metier, Date date) {
- double fishingTime = fishingTimePerMonthPerVessel(str, metier, date);
+ Metier metier, TimeStep step) {
+ double fishingTime = fishingTimePerMonthPerVessel(str, metier, step);
EffortDescription effort = str.getSetOfVessels().getPossibleMetiers(
metier);
@@ -363,10 +360,10 @@
// matrixOtherRunningCostsPerVessel
//////////////////////////////////////////////////////////////////////
- public MatrixND matrixOtherRunningCostsPerVessel(Date date)
+ public MatrixND matrixOtherRunningCostsPerVessel(TimeStep step)
throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
- List<Metier> metiers = siMatrix.getMetiers(date);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+ List<Metier> metiers = siMatrix.getMetiers(step);
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_OTHER_RUNNING_COSTS_PER_VESSEL,
@@ -375,10 +372,10 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = siMatrix.getMetiers(str, date);
+ metiers = siMatrix.getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
- double value = otherRunningCostsPerVessel(str, metier, date);
+ double value = otherRunningCostsPerVessel(str, metier, step);
result.setValue(str, metier, value);
}
}
@@ -394,12 +391,12 @@
*
* @param str
* @param metier
- * @param date
+ * @param step
* @return
*/
private double otherRunningCostsPerVessel(Strategy str, Metier metier,
- Date date) {
- double fishingTime = fishingTimePerMonthPerVessel(str, metier, date);
+ TimeStep step) {
+ double fishingTime = fishingTimePerMonthPerVessel(str, metier, step);
EffortDescription effort = str.getSetOfVessels().getPossibleMetiers(
metier);
@@ -416,10 +413,10 @@
// matrixSharedNotFixedCostsPerVessel
//////////////////////////////////////////////////////////////////////
- public MatrixND matrixSharedNotFixedCostsPerVessel(Date date)
+ public MatrixND matrixSharedNotFixedCostsPerVessel(TimeStep step)
throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
- List<Metier> metiers = siMatrix.getMetiers(date);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+ List<Metier> metiers = siMatrix.getMetiers(step);
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_SHARED_NOT_FIXED_COSTS_PER_VESSEL,
@@ -428,10 +425,10 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = siMatrix.getMetiers(str, date);
+ metiers = siMatrix.getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
- double value = sharedNotFixedCostsPerVessel(str, metier, date);
+ double value = sharedNotFixedCostsPerVessel(str, metier, step);
result.setValue(str, metier, value);
}
}
@@ -446,14 +443,14 @@
*
* @param str
* @param metier
- * @param date
+ * @param step
* @return
*/
private double sharedNotFixedCostsPerVessel(Strategy str, Metier metier,
- Date date) {
- double fuelCostsPerVessel = fuelCostsPerVessel(str, metier, date);
+ TimeStep step) {
+ double fuelCostsPerVessel = fuelCostsPerVessel(str, metier, step);
double otherRunningCostsPerVessel = otherRunningCostsPerVessel(str,
- metier, date);
+ metier, step);
return fuelCostsPerVessel + otherRunningCostsPerVessel;
}
@@ -462,11 +459,11 @@
// matrixGrossValueOfLandingsPerSpeciesPerStrategyMet
//////////////////////////////////////////////////////////////////////
- public MatrixND matrixGrossValueOfLandingsPerSpeciesPerStrategyMet(Date date)
+ public MatrixND matrixGrossValueOfLandingsPerSpeciesPerStrategyMet(TimeStep step)
throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
- List<Metier> metiers = siMatrix.getMetiers(date);
- List<Population> pops = siMatrix.getPopulations(date);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+ List<Metier> metiers = siMatrix.getMetiers(step);
+ List<Population> pops = siMatrix.getPopulations(step);
MatrixND result = MatrixFactory
.getInstance()
@@ -480,11 +477,11 @@
Population pop = pops.get(p);
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = siMatrix.getMetiers(str, date);
+ metiers = siMatrix.getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
double value = grossValueOfLandingsPerSpeciesPerStrategyMet(
- str, metier, pop, date);
+ str, metier, pop, step);
result.setValue(str, metier, pop, value);
}
}
@@ -506,11 +503,11 @@
* @param str
* @param metier
* @param pop
- * @param date
+ * @param step
* @return
*/
private double grossValueOfLandingsPerSpeciesPerStrategyMet(Strategy str,
- Metier metier, Population pop, Date date) {
+ Metier metier, Population pop, TimeStep step) {
List<PopulationGroup> groups = pop.getPopulationGroup();
double result = 0;
for (PopulationGroup group : groups) {
@@ -518,9 +515,9 @@
Collection<Zone> zones = pop.getPopulationZone();
for (Zone zone : zones) {
double catchWeight = getCatchWeightPerStrMetPerZonePop(str,
- metier, group, zone, date);
+ metier, group, zone, step);
double discardsWeight = getDiscardsWeightPerStrMet(str, metier,
- group, zone, date);
+ group, zone, step);
// FIXME demander/verifier que ce le bon calcule
result += price * (catchWeight - discardsWeight);
}
@@ -533,12 +530,12 @@
* @param metier
* @param group
* @param zone
- * @param date
+ * @param step
* @return
*/
private double getCatchWeightPerStrMetPerZonePop(Strategy str,
- Metier metier, PopulationGroup group, Zone zone, Date date) {
- MatrixND mat = resultManager.getMatrix(date, group.getPopulation(),
+ Metier metier, PopulationGroup group, Zone zone, TimeStep step) {
+ MatrixND mat = resultManager.getMatrix(step, group.getPopulation(),
ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
double result = 0;
if (mat != null) {
@@ -552,12 +549,12 @@
* @param metier
* @param group
* @param zone
- * @param date
+ * @param step
* @return
*/
private double getDiscardsWeightPerStrMet(Strategy str, Metier metier,
- PopulationGroup group, Zone zone, Date date) {
- MatrixND mat = resultManager.getMatrix(date, group.getPopulation(),
+ PopulationGroup group, Zone zone, TimeStep step) {
+ MatrixND mat = resultManager.getMatrix(step, group.getPopulation(),
ResultName.MATRIX_DISCARDS_WEIGHT_PER_STR_MET_PER_ZONE_POP);
double result = 0;
if (mat != null) {
@@ -570,10 +567,10 @@
// matrixGrossValueOfLandingsPerStrategyMet
//////////////////////////////////////////////////////////////////////
- public MatrixND matrixGrossValueOfLandingsPerStrategyMet(Date date)
+ public MatrixND matrixGrossValueOfLandingsPerStrategyMet(TimeStep step)
throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
- List<Metier> metiers = siMatrix.getMetiers(date);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+ List<Metier> metiers = siMatrix.getMetiers(step);
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_GROSS_VALUE_OF_LANDINGS_PER_STRATEGY_MET,
@@ -582,11 +579,11 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = siMatrix.getMetiers(str, date);
+ metiers = siMatrix.getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
double value = grossValueOfLandingsPerStrategyMet(str, metier,
- date);
+ step);
result.setValue(str, metier, value);
}
}
@@ -597,18 +594,18 @@
/**
* @param str
* @param metier
- * @param date
+ * @param step
* @return
* @throws TopiaException
*/
private double grossValueOfLandingsPerStrategyMet(Strategy str,
- Metier metier, Date date) throws TopiaException {
- List<Population> pops = siMatrix.getPopulations(date);
+ Metier metier, TimeStep step) throws TopiaException {
+ List<Population> pops = siMatrix.getPopulations(step);
double result = 0;
for (int i = 0; i < pops.size(); i++) {
Population pop = (Population) pops.get(i);
result += grossValueOfLandingsPerSpeciesPerStrategyMet(str, metier,
- pop, date);
+ pop, step);
}
return result;
}
@@ -617,10 +614,10 @@
// matrixGrossValueOfLandingsPerStrategyMetPerVessel
//////////////////////////////////////////////////////////////////////
- public MatrixND matrixGrossValueOfLandingsPerStrategyMetPerVessel(Date date)
+ public MatrixND matrixGrossValueOfLandingsPerStrategyMetPerVessel(TimeStep step)
throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
- List<Metier> metiers = siMatrix.getMetiers(date);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+ List<Metier> metiers = siMatrix.getMetiers(step);
MatrixND result = MatrixFactory
.getInstance()
@@ -631,11 +628,11 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = siMatrix.getMetiers(str, date);
+ metiers = siMatrix.getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
double value = grossValueOfLandingsPerStrategyMetPerVessel(str,
- metier, date);
+ metier, step);
result.setValue(str, metier, value);
}
}
@@ -650,20 +647,20 @@
*
* @param str
* @param metier
- * @param date
+ * @param step
* @return
* @throws TopiaException
*/
private double grossValueOfLandingsPerStrategyMetPerVessel(Strategy str,
- Metier metier, Date date) throws TopiaException {
+ Metier metier, TimeStep step) throws TopiaException {
double grossValueOfLandingsPerStrategyMet = grossValueOfLandingsPerStrategyMet(
- str, metier, date);
+ str, metier, step);
// 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);
+ str, metier, step);
return (grossValueOfLandingsPerStrategyMet + grossValueOfLandingsOtherSpeciesPerStrategyMet)
/ (proportionSetOfVessels * numberOfVessels);
@@ -673,10 +670,10 @@
// matrixNetValueOfLandingsPerStrategyMet
//////////////////////////////////////////////////////////////////////
- public MatrixND matrixNetValueOfLandingsPerStrategyMet(Date date)
+ public MatrixND matrixNetValueOfLandingsPerStrategyMet(TimeStep step)
throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
- List<Metier> metiers = siMatrix.getMetiers(date);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+ List<Metier> metiers = siMatrix.getMetiers(step);
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET,
@@ -685,11 +682,11 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = siMatrix.getMetiers(str, date);
+ metiers = siMatrix.getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
double value = netValueOfLandingsPerStrategyMet(str, metier,
- date);
+ step);
result.setValue(str, metier, value);
}
}
@@ -705,14 +702,14 @@
*
* @param str
* @param metier
- * @param date
+ * @param step
* @return
* @throws TopiaException
*/
private double netValueOfLandingsPerStrategyMet(Strategy str,
- Metier metier, Date date) throws TopiaException {
+ Metier metier, TimeStep step) throws TopiaException {
double grossValue = grossValueOfLandingsPerStrategyMet(str, metier,
- date);
+ step);
EffortDescription effort = str.getSetOfVessels().getPossibleMetiers(
metier);
double landingCost = 1;
@@ -722,7 +719,7 @@
}
double grossValueOfLandingsOtherSpeciesPerStrategyMet = grossValueOfLandingsOtherSpeciesPerStrategyMet(
- str, metier, date);
+ str, metier, step);
double result = (grossValue + grossValueOfLandingsOtherSpeciesPerStrategyMet)
* landingCost;
@@ -730,7 +727,7 @@
}
private double grossValueOfLandingsOtherSpeciesPerStrategyMet(Strategy str,
- Metier metier, Date date) throws TopiaException {
+ Metier metier, TimeStep step) throws TopiaException {
// FIXME evaluer l'equation dans suivant le doc des equations
return 0;
}
@@ -739,10 +736,10 @@
// matrixNetValueOfLandingsPerStrategyMetPerVessel
//////////////////////////////////////////////////////////////////////
- public MatrixND matrixNetValueOfLandingsPerStrategyMetPerVessel(Date date)
+ public MatrixND matrixNetValueOfLandingsPerStrategyMetPerVessel(TimeStep step)
throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
- List<Metier> metiers = siMatrix.getMetiers(date);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+ List<Metier> metiers = siMatrix.getMetiers(step);
MatrixND result = MatrixFactory
.getInstance()
@@ -753,11 +750,11 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = siMatrix.getMetiers(str, date);
+ metiers = siMatrix.getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
double value = netValueOfLandingsPerStrategyMetPerVessel(str,
- metier, date);
+ metier, step);
result.setValue(str, metier, value);
}
}
@@ -773,14 +770,14 @@
*
* @param str
* @param metier
- * @param date
+ * @param step
* @return
* @throws TopiaException
*/
private double netValueOfLandingsPerStrategyMetPerVessel(Strategy str,
- Metier metier, Date date) throws TopiaException {
+ Metier metier, TimeStep step) throws TopiaException {
double netValueOfLandingsPerStrategyMet = netValueOfLandingsPerStrategyMet(
- str, metier, date);
+ str, metier, step);
// 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();
@@ -793,10 +790,10 @@
// matrixNetRenevueToSharePerStrategyMetPerVessel
//////////////////////////////////////////////////////////////////////
- public MatrixND matrixNetRenevueToSharePerStrategyMetPerVessel(Date date)
+ public MatrixND matrixNetRenevueToSharePerStrategyMetPerVessel(TimeStep step)
throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
- List<Metier> metiers = siMatrix.getMetiers(date);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+ List<Metier> metiers = siMatrix.getMetiers(step);
MatrixND result = MatrixFactory
.getInstance()
@@ -807,11 +804,11 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = siMatrix.getMetiers(str, date);
+ metiers = siMatrix.getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
double value = netRenevueToSharePerStrategyMetPerVessel(str,
- metier, date);
+ metier, step);
result.setValue(str, metier, value);
}
}
@@ -828,17 +825,17 @@
*
* @param str
* @param metier
- * @param date
+ * @param step
* @return
* @throws TopiaException
*/
private double netRenevueToSharePerStrategyMetPerVessel(Strategy str,
- Metier metier, Date date) throws TopiaException {
+ Metier metier, TimeStep step) throws TopiaException {
double netRenevueToSharePerStrategyMetPerVessel = netValueOfLandingsPerStrategyMetPerVessel(
- str, metier, date);
+ str, metier, step);
double sharedNotFixedCostsPerVessel = sharedNotFixedCostsPerVessel(str,
- metier, date);
- double propStr = str.getStrategyMonthInfo(date.getMonth())
+ metier, step);
+ double propStr = str.getStrategyMonthInfo(step.getMonth())
.getProportionMetier(metier);
double result = netRenevueToSharePerStrategyMetPerVessel
@@ -850,10 +847,10 @@
// matrixCrewSharePerStrategyMetPerVessel
//////////////////////////////////////////////////////////////////////
- public MatrixND matrixCrewSharePerStrategyMetPerVessel(Date date)
+ public MatrixND matrixCrewSharePerStrategyMetPerVessel(TimeStep step)
throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
- List<Metier> metiers = siMatrix.getMetiers(date);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+ List<Metier> metiers = siMatrix.getMetiers(step);
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_CREW_SHARE_PER_STRATEGY_MET_PER_VESSEL,
@@ -862,11 +859,11 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = siMatrix.getMetiers(str, date);
+ metiers = siMatrix.getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
double value = crewSharePerStrategyMetPerVessel(str, metier,
- date);
+ step);
result.setValue(str, metier, value);
}
}
@@ -881,14 +878,14 @@
*
* @param str
* @param metier
- * @param date
+ * @param step
* @return
* @throws TopiaException
*/
private double crewSharePerStrategyMetPerVessel(Strategy str,
- Metier metier, Date date) throws TopiaException {
+ Metier metier, TimeStep step) throws TopiaException {
double netRenevueToShare = netRenevueToSharePerStrategyMetPerVessel(
- str, metier, date);
+ str, metier, step);
EffortDescription effort = str.getSetOfVessels().getPossibleMetiers(
metier);
@@ -906,9 +903,9 @@
//////////////////////////////////////////////////////////////////////
public MatrixND matrixOwnerMarginOverVariableCostsPerStrategyMetPerVessel(
- Date date) throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
- List<Metier> metiers = siMatrix.getMetiers(date);
+ TimeStep step) throws TopiaException {
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+ List<Metier> metiers = siMatrix.getMetiers(step);
MatrixND result = MatrixFactory
.getInstance()
@@ -919,11 +916,11 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = siMatrix.getMetiers(str, date);
+ metiers = siMatrix.getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
double value = ownerMarginOverVariableCostsPerStrategyMetPerVessel(
- str, metier, date);
+ str, metier, step);
result.setValue(str, metier, value);
}
}
@@ -941,18 +938,18 @@
*
* @param str
* @param metier
- * @param date
+ * @param step
* @return
* @throws TopiaException
*/
private double ownerMarginOverVariableCostsPerStrategyMetPerVessel(
- Strategy str, Metier metier, Date date) throws TopiaException {
+ Strategy str, Metier metier, TimeStep step) throws TopiaException {
double netRenevueToShare = netRenevueToSharePerStrategyMetPerVessel(
- str, metier, date);
- double crewShare = crewSharePerStrategyMetPerVessel(str, metier, date);
+ str, metier, step);
+ double crewShare = crewSharePerStrategyMetPerVessel(str, metier, step);
double repair = repairAndMaintenanceGearCostsPerVessel(str, metier,
- date);
- double propStr = str.getStrategyMonthInfo(date.getMonth())
+ step);
+ double propStr = str.getStrategyMonthInfo(step.getMonth())
.getProportionMetier(metier);
return netRenevueToShare - crewShare - repair * propStr;
@@ -963,9 +960,9 @@
//////////////////////////////////////////////////////////////////////
public MatrixND matrixVesselMarginOverVariableCostsPerStrategyMetPerVessel(
- Date date) throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
- List<Metier> metiers = siMatrix.getMetiers(date);
+ TimeStep step) throws TopiaException {
+ List<Strategy> strategies = siMatrix.getStrategies(step);
+ List<Metier> metiers = siMatrix.getMetiers(step);
MatrixND result = MatrixFactory
.getInstance()
@@ -976,11 +973,11 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = siMatrix.getMetiers(str, date);
+ metiers = siMatrix.getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
double value = vesselMarginOverVariableCostsPerStrategyMetPerVessel(
- str, metier, date);
+ str, metier, step);
result.setValue(str, metier, value);
}
}
@@ -997,17 +994,17 @@
*
* @param str
* @param metier
- * @param date
+ * @param step
* @return
* @throws TopiaException
*/
private double vesselMarginOverVariableCostsPerStrategyMetPerVessel(
- Strategy str, Metier metier, Date date) throws TopiaException {
+ Strategy str, Metier metier, TimeStep step) throws TopiaException {
double netRenevueToShare = netRenevueToSharePerStrategyMetPerVessel(
- str, metier, date);
+ str, metier, step);
double repair = repairAndMaintenanceGearCostsPerVessel(str, metier,
- date);
- double propStr = str.getStrategyMonthInfo(date.getMonth())
+ step);
+ double propStr = str.getStrategyMonthInfo(step.getMonth())
.getProportionMetier(metier);
return netRenevueToShare - repair * propStr;
@@ -1018,8 +1015,8 @@
//////////////////////////////////////////////////////////////////////
public MatrixND matrixOwnerMarginOverVariableCostsPerStrategyPerVessel(
- Date date) throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
+ TimeStep step) throws TopiaException {
+ List<Strategy> strategies = siMatrix.getStrategies(step);
MatrixND result = MatrixFactory
.getInstance()
@@ -1031,7 +1028,7 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
double value = ownerMarginOverVariableCostsPerStrategyPerVessel(
- str, date);
+ str, step);
result.setValue(s, value);
}
@@ -1045,12 +1042,12 @@
* [str,met,month]
*
* @param str
- * @param date
+ * @param step
* @return
* @throws TopiaException
*/
private double ownerMarginOverVariableCostsPerStrategyPerVessel(
- Strategy str, Date date) throws TopiaException {
+ Strategy str, TimeStep step) throws TopiaException {
SetOfVessels sov = str.getSetOfVessels();
Collection<EffortDescription> efforts = sov.getPossibleMetiers();
@@ -1059,7 +1056,7 @@
for (EffortDescription effort : efforts) {
Metier metier = effort.getPossibleMetiers();
result += ownerMarginOverVariableCostsPerStrategyMetPerVessel(str,
- metier, date);
+ metier, step);
}
return result;
}
@@ -1068,9 +1065,9 @@
// matrixOwnerMarginOverVariableCostsPerStrategy
//////////////////////////////////////////////////////////////////////
- public MatrixND matrixOwnerMarginOverVariableCostsPerStrategy(Date date)
+ public MatrixND matrixOwnerMarginOverVariableCostsPerStrategy(TimeStep step)
throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
MatrixND result = MatrixFactory
.getInstance()
@@ -1081,7 +1078,7 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- double value = ownerMarginOverVariableCostsPerStrategy(str, date);
+ double value = ownerMarginOverVariableCostsPerStrategy(str, step);
result.setValue(s, value);
}
@@ -1095,14 +1092,14 @@
* *[PropNbVessels(str,sov)*NbVesselsSetOfVessels(sov)]
*
* @param str
- * @param date
+ * @param step
* @return
* @throws TopiaException
*/
private double ownerMarginOverVariableCostsPerStrategy(Strategy str,
- Date date) throws TopiaException {
+ TimeStep step) throws TopiaException {
double ownerMarginOverVariableCostsPerStrategyPerVessel = ownerMarginOverVariableCostsPerStrategyPerVessel(
- str, date);
+ str, step);
double proportionSetOfVessels = str.getProportionSetOfVessels();
double numberOfVessels = str.getSetOfVessels().getNumberOfVessels();
@@ -1115,8 +1112,8 @@
//////////////////////////////////////////////////////////////////////
public MatrixND matrixVesselMarginOverVariableCostsPerStrategyPerVessel(
- Date date) throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
+ TimeStep step) throws TopiaException {
+ List<Strategy> strategies = siMatrix.getStrategies(step);
MatrixND result = MatrixFactory
.getInstance()
@@ -1128,7 +1125,7 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
double value = vesselMarginOverVariableCostsPerStrategyPerVessel(
- str, date);
+ str, step);
result.setValue(s, value);
}
@@ -1142,12 +1139,12 @@
* [str,met,month]
*
* @param str
- * @param date
+ * @param step
* @return
* @throws TopiaException
*/
private double vesselMarginOverVariableCostsPerStrategyPerVessel(
- Strategy str, Date date) throws TopiaException {
+ Strategy str, TimeStep step) throws TopiaException {
SetOfVessels sov = str.getSetOfVessels();
Collection<EffortDescription> efforts = sov.getPossibleMetiers();
@@ -1156,7 +1153,7 @@
for (EffortDescription effort : efforts) {
Metier metier = effort.getPossibleMetiers();
result += vesselMarginOverVariableCostsPerStrategyMetPerVessel(str,
- metier, date);
+ metier, step);
}
return result;
}
@@ -1165,9 +1162,9 @@
// matrixVesselMarginOverVariableCostsPerStrategy
//////////////////////////////////////////////////////////////////////
- public MatrixND matrixVesselMarginOverVariableCostsPerStrategy(Date date)
+ public MatrixND matrixVesselMarginOverVariableCostsPerStrategy(TimeStep step)
throws TopiaException {
- List<Strategy> strategies = siMatrix.getStrategies(date);
+ List<Strategy> strategies = siMatrix.getStrategies(step);
MatrixND result = MatrixFactory
.getInstance()
@@ -1178,7 +1175,7 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- double value = vesselMarginOverVariableCostsPerStrategy(str, date);
+ double value = vesselMarginOverVariableCostsPerStrategy(str, step);
result.setValue(s, value);
}
@@ -1192,14 +1189,14 @@
* *[PropNbVessels(str,sov)*NbVesselsSetOfVessels(sov)]
*
* @param str
- * @param date
+ * @param step
* @return
* @throws TopiaException
*/
private double vesselMarginOverVariableCostsPerStrategy(Strategy str,
- Date date) throws TopiaException {
+ TimeStep step) throws TopiaException {
double vesselMarginOverVariableCostsPerStrategyPerVessel = vesselMarginOverVariableCostsPerStrategyPerVessel(
- str, date);
+ str, step);
double proportionSetOfVessels = str.getProportionSetOfVessels();
double numberOfVessels = str.getSetOfVessels().getNumberOfVessels();
@@ -1214,8 +1211,8 @@
///////////////////////////////////////////////////////////////////////////
public double valuePerUnitFishingEffort(Strategy str, Metier metier,
- Date date) throws TopiaException {
- List<Population> pops = siMatrix.getPopulations(date);
+ TimeStep step) throws TopiaException {
+ List<Population> pops = siMatrix.getPopulations(step);
double result = 0;
@@ -1226,15 +1223,15 @@
double price = group.getPrice();
for (Zone zone : zones) {
double catchValue = getCatchWeightPerStrMetPerZonePop(str,
- metier, group, zone, date);
+ metier, group, zone, step);
double discards = getDiscardsWeightPerStrMet(str, metier,
- group, zone, date);
+ group, zone, step);
result += price * (catchValue - discards);
}
}
}
- double effort = getEffortPerStrategyMet(str, metier, date);
+ double effort = getEffortPerStrategyMet(str, metier, step);
if (effort == 0) {
result = 0;
@@ -1248,11 +1245,11 @@
/**
* @param str
* @param metier
- * @param date
+ * @param step
* @return
*/
- public double getEffortPerStrategyMet(Strategy str, Metier metier, Date date) {
- MatrixND mat = resultManager.getMatrix(date,
+ public double getEffortPerStrategyMet(Strategy str, Metier metier, TimeStep step) {
+ MatrixND mat = resultManager.getMatrix(step,
ResultName.MATRIX_EFFORT_PER_STRATEGY_MET);
double result = 0;
if (mat != null) {
@@ -1262,10 +1259,10 @@
}
public double landingPerUnitFishingEffort(Strategy str, Metier metier,
- Date date) throws TopiaException {
- List<Population> pops = siMatrix.getPopulations(date);
+ TimeStep step) throws TopiaException {
+ List<Population> pops = siMatrix.getPopulations(step);
- double effort = getEffortPerStrategyMet(str, metier, date);
+ double effort = getEffortPerStrategyMet(str, metier, step);
double result = 0;
if (effort != 0) { // s'il n'y a pas d'effort on retournera 0
@@ -1275,9 +1272,9 @@
for (PopulationGroup group : groups) {
for (Zone zone : zones) {
double catchValue = getCatchWeightPerStrMetPerZonePop(
- str, metier, group, zone, date);
+ str, metier, group, zone, step);
double discards = getDiscardsWeightPerStrMet(str,
- metier, group, zone, date);
+ metier, group, zone, step);
result += catchValue - discards;
}
}
Modified: isis-fish/trunk/src/test/resources/test-database/scripts/ResultName.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/scripts/ResultName.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/scripts/ResultName.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, Code Lutin, Cedric Pineau, Benjamin Poussin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -23,18 +20,6 @@
* #L%
*/
-/* *
- * ResultName.java
- *
- * Created: 23 aout 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.nuiton.i18n.I18n.n_;
@@ -57,91 +42,371 @@
* @author poussin
*/
public class ResultName {
+
+ /**
+ * Matrix with 4 dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Metier
+ * Dimension 3 : Population
+ * Dimension 4 : Zone
+ */
@Doc(value = "do the doc of Result matrixDiscardsWeightPerStrMet")
static final public String MATRIX_DISCARDS_WEIGHT_PER_STR_MET_PER_ZONE_POP = n_("matrixDiscardsWeightPerStrMetPerZonePop");
+ /**
+ * Matrix with five dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ * Dimension 4 : Group
+ * Dimension 5 : Zone
+ */
@Doc(value = "do the doc of Result matrixDiscardsPerStrMet")
static final public String MATRIX_DISCARDS_PER_STR_MET_PER_ZONE_POP = n_("matrixDiscardsPerStrMetPerZonePop");
+
+ /**
+ * Matrix with five dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ * Dimension 4 : Group
+ * Dimension 5 : Zone
+ */
@Doc(value = "do the doc of Result matrixLandingPerMet")
static final public String MATRIX_LANDING_PER_MET = n_("matrixLandingPerMet");
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@Doc(value = "do the doc of Result matrixEffortPerStrategyMet")
static final public String MATRIX_EFFORT_PER_STRATEGY_MET = n_("matrixEffortPerStrategyMet");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@Doc(value = "do the doc of Result matrixEffortNominalPerStrategyMet")
static final public String MATRIX_EFFORT_NOMINAL_PER_STRATEGY_MET = n_("matrixEffortNominalPerStrategyMet");
- @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");
+
+ /**
+ * Matrix with five dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ * Dimension 4 : Group
+ * Dimension 5 : Zone
+ */
@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");
+
+ /**
+ * Matrix with five dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ * Dimension 4 : Group
+ * Dimension 5 : Zone
+ */
@Doc(value = "do the doc of Result matrixCatchPerStrategyMetPerZoneMet")
static final public String MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_MET = n_("matrixCatchPerStrategyMetPerZoneMet");
+
+ /**
+ * Matrix with five dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ * Dimension 4 : Group
+ * Dimension 5 : Zone
+ */
@Doc(value = "do the doc of Result matrixCatchPerStrategyMetPerZonePop")
static final public String MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_POP = n_("matrixCatchPerStrategyMetPerZonePop");
+
+ /**
+ * Matrix with five dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ * Dimension 4 : Group
+ * Dimension 5 : Zone
+ */
@Doc(value = "do the doc of Result matrixCatchWeightPerStrategyMetPerZoneMet")
static final public String MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_MET = n_("matrixCatchWeightPerStrategyMetPerZoneMet");
+
+ /**
+ * Matrix with five dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ * Dimension 4 : Group
+ * Dimension 5 : Zone
+ */
@Doc(value = "do the doc of Result matrixCatchWeightPerStrategyMetPerZonePop")
static final public String MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP = n_("matrixCatchWeightPerStrategyMetPerZonePop");
+
+ /**
+ * Matrix with five dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ * Dimension 4 : Group
+ * Dimension 5 : Zone
+ */
@Doc(value = "Disponible uniquement avec les simulations par Zone. do the doc of Result matrixFishingMortality")
static final public String MATRIX_FISHING_MORTALITY = n_("matrixFishingMortality");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Group (semantics : Dimension 1)
+ * Dimension 3 : Zone (semantics : Dimension 2)
+ */
@Doc(value = "do the doc of Result matrixAbundance")
static final public String MATRIX_ABUNDANCE = n_("matrixAbundance");
- @Doc(value = "do the doc of Result matrixBiomass")
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : Date
+ * Dimension 2 : Group
+ * Dimension 3 : Zone
+ */
+ @Doc(value = "do the doc of Result matrixAbundanceBeginMonth")
static final public String MATRIX_ABUNDANCE_BEGIN_MONTH = n_("matrixAbundanceBeginMonth");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Group
+ * Dimension 3 : Zone
+ */
@Doc(value = "do the doc of Result matrixBiomass")
static final public String MATRIX_BIOMASS = n_("matrixBiomass");
- @Doc(value = "do the doc of Result matrixBiomass")
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Group
+ * Dimension 3 : Zone
+ */
+ @Doc(value = "do the doc of Result matrixBiomassBeginMonth")
static final public String MATRIX_BIOMASS_BEGIN_MONTH = n_("matrixBiomassBeginMonth");
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@Doc(value = "do the doc of Result matrixFishingTimePerMonthPerVessel")
static final public String MATRIX_FISHING_TIME_PER_MONTH_PER_VESSEL = n_("matrixFishingTimePerMonthPerVessel");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@Doc(value = "do the doc of Result matrixFuelCostsOfTravelPerVessel")
static final public String MATRIX_FUEL_COSTS_OF_TRAVEL_PER_VESSEL = n_("matrixFuelCostsOfTravelPerVessel");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@Doc(value = "do the doc of Result matrixCostsOfFishingPerVessel")
static final public String MATRIX_COSTS_OF_FISHING_PER_VESSEL = n_("matrixCostsOfFishingPerVessel");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@Doc(value = "do the doc of Result matrixFuelCostsPerVessel")
static final public String MATRIX_FUEL_COSTS_PER_VESSEL = n_("matrixFuelCostsPerVessel");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@Doc(value = "do the doc of Result matrixRepairAndMaintenanceGearCostsPerVessel")
static final public String MATRIX_REPAIR_AND_MAINTENANCE_GEAR_COSTS_PER_VESSEL = n_("matrixRepairAndMaintenanceGearCostsPerVessel");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@Doc(value = "do the doc of Result matrixOtherRunningCostsPerVessel")
static final public String MATRIX_OTHER_RUNNING_COSTS_PER_VESSEL = n_("matrixOtherRunningCostsPerVessel");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@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");
+
+ /**
+ * Matrix with four dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ * Dimension 4 : Population
+ */
@Doc(value = "do the doc of Result matrixGrossValueOfLandingsPerSpeciesPerStrategyMet")
static final public String MATRIX_GROSS_VALUE_OF_LANDINGS_PER_SPECIES_PER_STRATEGY_MET = n_("matrixGrossValueOfLandingsPerSpeciesPerStrategyMet");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@Doc(value = "do the doc of Result matrixGrossValueOfLandingsPerStrategyMet")
static final public String MATRIX_GROSS_VALUE_OF_LANDINGS_PER_STRATEGY_MET = n_("matrixGrossValueOfLandingsPerStrategyMet");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ *
+ * Matrix calculated in the non generic Rule : GraviteVPUE1LangEtGrossValueOtherSpeciesECOMOD
+ */
@Doc(value = "do the doc of Result matrixGrossValueOfLandingsOtherSpeciesPerStrategyMet")
static final public String MATRIX_GROSS_VALUE_OF_LANDINGS_OTHER_SPECIES_PER_STRATEGY_MET = n_("matrixGrossValueOfLandingsOtherSpeciesPerStrategyMet");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@Doc(value = "do the doc of Result matrixGrossValueOfLandingsPerStrategyMetPerVessel")
static final public String MATRIX_GROSS_VALUE_OF_LANDINGS_PER_STRATEGY_MET_PER_VESSEL = n_("matrixGrossValueOfLandingsPerStrategyMetPerVessel");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@Doc(value = "do the doc of Result matrixNetValueOfLandingsPerStrategyMet")
static final public String MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET = n_("matrixNetValueOfLandingsPerStrategyMet");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@Doc(value = "do the doc of Result matrixNetValueOfLandingsPerStrategyMetPerVessel")
static final public String MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET_PER_VESSEL = n_("matrixNetValueOfLandingsPerStrategyMetPerVessel");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@Doc(value = "do the doc of Result matrixNetRenevueToSharePerStrategyMetPerVessel")
static final public String MATRIX_NET_RENEVUE_TO_SHARE_PER_STRATEGY_MET_PER_VESSEL = n_("matrixNetRenevueToSharePerStrategyMetPerVessel");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@Doc(value = "do the doc of Result matrixCrewSharePerStrategyPerVessel")
static final public String MATRIX_CREW_SHARE_PER_STRATEGY_MET_PER_VESSEL = n_("matrixCrewSharePerStrategyPerVessel");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@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");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@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");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@Doc(value = "do the doc of Result matrixOwnerMarginOverVariableCostsPerStrategyPerVessel")
static final public String MATRIX_OWNER_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_PER_VESSEL = n_("matrixOwnerMarginOverVariableCostsPerStrategyPerVessel");
+
+ /**
+ * Matrix with two dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ */
@Doc(value = "do the doc of Result matrixOwnerMarginOverVariableCostsPerStrategy")
static final public String MATRIX_OWNER_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY = n_("matrixOwnerMarginOverVariableCostsPerStrategy");
+
+ /**
+ * Matrix with two dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ */
@Doc(value = "do the doc of Result matrixVesselMarginOverVariableCostsPerStrategyPerVessel")
static final public String MATRIX_VESSEL_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_PER_VESSEL = n_("matrixVesselMarginOverVariableCostsPerStrategyPerVessel");
+
+ /**
+ * Matrix with two dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ */
@Doc(value = "do the doc of Result matrixVesselMarginOverVariableCostsPerStrategy")
static final public String MATRIX_VESSEL_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY = n_("matrixVesselMarginOverVariableCostsPerStrategy");
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Strategy
+ * Dimension 3 : Metier
+ */
@Doc(value = "do the doc of Result matrixNoActivity")
static final public String MATRIX_NO_ACTIVITY = n_("matrixNoActivity");
+
+ /**
+ * Matrix with three dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Metier
+ * Dimension 3 : Zone
+ */
@Doc(value = "do the doc of Result matrixMetierZone")
static final public String MATRIX_METIER_ZONE = n_("matrixMetierZone");
+
+ /**
+ * Matrix with two dimensions
+ * Dimension 1 : TimeStep
+ * Dimension 2 : Group
+ */
@Doc(value = "do the doc of Result matrixPrice")
static final public String MATRIX_PRICE = n_("matrixPrice");
}
Modified: isis-fish/trunk/src/test/resources/test-database/scripts/RuleUtil.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/scripts/RuleUtil.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/scripts/RuleUtil.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -35,7 +32,7 @@
import fr.ifremer.isisfish.entities.PopulationGroup;
import fr.ifremer.isisfish.entities.Species;
import fr.ifremer.isisfish.simulator.SimulationContext;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* RuleUtil.
@@ -60,7 +57,7 @@
* passe seulement pour que le cache ne retourne pas toujours la meme valeur
* @return total catch in tons
*/
- public static double getTotalCatchTons(SimulationContext context, Species species, Date date) {
+ public static double getTotalCatchTons(SimulationContext context, Species species, TimeStep step) {
double result = 0;
for (Population pop : species.getPopulation()) {
MatrixND mat = context.getPopulationMonitor().getHoldCatch(pop);
Modified: isis-fish/trunk/src/test/resources/test-database/scripts/SiMatrix.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/scripts/SiMatrix.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/scripts/SiMatrix.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 Ifremer, 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
@@ -58,7 +55,7 @@
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.TimeStep;
import fr.ifremer.isisfish.types.Month;
/**
@@ -67,15 +64,15 @@
* Created: 21 aout 2006 15:53:01
*
* @author poussin
- * @version $Revision: 1 $
+ * @version $Revision: 1.18 $
*
- * Last update: $Date: 2009-10-19 14:25:49 +0200 (lun., 19 oct. 2009) $
+ * Last update: $Date: 2007-11-02 17:53:20 $
* by : $Author: bpoussin $
*/
public class SiMatrix {
/** to use log facility, just put in your code: log.info("..."); */
- private Log log = LogFactory.getLog(SiMatrix.class);
+ static private Log log = LogFactory.getLog(SiMatrix.class);
protected SimulationContext context = null;
protected TopiaContext db = null;
@@ -121,7 +118,7 @@
* @return
* @throws TopiaException
*/
- public List<Zone> getZones(Date date) throws TopiaException {
+ public List<Zone> getZones(TimeStep step) throws TopiaException {
ZoneDAO dao = IsisFishDAOHelper.getZoneDAO(db);
List<Zone> result = dao.findAll();
return result;
@@ -131,7 +128,7 @@
* @return
* @throws TopiaException
*/
- public List<Population> getPopulations(Date date) throws TopiaException {
+ public List<Population> getPopulations(TimeStep step) throws TopiaException {
List<Population> populations = new ArrayList<Population>();
for (Population pop : context.getSimulationStorage().getParameter()
.getPopulations()) {
@@ -145,7 +142,7 @@
* @return
* @throws TopiaException
*/
- public List<Strategy> getStrategies(Date date) throws TopiaException {
+ public List<Strategy> getStrategies(TimeStep step) throws TopiaException {
// if (strategies == null) {
List<Strategy> strategies = new ArrayList<Strategy>();
for (Strategy str : context.getSimulationStorage().getParameter()
@@ -157,11 +154,11 @@
return strategies;
}
- public List<Metier> getMetiers(Date date) throws TopiaException {
+ public List<Metier> getMetiers(TimeStep step) throws TopiaException {
// if (metiers == null) {
List<Metier> metiers = new ArrayList<Metier>();
HashSet<Metier> tmp = new HashSet<Metier>();
- for (Strategy str : getStrategies(date)) {
+ for (Strategy str : getStrategies(step)) {
SetOfVessels sov = str.getSetOfVessels();
for (EffortDescription effort : sov.getPossibleMetiers()) {
Metier metier = effort.getPossibleMetiers();
@@ -175,15 +172,15 @@
}
/**
- * Retourne les metiers pratiques par une Strategie a une date donnee Un
+ * Retourne les metiers pratiques par une Strategie a une step donnee Un
* metier est pratique si le PropStrMet est different de 0
*
* @param str
- * @param date
+ * @param step
* @return
*/
- public List<Metier> getMetiers(Strategy str, Date date) {
- StrategyMonthInfo info = str.getStrategyMonthInfo(date.getMonth());
+ public List<Metier> getMetiers(Strategy str, TimeStep step) {
+ StrategyMonthInfo info = str.getStrategyMonthInfo(step.getMonth());
MatrixND props = info.getProportionMetier();
List<Metier> result = new ArrayList<Metier>();
@@ -200,17 +197,17 @@
/**
* Retourne la matrix Metier x Zone qui correspond au zone utilise par un
- * metier pour une date donnee. Si la valeur de la matrice est 1 alors la
+ * metier pour une step donnee. Si la valeur de la matrice est 1 alors la
* zone est utilise par le metier, si elle vaut 0 alors elle n'est pas
* utilisee.
*
- * @param date
+ * @param step
* @return
* @throws TopiaException
*/
- public MatrixND getMetierZone(Date date) throws TopiaException {
- List<Metier> metiers = getMetiers(date);
- List<Zone> zones = getZones(date);
+ public MatrixND getMetierZone(TimeStep step) throws TopiaException {
+ List<Metier> metiers = getMetiers(step);
+ List<Zone> zones = getZones(step);
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_METIER_ZONE, new List[] { metiers, zones },
@@ -218,7 +215,7 @@
for (Metier metier : metiers) {
Collection<Zone> zoneMetier = metier.getMetierSeasonInfo(
- date.getMonth()).getZone();
+ step.getMonth()).getZone();
for (Zone zone : zoneMetier) {
result.setValue(metier, zone, 1);
}
@@ -226,7 +223,7 @@
return result;
}
- public MatrixND matrixPrice(Date date, Population pop) {
+ public MatrixND matrixPrice(TimeStep step, Population pop) {
List<PopulationGroup> groups = pop.getPopulationGroup();
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_PRICE, new List[] { groups },
@@ -246,7 +243,7 @@
//
///////////////////////////////////////////////////////////////////////////
- public MatrixND matrixCatchWeightPerStrategyMetPerZoneMet(Date date,
+ public MatrixND matrixCatchWeightPerStrategyMetPerZoneMet(TimeStep step,
Population pop, MatrixND matrixCatchPerStrategyMetPerZoneMet)
throws TopiaException, IsisFishException {
List<PopulationGroup> groups = pop.getPopulationGroup();
@@ -264,23 +261,23 @@
}
public MatrixND matrixCatchPerStrategyMetPerZoneMet(MatrixND N,
- Population pop, Date date) throws TopiaException, IsisFishException {
+ Population pop, TimeStep step) throws TopiaException, IsisFishException {
MatrixND matrixFishingMortalityPerCell = matrixFishingMortalityPerCell(
- date, pop);
+ step, pop);
MatrixND matrixCatchRatePerStrategyMetPerCell = matrixCatchRatePerStrategyMetPerCell(
- pop, date, matrixFishingMortalityPerCell);
+ pop, step, matrixFishingMortalityPerCell);
MatrixND matrixCatchPerStrategyMetPerCell = matrixCatchPerStrategyMetPerCell(
- N, pop, date, matrixCatchRatePerStrategyMetPerCell);
+ N, pop, step, matrixCatchRatePerStrategyMetPerCell);
- List<Strategy> strategies = getStrategies(date);
- List<Metier> metiers = getMetiers(date);
+ List<Strategy> strategies = getStrategies(step);
+ List<Metier> metiers = getMetiers(step);
List<PopulationGroup> groups = (List<PopulationGroup>)matrixCatchPerStrategyMetPerCell
- .getSemantics(2);
- List<Zone> zones = getZones(date);
+ .getSemantic(2);
+ List<Zone> zones = getZones(step);
Set<Cell> cellPops = new HashSet(matrixCatchPerStrategyMetPerCell
- .getSemantics(4));
+ .getSemantic(4));
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_MET,
@@ -298,7 +295,7 @@
PopulationGroup group = groups.get(g);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
- MetierSeasonInfo infoMet = metier.getMetierSeasonInfo(date
+ MetierSeasonInfo infoMet = metier.getMetierSeasonInfo(step
.getMonth());
Collection<Zone> zoneMet = infoMet.getZone();
for (Zone z : zoneMet) {
@@ -323,13 +320,13 @@
}
public MatrixND matrixCatchPerStrategyMetPerZonePop(MatrixND N,
- Population pop, Date date) throws TopiaException, IsisFishException {
+ Population pop, TimeStep step) throws TopiaException, IsisFishException {
MatrixND matrixFishingMortalityPerCell = matrixFishingMortalityPerCell(
- date, pop);
+ step, pop);
MatrixND matrixCatchRatePerStrategyMetPerCell = matrixCatchRatePerStrategyMetPerCell(
- pop, date, matrixFishingMortalityPerCell);
+ pop, step, matrixFishingMortalityPerCell);
MatrixND matrixCatchPerStrategyMetPerCell = matrixCatchPerStrategyMetPerCell(
- N, pop, date, matrixCatchRatePerStrategyMetPerCell);
+ N, pop, step, matrixCatchRatePerStrategyMetPerCell);
// on somme sur les cellules
MatrixND result = matrixCatchPerStrategyMetPerCell.sumOverDim(4);
@@ -339,7 +336,7 @@
return result;
}
- public MatrixND matrixCatchWeightPerStrategyMetPerZonePop(Date date,
+ public MatrixND matrixCatchWeightPerStrategyMetPerZonePop(TimeStep step,
Population pop, MatrixND matrixCatchPerStrategyMetPerZonePop)
throws TopiaException, IsisFishException {
List<PopulationGroup> groups = pop.getPopulationGroup();
@@ -363,20 +360,20 @@
*
* @param N l'abondance sous forme de matrice 2D [class x zone]
* @param pop
- * @param date
+ * @param step
* @param matrixCatchRatePerStrategyMet
* @return
* @throws TopiaException
* @throws IsisFishException
*/
public MatrixND matrixCatchPerStrategyMetPerZone(MatrixND N,
- Population pop, Date date, MatrixND matrixCatchRatePerStrategyMet)
+ Population pop, TimeStep step, 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 matrixCatchRatePerStrategyMet = matrixCatchRatePerStrategyMet(pop, step);
MatrixND result = matrixCatchRatePerStrategyMet.copy();
result.setName(ResultName.MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_POP);
@@ -396,17 +393,17 @@
* Strategy x Metier x Classe x zonePop ]
*
* @param pop
- * @param date
+ * @param step
* @param matrixFishingMortality
* @return
* @throws TopiaException
* @throws IsisFishException
*/
public MatrixND matrixCatchRatePerStrategyMetPerZone(Population pop,
- Date date, MatrixND matrixFishingMortality) throws TopiaException,
+ TimeStep step, MatrixND matrixFishingMortality) throws TopiaException,
IsisFishException {
- List<Strategy> strategies = getStrategies(date);
- List<Metier> metiers = getMetiers(date);
+ List<Strategy> strategies = getStrategies(step);
+ List<Metier> metiers = getMetiers(step);
List<PopulationGroup> groups = pop.getPopulationGroup();
List<Zone> zones = pop.getPopulationZone();
@@ -419,17 +416,17 @@
// Optimisation Hilaire
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = getMetiers(str, date);
+ metiers = getMetiers(str, step);
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);
+ double effort = effortPerZonePop(str, metier, step, 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);
+ step, group, zone, matrixFishingMortality);
result.setValue(str, metier, group, zone, value);
}
}
@@ -442,18 +439,18 @@
/**
* @param str
* @param metier
- * @param date
+ * @param step
* @param zone
* @return
*/
- private double effortPerZonePop(Strategy str, Metier metier, Date date,
+ private double effortPerZonePop(Strategy str, Metier metier, TimeStep step,
Zone zonePop) {
- Month month = date.getMonth();
+ Month month = step.getMonth();
Collection<Zone> zoneMet = metier.getMetierSeasonInfo(month).getZone();
double inter = nbCellInter(zoneMet, zonePop);
double effortPerStrategyPerCell = effortPerStrategyPerCell(str, metier,
- date);
+ step);
if (log.isDebugEnabled()) {
log.debug(" strategy=" + str + " metier=" + metier + " inter="
@@ -467,10 +464,10 @@
// Optimisation Hilaire
private double catchRatePerStrategyMet(Strategy str, Metier metier,
- Date date, PopulationGroup group, Zone zone,
+ TimeStep step, PopulationGroup group, Zone zone,
MatrixND matrixFishingMortality) throws TopiaException,
IsisFishException {
- double totalFishingMortality = totalFishingMortality(date,
+ double totalFishingMortality = totalFishingMortality(step,
matrixFishingMortality).getValue(group, zone);
if (totalFishingMortality == 0) {
@@ -483,7 +480,7 @@
double fishingMortality = matrixFishingMortality.getValue(str, metier,
group, zone);
- double totalCatchRate = totalCatchRate(date, group, zone,
+ double totalCatchRate = totalCatchRate(step, group, zone,
totalFishingMortality);
if (log.isDebugEnabled()) {
@@ -498,14 +495,14 @@
}
/**
- * @param date
+ * @param step
* @param group
* @param zone
* @param totalFishingMortality
* @return
* @throws TopiaException
*/
- private double totalCatchRate(Date date, PopulationGroup group, Zone zone,
+ private double totalCatchRate(TimeStep step, PopulationGroup group, Zone zone,
double totalFishingMortality) throws TopiaException {
double M = group.getNaturalDeathRate(zone) / Month.NUMBER_OF_MONTH;
if (M == 0) {
@@ -528,13 +525,13 @@
* Returne une matrice de mortalite group x zone, donc somme sur str et
* metier
*
- * @param date
+ * @param step
* @param matrixFishingMortality
* @param group
* @param zone
* @return
*/
- private MatrixND totalFishingMortality(Date date,
+ private MatrixND totalFishingMortality(TimeStep step,
MatrixND matrixFishingMortality) {
MatrixND result = matrixFishingMortality.sumOverDim(0);
result = result.sumOverDim(1);
@@ -546,15 +543,15 @@
* Matrice fishing mortality dim [ Strategy x Metier x Classe x zonePop ]
*
* @param pop
- * @param date
+ * @param step
* @return
* @throws TopiaException
* @throws IsisFishException
*/
- public MatrixND matrixFishingMortality(Date date, Population pop)
+ public MatrixND matrixFishingMortality(TimeStep step, Population pop)
throws TopiaException, IsisFishException {
- List<Strategy> strategies = getStrategies(date);
- List<Metier> metiers = getMetiers(date);
+ List<Strategy> strategies = getStrategies(step);
+ List<Metier> metiers = getMetiers(step);
List<PopulationGroup> groups = pop.getPopulationGroup();
List<Zone> zones = pop.getPopulationZone();
@@ -565,7 +562,7 @@
new String[] { n_("Strategies"), n_("Metiers"), n_("Groups"),
n_("Zones") });
- Month month = date.getMonth();
+ Month month = step.getMonth();
PopulationSeasonInfo infoPop = pop.getPopulationSeasonInfo(month);
for (int g = 0; g < groups.size(); g++) {
@@ -600,7 +597,7 @@
for (int z = 0; z < zones.size(); z++) {
Zone zone = zones.get(z);
double effort = effortPerZonePop(str,
- metier, date, zone);
+ metier, step, zone);
if (effort > 0) { // put value only if <> 0
double value = coeff
* capturability * ciblage
@@ -625,20 +622,20 @@
* @param N
* l'abondance sous forme de matrice 2D [class x zone]
* @param pop
- * @param date
+ * @param step
* @return
* @throws TopiaException
* @throws IsisFishException
*/
private MatrixND matrixCatchPerStrategyMetPerCell(MatrixND N,
- Population pop, Date date,
+ Population pop, TimeStep step,
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 matrixCatchRatePerStrategyMet = matrixCatchRatePerStrategyMet(pop, step);
MatrixND result = matrixCatchRatePerStrategyMetPerCell.copy();
result.setName("matrixCatchPerStrategyMetPerCell");
@@ -657,16 +654,16 @@
* Matrice des captures en poids dim [ Strategy x Metier x Classe x zonePop ]
*
* @param pop
- * @param date
+ * @param step
* @return
* @throws TopiaException
* @throws IsisFishException
*/
private MatrixND matrixCatchRatePerStrategyMetPerCell(Population pop,
- Date date, MatrixND matrixFishingMortalityPerCell)
+ TimeStep step, MatrixND matrixFishingMortalityPerCell)
throws TopiaException, IsisFishException {
- List<Strategy> strategies = getStrategies(date);
- List<Metier> metiers = getMetiers(date);
+ List<Strategy> strategies = getStrategies(step);
+ List<Metier> metiers = getMetiers(step);
List<PopulationGroup> groups = pop.getPopulationGroup();
List<Zone> zones = pop.getPopulationZone();
List<Cell> cells = getCells(zones);
@@ -685,7 +682,7 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = getMetiers(str, date);
+ metiers = getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
for (int z = 0; z < zones.size(); z++) {
@@ -699,7 +696,7 @@
for (int g = 0; g < groups.size(); g++) {
PopulationGroup group = groups.get(g);
double value = catchRatePerStrategyMetPerCell(
- str, metier, date, group, zone, cell,
+ str, metier, step, group, zone, cell,
matrixFishingMortalityPerCell);
result.setValue(new Object[] { str, metier,
group, zone, cell }, value);
@@ -720,7 +717,7 @@
*
* @param str
* @param metier
- * @param date
+ * @param step
* @param group
* @param zone
* @param cell
@@ -730,12 +727,12 @@
* @throws IsisFishException
*/
private double catchRatePerStrategyMetPerCell(Strategy str, Metier metier,
- Date date, PopulationGroup group, Zone zone, Cell cell,
+ TimeStep step, PopulationGroup group, Zone zone, Cell cell,
MatrixND matrixFishingMortalityPerCell) throws TopiaException,
IsisFishException {
MatrixND totalFishingMortalityPerCell = totalFishingMortalityPerCell(
- date, matrixFishingMortalityPerCell);
+ step, matrixFishingMortalityPerCell);
double totalFishingMortality = totalFishingMortalityPerCell.getValue(
group, zone, cell);
@@ -749,7 +746,7 @@
double fishingMortalityPerCell = matrixFishingMortalityPerCell
.getValue(new Object[] { str, metier, group, zone, cell });
- double totalCatchRatePerCell = totalCatchRatePerCell(date, group, zone,
+ double totalCatchRatePerCell = totalCatchRatePerCell(step, group, zone,
totalFishingMortality);
if (log.isDebugEnabled()) {
@@ -764,14 +761,14 @@
}
/**
- * @param date
+ * @param step
* @param group
* @param zone
* @param totalFishingMortality
* @return
* @throws TopiaException
*/
- private double totalCatchRatePerCell(Date date, PopulationGroup group,
+ private double totalCatchRatePerCell(TimeStep step, PopulationGroup group,
Zone zone, double totalFishingMortalityPerCell)
throws TopiaException {
double M = group.getNaturalDeathRate(zone) / Month.NUMBER_OF_MONTH;
@@ -795,13 +792,13 @@
* Returne une matrice de mortalite group x zone, donc somme sur str et
* metier
*
- * @param date
+ * @param step
* @param matrixFishingMortality
* @param group
* @param zone
* @return
*/
- private MatrixND totalFishingMortalityPerCell(Date date,
+ private MatrixND totalFishingMortalityPerCell(TimeStep step,
MatrixND matrixFishingMortalityPerCell) {
MatrixND result = matrixFishingMortalityPerCell.sumOverDim(0);
result = result.sumOverDim(1);
@@ -816,15 +813,15 @@
* Nouvelle implantation suite a demande Steph et Sigrid: 20080208 (NouvellesEquationsfev2008ParCelluleAvecAlgo.odt)
*
* @param pop
- * @param date
+ * @param step
* @return
* @throws TopiaException
* @throws IsisFishException
*/
- public MatrixND matrixFishingMortalityPerCell(Date date, Population pop)
+ public MatrixND matrixFishingMortalityPerCell(TimeStep step, Population pop)
throws TopiaException, IsisFishException {
- List<Strategy> strategies = getStrategies(date);
- List<Metier> metiers = getMetiers(date);
+ List<Strategy> strategies = getStrategies(step);
+ List<Metier> metiers = getMetiers(step);
List<PopulationGroup> groups = pop.getPopulationGroup();
List<Zone> zones = pop.getPopulationZone();
List<Cell> cells = getCells(zones);
@@ -836,7 +833,7 @@
new String[] { n_("Strategies"), n_("Metiers"), n_("Groups"),
n_("Zones"), n_("Cells") });
- Month month = date.getMonth();
+ Month month = step.getMonth();
PopulationSeasonInfo infoPop = pop.getPopulationSeasonInfo(month);
for (int g = 0; g < groups.size(); g++) {
@@ -868,7 +865,7 @@
Strategy str = strategies.get(s);
// l'effort d'une cellule du metier
double effort = effortPerStrategyPerCell(
- str, metier, date);
+ str, metier, step);
if (effort > 0) { // put value only if <> 0
for (int z = 0; z < zones.size(); z++) {
Zone zone = zones.get(z);
@@ -900,12 +897,12 @@
/**
* @param str
* @param metier
- * @param date
+ * @param step
* @return
*/
private double effortPerStrategyPerCell(Strategy str, Metier metier,
- Date date) {
- Month month = date.getMonth();
+ TimeStep step) {
+ Month month = step.getMonth();
//StrategyMonthInfo smi = str.getStrategyMonthInfo(month);
Collection<Zone> zones = metier.getMetierSeasonInfo(month).getZone();
double nbCell = getCells(zones).size();
@@ -920,7 +917,7 @@
return 0;
}
- double effortPerStrategy = effortPerStrategyMet(str, metier, date);
+ double effortPerStrategy = effortPerStrategyMet(str, metier, step);
if (log.isDebugEnabled()) {
log.debug(" strategy=" + str + " metier=" + metier + " nbCell="
@@ -935,17 +932,17 @@
/**
* @param str
* @param metier
- * @param date
+ * @param step
* @return
*/
- private double effortNominalPerStrategyMet(Strategy str, Metier metier, Date date) {
- Month month = date.getMonth();
+ private double effortNominalPerStrategyMet(Strategy str, Metier metier, TimeStep step) {
+ Month month = step.getMonth();
StrategyMonthInfo smi = str.getStrategyMonthInfo(month);
double propSetOfVessels = str.getProportionSetOfVessels();
int nbOfVessels = str.getSetOfVessels().getNumberOfVessels();
double propStrMet = smi.getProportionMetier(metier);
- double effortNominalPerVessel = effortNominalPerStrategyPerVessel(str, metier, date);
+ double effortNominalPerVessel = effortNominalPerStrategyPerVessel(str, metier, step);
if(log.isDebugEnabled()) {
log.debug(
@@ -966,14 +963,14 @@
/**
* @param str
* @param metier
- * @param date
+ * @param step
* @return
*/
- private double effortNominalPerStrategyPerVessel(Strategy str, Metier metier, Date date) {
- Month month = date.getMonth();
+ private double effortNominalPerStrategyPerVessel(Strategy str, Metier metier, TimeStep step) {
+ Month month = step.getMonth();
StrategyMonthInfo smi = str.getStrategyMonthInfo(month);
double nbTrips = smi.getNumberOfTrips();
- double fishingTime = fishingTimePerTrip(str, metier, date);
+ double fishingTime = fishingTimePerTrip(str, metier, step);
if(log.isDebugEnabled()) {
@@ -995,17 +992,17 @@
/**
* @param str
* @param metier
- * @param date
+ * @param step
* @return
*/
- private double effortPerStrategyMet(Strategy str, Metier metier, Date date) {
- Month month = date.getMonth();
+ private double effortPerStrategyMet(Strategy str, Metier metier, TimeStep step) {
+ Month month = step.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);
+ double effortPerVessel = effortPerStrategyPerVessel(str, metier, step);
if (log.isDebugEnabled()) {
log.debug(" strategy=" + str + " metier=" + metier
@@ -1023,16 +1020,16 @@
/**
* @param str
* @param metier
- * @param date
+ * @param step
* @return
*/
private double effortPerStrategyPerVessel(Strategy str, Metier metier,
- Date date) {
- Month month = date.getMonth();
+ TimeStep step) {
+ Month month = step.getMonth();
StrategyMonthInfo smi = str.getStrategyMonthInfo(month);
double nbTrips = smi.getNumberOfTrips();
- double fishingTime = fishingTimePerTrip(str, metier, date);
- double stdEffortPerHour = stdEffortPerHour(date, str.getSetOfVessels(),
+ double fishingTime = fishingTimePerTrip(str, metier, step);
+ double stdEffortPerHour = stdEffortPerHour(step, str.getSetOfVessels(),
metier);
if (log.isDebugEnabled()) {
@@ -1051,11 +1048,11 @@
*
* @param str
* @param metier
- * @param date
+ * @param step
* @return
*/
- protected double fishingTimePerTrip(Strategy str, Metier metier, Date date) {
- Month month = date.getMonth();
+ protected double fishingTimePerTrip(Strategy str, Metier metier, TimeStep step) {
+ Month month = step.getMonth();
StrategyMonthInfo smi = str.getStrategyMonthInfo(month);
Collection<Zone> zone = metier.getMetierSeasonInfo(month).getZone();
@@ -1190,12 +1187,12 @@
* @param metier
* @return
*/
- private double stdEffortPerHour(Date date, SetOfVessels sov, Metier metier) {
+ private double stdEffortPerHour(TimeStep step, 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 etp = sov.getTechnicalEfficiency(metier);
double val = fstd * etp * ed.getFishingOperation()
* ed.getGearsNumberPerOperation();
result = val;
@@ -1242,13 +1239,13 @@
/**
* @param N
* @param pop
- * @param date
+ * @param step
* @return
* @throws IsisFishException
* @throws TopiaException
*/
private MatrixND matrixAbundancePerCell(MatrixND N, Population pop,
- Date date, MatrixND matrixFishingMortality) throws TopiaException,
+ TimeStep step, MatrixND matrixFishingMortality) throws TopiaException,
IsisFishException {
List<PopulationGroup> groups = pop.getPopulationGroup();
@@ -1267,7 +1264,7 @@
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,
+ double value = survivalRatePerCell(step, group, zone, cell,
matrixFishingMortality);
double n = N.getValue(g, z) / zone.sizeCell();
value *= n;
@@ -1284,18 +1281,18 @@
*
* @param N
* @param pop
- * @param date
+ * @param step
* @return
* @throws IsisFishException
* @throws TopiaException
*/
- public MatrixND matrixAbundance(MatrixND N, Population pop, Date date)
+ public MatrixND matrixAbundance(MatrixND N, Population pop, TimeStep step)
throws TopiaException, IsisFishException {
MatrixND matrixFishingMortalityPerCell = matrixFishingMortalityPerCell(
- date, pop);
+ step, pop);
- MatrixND result = matrixAbundancePerCell(N, pop, date,
+ MatrixND result = matrixAbundancePerCell(N, pop, step,
matrixFishingMortalityPerCell);
result = result.sumOverDim(2);
result = result.reduceDims(2);
@@ -1309,13 +1306,13 @@
*
* @param N
* @param pop
- * @param date
+ * @param step
* @param matrixFishingMortality
* @return
* @throws IsisFishException
* @throws TopiaException
*/
- public MatrixND matrixAbundance(MatrixND N, Population pop, Date date,
+ public MatrixND matrixAbundance(MatrixND N, Population pop, TimeStep step,
MatrixND matrixFishingMortality) throws TopiaException,
IsisFishException {
List<PopulationGroup> groups = pop.getPopulationGroup();
@@ -1329,7 +1326,7 @@
PopulationGroup group = groups.get(g);
for (int z = 0; z < zones.size(); z++) {
Zone zone = zones.get(z);
- double value = survivalRatePerZone(date, group, zone,
+ double value = survivalRatePerZone(step, group, zone,
matrixFishingMortality);
double n = N.getValue(g, z);
value *= n;
@@ -1346,12 +1343,12 @@
*
* @param N
* @param pop
- * @param date
+ * @param step
* @return
* @throws IsisFishException
* @throws TopiaException
*/
- public MatrixND matrixAbundanceSsF(MatrixND N, Population pop, Date date)
+ public MatrixND matrixAbundanceSsF(MatrixND N, Population pop, TimeStep step)
throws TopiaException, IsisFishException {
List<PopulationGroup> groups = pop.getPopulationGroup();
List<Zone> zones = pop.getPopulationZone();
@@ -1378,18 +1375,18 @@
}
/**
- * @param date
+ * @param step
* @param group
* @param zone
* @return
* @throws IsisFishException
* @throws TopiaException
*/
- private double survivalRatePerZone(Date date, PopulationGroup group,
+ private double survivalRatePerZone(TimeStep step, 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 F = totalFishingMortality(step, matrixFishingMortality)
+ .getValue(group, zone); //totalFishingMortality(step, 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));
@@ -1398,19 +1395,19 @@
}
/**
- * @param date
+ * @param step
* @param group
* @param zone
* @return
* @throws IsisFishException
* @throws TopiaException
*/
- private double survivalRatePerCell(Date date, PopulationGroup group,
+ private double survivalRatePerCell(TimeStep step, 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 F = totalFishingMortalityPerCell(step,
+ matrixFishingMortalityPerCell).getValue(group, zone, cell); //totalFishingMortality(step, 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));
@@ -1427,12 +1424,12 @@
/**
* @param N
* @param pop
- * @param date
+ * @param step
* @return
*/
- public MatrixND matrixBiomass(MatrixND N, Population pop, Date date) {
- List<PopulationGroup> groups = (List<PopulationGroup>)N.getSemantics(0);
- List<Zone> zones = (List<Zone>)N.getSemantics(1);
+ public MatrixND matrixBiomass(MatrixND N, Population pop, TimeStep step) {
+ List<PopulationGroup> groups = (List<PopulationGroup>)N.getSemantic(0);
+ List<Zone> zones = (List<Zone>)N.getSemantic(1);
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_BIOMASS, new List[] { groups, zones },
@@ -1453,9 +1450,9 @@
}
public MatrixND matrixBiomassBeginMonth(MatrixND N, Population pop,
- Date date) {
- List<PopulationGroup> groups = (List<PopulationGroup>)N.getSemantics(0);
- List<Zone> zones = (List<Zone>)N.getSemantics(1);
+ TimeStep step) {
+ List<PopulationGroup> groups = (List<PopulationGroup>)N.getSemantic(0);
+ List<Zone> zones = (List<Zone>)N.getSemantic(1);
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_BIOMASS_BEGIN_MONTH, new List[] { groups, zones },
@@ -1475,9 +1472,9 @@
}
public MatrixND matrixAbondanceBeginMonth(MatrixND N, Population pop,
- Date date) {
- List<PopulationGroup> groups = (List<PopulationGroup>)N.getSemantics(0);
- List<Zone> zones = (List<Zone>)N.getSemantics(1);
+ TimeStep step) {
+ List<PopulationGroup> groups = (List<PopulationGroup>)N.getSemantic(0);
+ List<Zone> zones = (List<Zone>)N.getSemantic(1);
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_ABUNDANCE_BEGIN_MONTH, new List[] { groups, zones },
@@ -1501,13 +1498,13 @@
///////////////////////////////////////////////////////////////////////////
/**
- * @param date
+ * @param step
* @return
* @throws TopiaException
*/
- public MatrixND matrixEffortPerStrategyMet(Date date) throws TopiaException {
- List<Strategy> strategies = getStrategies(date);
- List<Metier> metiers = getMetiers(date);
+ public MatrixND matrixEffortPerStrategyMet(TimeStep step) throws TopiaException {
+ List<Strategy> strategies = getStrategies(step);
+ List<Metier> metiers = getMetiers(step);
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_EFFORT_PER_STRATEGY_MET,
@@ -1516,10 +1513,10 @@
for (int s = 0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = getMetiers(str, date);
+ metiers = getMetiers(str, step);
for (int m = 0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
- double value = effortPerStrategyMet(str, metier, date);
+ double value = effortPerStrategyMet(str, metier, step);
result.setValue(str, metier, value);
}
}
@@ -1537,12 +1534,12 @@
*
*
* @param pop
- * @param date
+ * @param step
* @param matrixDiscardPerStrategyMetPerZonePop
* @return
*/
public MatrixND matrixDiscardWeightPerStrategyMetPerZonePop(Population pop,
- Date date, MatrixND matrixDiscardPerStrategyMetPerZonePop) {
+ TimeStep step, MatrixND matrixDiscardPerStrategyMetPerZonePop) {
List<PopulationGroup> groups = pop.getPopulationGroup();
MatrixND result = matrixDiscardPerStrategyMetPerZonePop.copy();
@@ -1562,10 +1559,10 @@
//
//
///////////////////////////////////////////////////////////////////////////
- public MatrixND matrixEffortNominalPerStrategyMet(Date date) throws TopiaException {
+ public MatrixND matrixEffortNominalPerStrategyMet(TimeStep step) throws TopiaException {
- List<Strategy> strategies = getStrategies(date);
- List<Metier> metiers = getMetiers(date);
+ List<Strategy> strategies = getStrategies(step);
+ List<Metier> metiers = getMetiers(step);
MatrixND result = MatrixFactory.getInstance().create(
ResultName.MATRIX_EFFORT_NOMINAL_PER_STRATEGY_MET,
@@ -1574,10 +1571,10 @@
for (int s=0; s < strategies.size(); s++) {
Strategy str = strategies.get(s);
- metiers = getMetiers(str, date);
+ metiers = getMetiers(str, step);
for (int m=0; m < metiers.size(); m++) {
Metier metier = metiers.get(m);
- double value = effortNominalPerStrategyMet(str, metier, date);
+ double value = effortNominalPerStrategyMet(str, metier, step);
result.setValue(str, metier, value);
}
}
Deleted: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorJavaExpandGrid.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivity/SensitivityCalculatorJavaExpandGrid.java 2011-06-14 13:21:14 UTC (rev 3392)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorJavaExpandGrid.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,630 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-
-package sensitivity;
-
-import java.io.File;
-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.RProxy;
-import org.codelutin.util.FileUtil;
-
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.simulator.SimulationParameter;
-import fr.ifremer.isisfish.simulator.sensitivity.AbstractSensitivityCalculator;
-import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan;
-import fr.ifremer.isisfish.simulator.sensitivity.Factor;
-import fr.ifremer.isisfish.simulator.sensitivity.Scenario;
-import fr.ifremer.isisfish.simulator.sensitivity.SensitivityException;
-import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.DiscreteDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.EquationContinuousDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.MatrixContinuousDomain;
-import fr.ifremer.isisfish.util.Doc;
-
-/**
- * Implementation of ExpandGrid method using Java
- *
- * @author jcouteau
- * @version $Revision$
- *
- */
-public class SensitivityCalculatorJavaExpandGrid extends
- AbstractSensitivityCalculator {
-
- /** to use log facility, just put in your code: log.info("..."); */
- static private Log log = LogFactory
- .getLog(SensitivityCalculatorJavaExpandGrid.class);
-
- @Doc("Interaction order")
- public int param_order = 2;
-
- /**
- * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
- * continue.
- *
- * @return <tt>true</tt> s'il sait la gerer
- */
- @Override
- public boolean canManageCardinality() {
- return false;
- }
-
- @Override
- public SensitivityScenarios compute(DesignPlan plan, File outputdirectory)
- throws SensitivityException {
-
- setIsisFactorsR(plan, outputdirectory);
-
- int k = 1; //number of sensitivity scenarios (initialization)
- int factorNumber = plan.getFactors().size(); //number of factors
- List<Factor<?, ?>> factors = plan.getFactors(); //list of factors
-
- for (int i = 0; i < factorNumber; i++) {
- if (factors.get(i).getDomain() instanceof ContinuousDomain) {
- if (((ContinuousDomain) factors.get(i).getDomain())
- .getCardinality() != 0) {
- k = k
- * ((ContinuousDomain) factors.get(i).getDomain())
- .getCardinality();
- }
- } else if (factors.get(i).getDomain() instanceof DiscreteDomain) {
- if (((DiscreteDomain) factors.get(i).getDomain()).getValues()
- .size() != 0) {
- k = k
- * ((DiscreteDomain) factors.get(i).getDomain())
- .getValues().size();
- }
- }
- }
-
- SensitivityScenarios thisExperiment = new SensitivityScenarios();
- List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
-
- for (int i = 0; i < k; i++) {
- int result = 0; //used for the euclidian division
- int rest = i; //used for the euclidian division
- Scenario experimentScenario = new Scenario();
- for (int j = 0; j < factorNumber; j++) {
- Factor factor = factors.get(j);
- if (factor.getDomain() instanceof ContinuousDomain) {
- Double max = ((ContinuousDomain) factor.getDomain())
- .getMaxBound();
- Double min = ((ContinuousDomain) factor.getDomain())
- .getMinBound();
- int card = ((ContinuousDomain) factor.getDomain())
- .getCardinality();
- result = (int) Math.floor(rest / card);
- rest = rest - (card * result);
-
- Double value = min + ((max - min) / (card - 1) * rest);
- if ((factor.getDomain() instanceof MatrixContinuousDomain)
- || (factor.getDomain() instanceof EquationContinuousDomain)) {
- factor.setValueForIdentifier(value);
- } else {
- factor.setValueForIdentifier(value);
- }
- }
- if (factor.getDomain() instanceof DiscreteDomain) {
- int card = ((DiscreteDomain) factor.getDomain())
- .getValues().size();
- result = (int) Math.floor(rest / card);
- rest = rest - (card * result);
- factor.setValueForIdentifier(rest);
- }
- rest = result;
- experimentScenario.addFactor(factor);
- }
- thisExperimentScenarios.add(experimentScenario);
-
- }
- thisExperiment.setScenarios(thisExperimentScenarios);
-
- thisExperimentScenarios = thisExperiment.getScenarios();
-
- /*
- * Call R to save the data for result analysis
- */
- int scenariosNumber = thisExperimentScenarios.size();
-
- REngine engine = new RProxy();
- try {
-
- //Clear session
- log.info("rm(list=ls())");
- engine.voidEval("rm(list=ls())");
-
- //Set working directory to get Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- //Get Isis R session
- log.info("load(\"" + outputdirectory.getName() + ".RData\")");
- engine
- .voidEval("load(\"" + outputdirectory.getName()
- + ".RData\")");
-
- String dataframe = "data<-data.frame(";
-
- //Create the factors vectors and the dataframe instruction
- for (int j = 0; j < factorNumber; j++) {
- Factor factor = thisExperimentScenarios.get(0).getFactors()
- .get(j);
- if (factor.getDomain() instanceof EquationContinuousDomain) {
-
- //String vector = "factor" + j + "<-c(";
- String vector = factor.getName().replaceAll(" ", "")
- + "<-c(";
- for (int i = 0; i < scenariosNumber; i++) {
- if (i < (scenariosNumber - 1)) {
- vector = vector
- + ((EquationContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue() + ",";
- } else {
- vector = vector
- + ((EquationContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue();
- }
-
- }
- vector = vector + ")";
- engine.voidEval(vector);
- log.info("Message sent to R : " + vector);
- } else if (factor.getDomain() instanceof MatrixContinuousDomain) {
- //String vector = "factor" + j + "<-c(";
- String vector = factor.getName().replaceAll(" ", "")
- + "<-c(";
- for (int i = 0; i < scenariosNumber; i++) {
- if (i < (scenariosNumber - 1)) {
- vector = vector
- + ((MatrixContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue() + ",";
- } else {
- vector = vector
- + ((MatrixContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue();
- }
-
- }
- vector = vector + ")";
- engine.voidEval(vector);
- log.info("Message sent to R : " + vector);
- } else {
- //String vector = "factor" + j + "<-c(";
- String vector = factor.getName().replaceAll(" ", "")
- + "<-c(";
- for (int i = 0; i < scenariosNumber; i++) {
- if (i < (scenariosNumber - 1)) {
- vector = vector
- + thisExperimentScenarios.get(i)
- .getFactors().get(j).getValue()
- + ",";
- } else {
- vector = vector
- + thisExperimentScenarios.get(i)
- .getFactors().get(j).getValue();
- }
-
- }
- vector = vector + ")";
- engine.voidEval(vector);
- log.info("Message sent to R : " + vector);
- }
-
- if (j < factorNumber - 1) {
- dataframe = dataframe
- + factor.getName().replaceAll(" ", "") + "=factor("
- + factor.getName().replaceAll(" ", "") + "),";
- } else {
- dataframe += factor.getName().replaceAll(" ", "")
- + "=factor(" + factor.getName().replaceAll(" ", "")
- + "))";
- }
-
- }
- engine.voidEval(dataframe);
- log.info("Message sent to R : " + dataframe);
-
- // Creating the factors vector.
- String rInstruction = "factornames<-c(";
- for (int i = 0; i < factorNumber; i++) {
- if (i != (factorNumber - 1)) {
- rInstruction = rInstruction + "\""
- + factors.get(i).getName() + "\",";
- } else {
- rInstruction = rInstruction + "\""
- + factors.get(i).getName() + "\"";
- }
- }
-
- rInstruction += ")";
-
- engine.voidEval(rInstruction);
- log.info("Message sent to R : " + rInstruction);
-
- // Set output directory
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- log.info("Message sent to R : " + "setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- // Export the data.frame object for the second run in a .expandgrid file
- engine.voidEval("write.csv(data,file=\".expandgrid.csv\")");
- log
- .info("Message sent to R : write.csv(data,file=\".expandgrid\")");
-
- // Export the factornames object for the second run in a .factornames file
- engine.voidEval("dput(factornames,file=\".factornames\")");
- log.info("Message sent to R : "
- + "dput(factornames,file=\".factornames\")");
-
- //Create the isis.factor.distribution
- log.info("Message sent to R : "
- + "isis.factor.distribution<-c(0.0)");
- engine.voidEval("isis.factor.distribution<-c(0.0)");
-
- //Create isis.MethodExp
- log
- .info("Message sent to R : "
- + "isis.MethodExp<-list(isis.factor,isis.factor.distribution,call_méthode=\"isis-fish-externeR\")");
- engine
- .voidEval("isis.MethodExp<-list(isis.factor,isis.factor.distribution,call_méthode=\"isis-fish-externeR\")");
-
- log
- .info("Message sent to R : "
- + "attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- //Create isis.Simule
- log.info("Message sent to R : " + "isis.simule<-data.frame(data)");
- engine.voidEval("isis.simule<-data.frame(data)");
-
- log
- .info("Message sent to R : "
- + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : "
- + "names(isis.simule)<-isis.factors[[1]]");
- engine.voidEval("names(isis.simule)<-isis.factors[[1]]");
-
- //Set working directory to save Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- // Save Isis R session
- log.info("save.image(file=\"" + outputdirectory.getName() + ".RData\")");
- engine.voidEval("save.image(file=\"" + outputdirectory.getName()
- + ".RData\")");
-
- engine.terminate();
-
- } catch (Exception e) {
- e.printStackTrace();
- // Error while processing
- }
-
- return thisExperiment;
- }
-
- @Override
- public void analyzeResult(List<SimulationStorage> simulationStorages,
- File outputdirectory) throws SensitivityException {
-
- REngine engine = new RProxy();
- try {
-
- //Clear session
- log.info("rm(list=ls())");
- engine.voidEval("rm(list=ls())");
-
- //Set working directory to get Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- //Get Isis R session
- log.info("load(\"" + outputdirectory.getName() + ".RData\")");
- engine
- .voidEval("load(\"" + outputdirectory.getName()
- + ".RData\")");
-
- // Set output directory
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- log.info("Message sent to R : setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- //Get back the scenarios
- engine.voidEval("factors<-read.csv(\".expandgrid.csv\")");
- log
- .info("Message sent to R : factors<-read.csv(\".expandgrid.csv\")");
-
- // Get the factornames object in the .factornames file
- engine.voidEval("factornames<-dget(\".factornames\")");
- log.info("Message sent to R : "
- + "factornames<-dget(\".factornames\")");
-
- //Get back the factors number
- int factorNumber = ((Double) engine.eval("length(factors)-1"))
- .intValue();
-
- SimulationParameter param = simulationStorages.get(0)
- .getParameter();
- int sensitivityNumber = param.getSensitivityExport().size();
-
- for (int k = 0; k < sensitivityNumber; k++) {
-
- // Creates the R expression to import results in R
- String name = param.getSensitivityExport().get(k)
- .getExportFilename();
- String rInstruction = name + "<-c(";
- for (int l = 0; l < simulationStorages.size(); l++) {
- File importFile = new File(simulationStorages.get(l)
- .getDirectory().toString()
- + File.separator
- + SimulationStorage.RESULT_EXPORT_DIRECTORY, param
- .getSensitivityExport().get(k).getExportFilename()
- + param.getSensitivityExport().get(k)
- .getExtensionFilename());
- String simulResult = FileUtil.readAsString(importFile);
- double simulationResult = Double.valueOf(simulResult);
- if (l < simulationStorages.size() - 1) {
- rInstruction = rInstruction + simulationResult + ",";
- } else {
- rInstruction = rInstruction + simulationResult;
- }
- }
- rInstruction = rInstruction + ")";
-
- log.info("Message sent to R : " + rInstruction);
-
- // Send the simulation results
- engine.voidEval(rInstruction);
-
- //Put results in isis.simule
- engine.voidEval("isis.simule<-data.frame(isis.simule," + name
- + ")");
- log.info("Message sent to R : "
- + "isis.simule<-data.frame(isis.simule," + name + ")");
-
- //Create the dataforaov data.frame
- String dataframe = "dataforaov<-data.frame(factors," + name
- + "=" + name + ")";
- engine.voidEval(dataframe);
- log.info("Message sent to R : " + dataframe);
-
- //Call aov()
- String aovCall = "aovresult<-aov(" + name + "~(";
- for (int j = 0; j < factorNumber; j++) {
- log.info("Message sent to R : " + "names(factors)["
- + (j + 2) + "]");
-
- if (j < (factorNumber - 1)) {
- aovCall = aovCall
- + engine
- .eval("names(factors)[" + (j + 2) + "]")
- + "+";
- } else {
- aovCall = aovCall
- + engine
- .eval("names(factors)[" + (j + 2) + "]")
- + ")";
- if(param_order>1){
- aovCall+="^" + param_order + ",data=dataforaov)";
- }else{
- aovCall+=",data=dataforaov)";
- }
- }
- }
- engine.voidEval(aovCall);
- log.info("Message sent to R : " + aovCall);
-
- /*Export the results
- *Export format is csv, data separated by ','
- *Results Export name is sensitivityExportName_Results.csv
- *Sensitivity Indices export name is sensitivityExportName_SensitivityIndices.csv
- */
-
- //Compute Sum of Squares and Sensitivity indices
- engine.voidEval("SoS<-summary(aovresult)[[1]][1:"
- + factorNumber + ",2]");
- log.info("Message sent to R : SoS<-summary(aovresult)[[1]][1:"
- + factorNumber + ",2]");
- engine
- .voidEval("names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:"
- + factorNumber + "]");
- log
- .info("Message sent to R : names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:"
- + factorNumber + "]");
- engine.voidEval("IndSensibilite<-SoS/sum(SoS)");
- log.info("Message sent to R : IndSensibilite<-SoS/sum(SoS)");
-
- //Create a data.frame to export sensitivity important results in one file.
- engine.voidEval("exportsensitivity=data.frame(SoS[1:"
- + factorNumber + "],IndSensibilite[1:" + factorNumber
- + "])");
- log
- .info("Message sent to R : exportsensitivity=data.frame(SoS[1:"
- + factorNumber
- + "],IndSensibilite[1:"
- + factorNumber + "])");
- engine
- .voidEval("names(exportsensitivity)<-c(\"Sum Of Squares\",\"Sensitivity indices\")");
- log
- .info("Message sent to R : names(exportsensitivity)<-c(\"Sum Of Squares\",\"Sensitivity indices\")");
- engine.voidEval("row.names(exportsensitivity)<-factornames");
- log.info("Message sent to R : "
- + "row.names(exportsensitivity)<-factornames");
-
- //Set dataforaov names
- engine
- .voidEval("resultsnames<-c(\"Simulation\",factornames,\"Result\")");
- log
- .info("Message sent to R : "
- + "resultsnames<-c(\"Simulation\",factornames,\"Result\")");
- engine.voidEval("names(dataforaov)<-resultsnames");
- log.info("Message sent to R : "
- + "names(dataforaov)<-resultsnames");
-
- /*Set the export directory
- *Export directory is the first simulation export directory.
- */
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
- log.info("Message sent to R : setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
-
- //Save the results with the scenarios.
- engine.voidEval("write.csv(dataforaov,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Results.csv\")");
- log.info("Message sent to R : write.csv(dataforaov,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Results.csv\")");
-
- //Save the sensitivity indices
- engine.voidEval("write.csv(exportsensitivity,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename()
- + "_SensitivityIndices.csv\")");
- log.info("Message sent to R : write.csv(exportsensitivity,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename()
- + "_SensitivityIndices.csv\")");
- //FIXME export through java to enable export when using Rserve (when distant Rserve).
-
- //creating isis.methodAnalyse
- log
- .info("Message sent to R : "
- + "isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\""
- + aovCall + "\""
- + ",\"analysis_result\"=list(aovresult,IndSensibilite))");
- engine
- .voidEval("isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\""
- + aovCall
- + "\""
- + ",\"analysis_result\"=list(aovresult,IndSensibilite))");
-
- log
- .info("Message sent to R : "
- + "attr(isis.methodAnalyse,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.methodAnalyse,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- String renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-isis.methodAnalyse";
- String simulationName = simulationStorages.get(0).getName()
- .replaceAll("-", "");
- log.info("Message sent to R : "
- + String.format(renameIsisMethodAnalyse, simulationName
- + "." + name));
- engine.voidEval(String.format(renameIsisMethodAnalyse,
- simulationName + "." + name));
-
- }
-
- //Rename R objects for saving purpose
-
- String renameIsisSimule = "%s.isis.simule<-isis.simule";
- String renameIsisFactorDistribution = "%s.isis.factor.distribution<-isis.factor.distribution";
- String renameIsisFactor = "%s.isis.factor<-isis.factors";
- String renameIsisMethodExp = "%s.isis.methodExp<-isis.MethodExp";
-
- String simulationName = simulationStorages.get(0).getName()
- .replaceAll("-", "");
-
- log.info("Message sent to R : "
- + String.format(renameIsisSimule, simulationName));
- engine.voidEval(String.format(renameIsisSimule, simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisFactorDistribution,
- simulationName));
- engine.voidEval(String.format(renameIsisFactorDistribution,
- simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisFactor, simulationName));
- engine.voidEval(String.format(renameIsisFactor, simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisMethodExp, simulationName));
- engine.voidEval(String.format(renameIsisMethodExp, simulationName));
-
- //Set working directory to save Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- // Save Isis R session
- log.info("save.image(file=\"" + outputdirectory.getName() + ".RData\")");
- engine.voidEval("save.image(file=\"" + outputdirectory.getName()
- + ".RData\")");
-
- engine.terminate();
-
- } catch (Exception e) {
- e.printStackTrace();
- // Error while processing
- }
-
- }
-
- @Override
- public String getDescription() {
- return "Implementation of Expand Grid method using Java";
- }
-
-}
Copied: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorJavaExpandGrid.java (from rev 3393, isis-fish/trunk/src/test/resources/test-database/sensitivity/SensitivityCalculatorJavaExpandGrid.java)
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorJavaExpandGrid.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorJavaExpandGrid.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -0,0 +1,386 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+
+package sensitivityanalysis;
+
+import java.io.File;
+import java.util.List;
+
+import fr.ifremer.isisfish.export.SensitivityExport;
+import fr.ifremer.isisfish.simulator.sensitivity.*;
+import org.nuiton.j2r.REngine;
+import org.nuiton.j2r.RProxy;
+
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.simulator.SimulationParameter;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.DiscreteDomain;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.EquationContinuousDomain;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.MatrixContinuousDomain;
+import fr.ifremer.isisfish.util.Doc;
+
+/**
+ * Implementation of ExpandGrid method using Java
+ *
+ * @author jcouteau
+ * @version $Revision$
+ *
+ */
+public class SensitivityCalculatorJavaExpandGrid extends
+ AbstractSensitivityAnalysis {
+
+ @Doc("Interaction order")
+ public int param_order = 2;
+
+ /**
+ * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
+ * continue.
+ *
+ * @return <tt>true</tt> s'il sait la gerer
+ */
+ @Override
+ public boolean canManageCardinality() {
+ return false;
+ }
+
+ @Override
+ public SensitivityScenarios compute(DesignPlan plan, File outputDirectory)
+ throws SensitivityException {
+
+ setIsisFactorsR(plan, outputDirectory);
+
+ int k = 1; //number of sensitivity scenarios (initialization)
+ int factorNumber = plan.getFactors().size(); //number of factors
+ List<Factor> factors = plan.getFactors(); //list of factors
+
+ for (int i = 0; i < factorNumber; i++) {
+ Domain domain = factors.get(i).getDomain();
+
+ //calculate the number of scenarios
+ if (domain instanceof ContinuousDomain) {
+ ContinuousDomain contDomain = (ContinuousDomain)domain;
+ if (contDomain.getCardinality() != 0) {
+ k = k * contDomain.getCardinality();
+ }
+ } else if (domain instanceof DiscreteDomain) {
+ DiscreteDomain discreteDomain = (DiscreteDomain)domain;
+ if (discreteDomain.getValues().size() != 0) {
+ k = k * discreteDomain.getValues().size();
+ }
+ }
+ }
+
+ SensitivityScenarios thisExperiment = new SensitivityScenarios();
+ List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
+
+ for (int i = 0; i < k; i++) {
+ int result = 0; //used for the euclidian division
+ int rest = i; //used for the euclidian division
+ Scenario experimentScenario = new Scenario();
+ for (int j = 0; j < factorNumber; j++) {
+ Factor factor = factors.get(j);
+ Domain domain = factor.getDomain();
+ if (domain instanceof ContinuousDomain) {
+ ContinuousDomain continuousDomain = (ContinuousDomain)domain;
+ Double max = continuousDomain.getCalculatorMaxBound();
+ Double min = continuousDomain.getCalculatorMinBound();
+ int card = continuousDomain.getCardinality();
+
+ //Do the euclidian division
+ result = (int) Math.floor(rest / card);
+ rest = rest - (card * result);
+
+ //Calculate the value of the factor
+ Double value = min + ((max - min) / (card - 1) * rest);
+ if ((domain instanceof MatrixContinuousDomain)
+ || (domain instanceof EquationContinuousDomain)) {
+ factor.setValueForIdentifier(value);
+ } else {
+ factor.setValueForIdentifier(value);
+ }
+ }
+ if (factor.getDomain() instanceof DiscreteDomain) {
+ DiscreteDomain discreteDomain = (DiscreteDomain)domain;
+ int card = discreteDomain.getValues().size();
+
+ //Do the euclidian division
+ result = (int) Math.floor(rest / card);
+ rest = rest - (card * result);
+
+ //Select the value of the factor
+ factor.setValueForIdentifier(rest);
+ }
+ rest = result;
+ experimentScenario.addFactor(factor);
+ }
+ thisExperimentScenarios.add(experimentScenario);
+
+ }
+ thisExperiment.setScenarios(thisExperimentScenarios);
+
+ thisExperimentScenarios = thisExperiment.getScenarios();
+
+ /*
+ * Call R to save the data for result analysis
+ */
+ int scenariosNumber = thisExperimentScenarios.size();
+
+ try {
+
+ REngine engine = new RProxy();
+
+ //Clear session
+ engine.clearSession();
+
+ //Get Isis R session
+ engine.loadRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ String dataframe = "data<-data.frame(";
+
+ //Create the factors vectors and the dataframe instruction
+ for (int j = 0; j < factorNumber; j++) {
+
+ Factor factor = factors.get(j);
+ String factorName = factor.getName().replaceAll(" ", "");
+
+ //String vector = "factor" + j + "<-c(";
+ String vector = factorName + "<-c(";
+ for (int i = 0; i < scenariosNumber; i++) {
+ Scenario scenario = thisExperimentScenarios.get(i);
+ List<Factor> newFactors = scenario.getFactors();
+ Factor factor1 = newFactors.get(j);
+
+ if (i < (scenariosNumber - 1)) {
+ vector += factor1.getDisplayedValue() + ",";
+ } else {
+ vector += factor1.getDisplayedValue();
+ }
+
+ }
+ vector = vector + ")";
+ engine.voidEval(vector);
+
+ if (j < factorNumber - 1) {
+ dataframe += factorName + "=factor(" + factorName + "),";
+ } else {
+ dataframe += factorName + "=factor(" + factorName + "))";
+ }
+
+ }
+ engine.voidEval(dataframe);
+
+ // Creating the factors vector.
+ String rInstruction = "factornames<-c(";
+ for (int i = 0; i < factorNumber; i++) {
+ if (i != (factorNumber - 1)) {
+ rInstruction = rInstruction + "\""
+ + factors.get(i).getName() + "\",";
+ } else {
+ rInstruction = rInstruction + "\""
+ + factors.get(i).getName() + "\"";
+ }
+ }
+
+ rInstruction += ")";
+
+ engine.voidEval(rInstruction);
+
+ //Create the isis.factor.distribution
+ engine.voidEval("isis.factor.distribution<-c(0.0)");
+
+ //Create isis.MethodExp
+ engine.voidEval("isis.MethodExp<-list(" +
+ "isis.factors," +
+ "isis.factor.distribution," +
+ "call_method=\"isis-fish-externeR\")");
+
+ engine.voidEval("attr(isis.MethodExp," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ //Create isis.Simule
+ engine.voidEval("isis.simule<-data.frame(data)");
+
+ engine.voidEval("attr(isis.simule," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ engine.voidEval("names(isis.simule)<-isis.factors[[1]]");
+
+ // Save Isis R session
+ engine.saveRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ engine.terminate();
+
+ } catch (Exception e) {
+ throw new SensitivityException("Can't generate scenarios", e);
+ }
+
+ return thisExperiment;
+ }
+
+ @Override
+ public void analyzeResult(List<SimulationStorage> simulationStorages,
+ File outputdirectory) throws SensitivityException {
+
+ SimulationStorage firstStorage = simulationStorages.get(0);
+ String simulationName = firstStorage.getName().replaceAll("-", "");
+ SimulationParameter param = firstStorage.getParameter();
+ int sensitivityNumber = param.getSensitivityExport().size();
+
+ try {
+
+ REngine engine = new RProxy();
+
+ //Clear session
+ engine.clearSession();
+
+ //Get Isis R session
+ engine.loadRData(outputdirectory.getParentFile(),
+ outputdirectory.getName());
+
+ //Get back the factors number
+ int factorNumber = (Integer)engine.eval("dim(data)[2]");
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ SensitivityExport sensitivityExport =
+ param.getSensitivityExport().get(k);
+
+ String name = sensitivityExport.getExportFilename();
+
+ String rInstruction = createImportInstruction(sensitivityExport,
+ simulationStorages);
+
+ // Send the simulation results
+ engine.voidEval(rInstruction);
+
+ //Put results in isis.simule
+ engine.voidEval("isis.simule<-data.frame(isis.simule,"
+ + name + ")");
+
+ //Create the dataforaov data.frame
+ String dataframe = "dataforaov<-data.frame(data," +
+ name + "=" + name + ")";
+ engine.voidEval(dataframe);
+
+ //Call aov()
+ String aovCall = "aovresult<-aov(" + name + "~(";
+ for (int j = 0; j < factorNumber; j++) {
+ if (j < (factorNumber - 1)) {
+ aovCall = aovCall +
+ engine.eval("names(data)[" + (j + 1) + "]") +
+ "+";
+ } else {
+ aovCall = aovCall +
+ engine.eval("names(data)[" + (j + 1) + "]") +
+ ")";
+ if(param_order>1){
+ aovCall+="^" + param_order + ",data=dataforaov)";
+ }else{
+ aovCall+=",data=dataforaov)";
+ }
+ }
+ }
+ engine.voidEval(aovCall);
+
+ /*Export the results
+ *Export format is csv, data separated by ','
+ *Results Export name is sensitivityExportName_Results.csv
+ *Sensitivity Indices export name is sensitivityExportName_SensitivityIndices.csv
+ */
+
+ //Compute Sum of Squares and Sensitivity indices
+ engine.voidEval("SoS<-summary(aovresult)[[1]][1:dim(summary(aovresult)[[1]])[1],2]");
+ engine.voidEval("names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:dim(summary(aovresult)[[1]])[1]]");
+ engine.voidEval("IndSensibilite<-SoS/sum(SoS)");
+
+ //Create a data.frame to export sensitivity important results in one file.
+ engine.voidEval("exportsensitivity<-data.frame(" +
+ "SoS[1:dim(summary(aovresult)[[1]])[1]]," +
+ "IndSensibilite[1:dim(summary(aovresult)[[1]])[1]])");
+ engine.voidEval("names(exportsensitivity)<-c(" +
+ "\"Sum Of Squares\"," +
+ "\"Sensitivity indices\")");
+ engine.voidEval("row.names(exportsensitivity)<-dimnames(summary(aovresult)[[1]])[1][[1]][1:dim(summary(aovresult)[[1]])[1]]");
+
+
+ //Set dataforaov names
+ engine.voidEval("resultsnames<-c(" +
+ "factornames," +
+ "\"Result\")");
+ engine.voidEval("names(dataforaov)<-resultsnames");
+
+ /*Set the export directory
+ *Export directory is the first simulation export directory.
+ */
+ engine.setwd(outputdirectory);
+
+ //Save the results with the scenarios.
+ engine.voidEval("write.csv(dataforaov,\""
+ + param.getSensitivityExport().get(k).getExportFilename() + "_Results.csv\")");
+
+ //Save the sensitivity indices
+ engine.voidEval("write.csv(exportsensitivity,\""
+ + param.getSensitivityExport().get(k).getExportFilename()
+ + "_SensitivityIndices.csv\")");
+ //FIXME export through java to enable export when using Rserve (when distant Rserve).
+
+ //creating isis.methodAnalyse
+ engine.voidEval("isis.methodAnalyse<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"isis.simule\"=isis.simule," +
+ "call_method=\"" + aovCall + "\"," +
+ "\"analysis_result\"=list(aovresult,IndSensibilite))");
+
+ engine.voidEval("attr(isis.methodAnalyse," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ String renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-" +
+ "isis.methodAnalyse";
+ engine.voidEval(String.format(renameIsisMethodAnalyse,
+ simulationName + "." + name));
+
+ }
+
+ //Rename R objects for saving purpose
+ renameObjects(engine, simulationName);
+
+ // Save Isis R session
+ engine.saveRData(outputdirectory.getParentFile(),
+ outputdirectory.getName());
+
+ engine.terminate();
+
+ } catch (Exception e) {
+ throw new SensitivityException("Can't evaluate results", e);
+ }
+
+ }
+
+ @Override
+ public String getDescription() {
+ return "Implementation of Expand Grid method using Java";
+ }
+
+}
Added: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRDOptimal.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRDOptimal.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRDOptimal.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -0,0 +1,398 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+
+package sensitivityanalysis;
+
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.export.SensitivityExport;
+import fr.ifremer.isisfish.simulator.SimulationParameter;
+import fr.ifremer.isisfish.simulator.sensitivity.*;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.DiscreteDomain;
+import fr.ifremer.isisfish.util.Doc;
+import org.nuiton.j2r.REngine;
+import org.nuiton.j2r.RException;
+import org.nuiton.j2r.RProxy;
+import org.nuiton.j2r.types.RDataFrame;
+
+import java.io.File;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * User: couteau
+ * Date: 14 janv. 2010
+ * Time: 11:58:09
+ */
+public class SensitivityCalculatorRDOptimal
+ extends AbstractSensitivityAnalysis {
+
+ @Doc("True to be able to modify the code sent to R")
+ public boolean param_modifR = false;
+
+ @Doc("Order")
+ public int param_order=1;
+
+ /**
+ * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
+ * continue.
+ *
+ * @return <tt>true</tt> s'il sait la gerer
+ */
+ @Override
+ public boolean canManageCardinality() {
+ return false;
+ }
+
+ @Override
+ public SensitivityScenarios compute(DesignPlan plan, File outputDirectory)
+ throws SensitivityException {
+
+ SensitivityScenarios thisExperiment = new SensitivityScenarios();
+
+ setIsisFactorsR(plan, outputDirectory);
+
+ //extract the factors from the design plan
+ List<Factor> factors = plan.getFactors();
+ int factorsNb = factors.size();
+
+ try {
+ REngine engine = new RProxy();
+
+ //Get Isis R session
+ engine.loadRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ engine.voidEval("library(AlgDesign)");
+
+ //Create a list of the factors under the form factor1=factor1,...
+ String factorsNames = "";
+
+ //Create a list of the factors under the form factor1,factor2,...
+ String factorNames = "";
+
+ //Create a list of the factors under the form factor1+factor2+...
+ String factorPlus="";
+
+ //create the factors vectors
+ for (Factor factor : factors) {
+ //The factor values vector
+ String factorName = factor.getName().replaceAll(" ", "");
+ factorsNames += factorName + "=" + factorName + ",";
+ factorNames += factorName + ",";
+ factorPlus += factorName + "+";
+
+ String vector = factorName + "<-c(";
+
+ Domain domain = factor.getDomain();
+
+ if (domain instanceof ContinuousDomain) {
+ ContinuousDomain contDomain = (ContinuousDomain) domain;
+ int card = contDomain.getCardinality();
+ Double min = contDomain.getCalculatorMinBound();
+ Double max = contDomain.getCalculatorMaxBound();
+
+ for (int i = 0; i < card; i++) {
+ //add the ith value
+ vector += (min + (i * (max - min) / (card - 1))) + ",";
+ }
+ } else {
+ Map<Object, Object> values = ((DiscreteDomain) domain).getValues();
+ int nbValues = values.size();
+ for (int i = 0; i < nbValues; i++) {
+ vector += "as.integer(" + i + "),";
+ }
+ }
+
+ vector = vector.substring(0, vector.length() - 1);
+
+ vector += ")";
+
+ engine.voidEval(vector);
+
+
+ }
+
+ factorsNames = factorsNames.substring(0,factorsNames.length()-1);
+ factorNames = factorNames.substring(0,factorNames.length()-1);
+ factorPlus = factorPlus.substring(0,factorPlus.length()-1);
+
+
+ //X<-expand.grid(vector=???,weight=???)
+ String expandGrid = "expandgrid<-expand.grid(%s)";
+
+
+
+ String rCall = String.format(expandGrid,factorsNames);
+
+ engine.voidEval(rCall);
+
+ if (param_order ==1 ){
+ rCall = "x<-optFederov(~(%s),data=expandgrid, " +
+ "approximate =FALSE, center=F, criterion = \"D\"," +
+ "nRepeats=10)";
+ } else {
+ rCall = "x<-optFederov(~(%s)^"+param_order+",data=expandgrid, " +
+ "approximate =FALSE, center=F, criterion = \"D\"," +
+ "nRepeats=10)";
+ }
+
+ rCall = String.format(rCall,factorPlus);
+
+ if (param_modifR) {
+ rCall = editRInstruction(rCall);
+ }
+
+ engine.voidEval("runif(1)");
+
+ engine.voidEval(rCall);
+
+ engine.eval("expPlan<-as.data.frame(x$design)");
+ RDataFrame dataFrame = (RDataFrame)engine.eval("expPlan");
+ dataFrame.setVariable("expPlan");
+ int nbExperiments = (Integer)engine.eval("dim(x$design)[1]");
+
+ List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
+ for (int j = 0; j < nbExperiments; j++) {
+ Scenario experimentScenario = new Scenario();
+ for (int i = 0; i < factorsNb; i++) {
+ Factor factor = factors.get(i);
+ factor.setValueForIdentifier(dataFrame.get(i, j));
+ experimentScenario.addFactor(factor);
+ }
+ thisExperimentScenarios.add(experimentScenario);
+ thisExperiment.setScenarios(thisExperimentScenarios);
+ }
+
+
+ String factorDistribution = "isis.factor.distribution<-data.frame(" +
+ "NomFacteur=c(%s)," +
+ "NomDistribution=c(%s)," +
+ "ParametreDistribution=c(%s))";
+
+ String distribution = "";
+ String parameters = "";
+
+ for (int i = 0; i < factorsNb; i++) {
+ Domain domain = factors.get(i).getDomain();
+ if (i != 0) {
+ distribution += ",";
+ parameters += ",";
+ }
+ if (domain instanceof ContinuousDomain){
+ ContinuousDomain contDomain = (ContinuousDomain)domain;
+ distribution += "\"qunif\"";
+ parameters += "\"[" + contDomain.getMinBound()
+ + ";" + contDomain.getMaxBound()
+ + "]\"";
+ } else {
+ DiscreteDomain discDomain = (DiscreteDomain)domain;
+ distribution += "\"discrete\"";
+ parameters+="\"[";
+ Map<Object, Object> values = discDomain.getValues();
+ int count=0;
+ Collection<Object> collecValues = values.values();
+ for (Object value:collecValues){
+ if (count!=0){
+ parameters += ",";
+ }
+ parameters += value;
+ count++;
+ }
+ parameters+="]\"";
+ }
+ }
+ engine.voidEval(String.format(factorDistribution, factorNames,
+ distribution, parameters));
+
+ engine.voidEval("call<-\"" + rCall + "\"");
+ engine.voidEval("isis.MethodExp<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"call\"=call)");
+ engine.voidEval("attr(isis.MethodExp," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+ engine.voidEval("isis.simule<-x$design");
+ engine.voidEval("attr(isis.simule," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+ engine.voidEval("names(isis.simule)<-isis.factors[[1]]");
+
+ // Save Isis R session
+ engine.saveRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+
+ } catch (RException eee) {
+ throw new SensitivityException("Can't generate scenarios", eee);
+ }
+
+ return thisExperiment;
+ }
+
+ @Override
+ public void analyzeResult(List<SimulationStorage> simulationStorages,
+ File outputDirectory) throws SensitivityException {
+
+ try {
+
+ REngine engine = new RProxy();
+
+ //Get Isis R session
+ engine.loadRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ //Get back the factors number
+ int factorNumber = (Integer)engine.eval("dim(x$design)[2]");
+
+ SimulationParameter param = simulationStorages.get(0).getParameter();
+ int sensitivityNumber = param.getSensitivityExport().size();
+
+ SimulationStorage firstStorage = simulationStorages.get(0);
+
+ String firstStorageName = firstStorage.getName().replaceAll("-", "");
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ SensitivityExport sensitivityExport =
+ param.getSensitivityExport().get(k);
+
+ String name = sensitivityExport.getExportFilename();
+
+ String rInstruction = createImportInstruction(sensitivityExport,
+ simulationStorages);
+
+ // Send the simulation results
+ engine.voidEval(rInstruction);
+
+ //Put results in isis.simule
+ engine.voidEval("isis.simule<-data.frame(isis.simule,"
+ + name + ")");
+
+ //Create the dataforaov data.frame
+ String dataFrame = "dataforaov<-data.frame(x$design,"
+ + name + "=" + name + ")";
+ engine.voidEval(dataFrame);
+
+ //Call aov()
+ String aovCall = "aovresult<-aov(" + name + "~(";
+ for (int j = 0; j < factorNumber; j++) {
+ if (j < (factorNumber - 1)) {
+ aovCall = aovCall
+ + engine.eval("names(x$design)[" + (j + 1) + "]")
+ + "+";
+ } else {
+ aovCall = aovCall
+ + engine.eval("names(x$design)[" + (j + 1) + "]")
+ + ")";
+ if(param_order>1){
+ aovCall+="^" + param_order + ",data=dataforaov)";
+ }else{
+ aovCall+=",data=dataforaov)";
+ }
+ }
+ }
+ engine.voidEval(aovCall);
+
+ /*Export the results
+ *Export format is csv, data separated by ','
+ *Results Export name is sensitivityExportName_Results.csv
+ *Sensitivity Indices export name is sensitivityExportName_SensitivityIndices.csv
+ */
+
+//Compute Sum of Squares and Sensitivity indices
+ engine.voidEval("SoS<-summary(aovresult)[[1]][1:dim(summary(aovresult)[[1]])[1],2]");
+ engine.voidEval("names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:dim(summary(aovresult)[[1]])[1]]");
+ engine.voidEval("IndSensibilite<-SoS/sum(SoS)");
+
+ //Create a data.frame to export sensitivity important results in one file.
+ engine.voidEval("exportsensitivity<-data.frame(" +
+ "SoS[1:dim(summary(aovresult)[[1]])[1]]," +
+ "IndSensibilite[1:dim(summary(aovresult)[[1]])[1]])");
+ engine.voidEval("names(exportsensitivity)<-c(" +
+ "\"Sum Of Squares\"," +
+ "\"Sensitivity indices\")");
+ engine.voidEval("row.names(exportsensitivity)<-dimnames(summary(aovresult)[[1]])[1][[1]][1:dim(summary(aovresult)[[1]])[1]]");
+
+
+ //Set dataforaov names
+ engine.voidEval("resultsnames<-c(names(x$design),\"Result\")");
+ engine.voidEval("names(dataforaov)<-resultsnames");
+
+
+ /*Set the export directory
+ *Export directory is the first simulation export directory.
+ */
+ engine.setwd(outputDirectory);
+
+ //Save the results with the scenarios.
+ engine.voidEval("write.csv(dataforaov,\""
+ + param.getSensitivityExport().get(k)
+
+ .getExportFilename() + "_Results.csv\")");
+
+ //Save the sensitivity indices
+ engine.voidEval("write.csv(exportsensitivity,\""
+ + param.getSensitivityExport().get(k)
+ .getExportFilename()
+ + "_SensitivityIndices.csv\")");
+ //FIXME export through java to enable export when using Rserve (when distant Rserve).
+
+ //creating isis.methodAnalyse
+ engine.voidEval("isis.methodAnalyse<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"isis.simule\"=isis.simule," +
+ "\"call_method\"=\"" + aovCall + "\"," +
+ "\"analysis_result\"=list(aovresult,IndSensibilite))");
+
+ engine.voidEval("attr(isis.methodAnalyse," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ String renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-isis.methodAnalyse";
+ engine.voidEval(String.format(renameIsisMethodAnalyse,
+ firstStorageName + "." + name));
+
+ }
+
+ //Rename R objects for saving purpose
+
+ renameObjects(engine, firstStorageName);
+
+ //Save Isis R session
+ engine.saveRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ engine.terminate();
+
+ } catch (Exception e) {
+ throw new SensitivityException("Can't evaluate results", e);
+ }
+
+ }
+
+ @Override
+ public String getDescription() {
+ return "Implementation of D optimal method method using R, needs" +
+ "AlgDesign package to work";
+ }
+}
Property changes on: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRDOptimal.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRExpandGrid.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRExpandGrid.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRExpandGrid.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -0,0 +1,368 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+
+package sensitivityanalysis;
+
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.export.SensitivityExport;
+import fr.ifremer.isisfish.simulator.SimulationParameter;
+import fr.ifremer.isisfish.simulator.sensitivity.*;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.DiscreteDomain;
+import fr.ifremer.isisfish.util.Doc;
+import org.nuiton.j2r.REngine;
+import org.nuiton.j2r.RException;
+import org.nuiton.j2r.RProxy;
+import org.nuiton.j2r.types.RDataFrame;
+
+import java.io.File;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * User: couteau
+ * Date: 6 janv. 2010
+ * Time: 14:31:09
+ */
+public class SensitivityCalculatorRExpandGrid
+ extends AbstractSensitivityAnalysis {
+
+ @Doc("Interaction order")
+ public int param_order = 2;
+
+ @Doc("True to be able to modify the code sent to R")
+ public boolean param_modifR = false;
+
+ /**
+ * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
+ * continue.
+ *
+ * @return <tt>true</tt> s'il sait la gerer
+ */
+ @Override
+ public boolean canManageCardinality() {
+ return false;
+ }
+
+ @Override
+ public SensitivityScenarios compute(DesignPlan plan, File outputDirectory)
+ throws SensitivityException {
+
+ SensitivityScenarios thisExperiment = new SensitivityScenarios();
+
+ setIsisFactorsR(plan, outputDirectory);
+
+ //extract the factors from the design plan
+ List<Factor> factors = plan.getFactors();
+ int factorsNb = factors.size();
+
+ try {
+ REngine engine = new RProxy();
+
+ //Get Isis R session
+ engine.loadRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ //Create a list of the factors under the form factor1=factor1,...
+ String factorsNames = "";
+
+ //Create a list of the factors under the form factor1,factor2,...
+ String factorNames = "";
+
+ //create the factors vectors
+ for (Factor factor : factors) {
+ //The factor values vector
+ String factorName = factor.getName().replaceAll(" ", "");
+ factorsNames += factorName + "=" + factorName + ",";
+ factorNames += factorName + ",";
+ String vector = factorName + "<-c(";
+
+ Domain domain = factor.getDomain();
+
+ if (domain instanceof ContinuousDomain) {
+ ContinuousDomain contDomain = (ContinuousDomain) domain;
+ int card = contDomain.getCardinality();
+ Double min = contDomain.getCalculatorMinBound();
+ Double max = contDomain.getCalculatorMaxBound();
+
+ for (int i = 0; i < card; i++) {
+ //add the ith value
+ vector += (min + (i * (max - min) / (card - 1))) + ",";
+ }
+ }
+
+ if (domain instanceof DiscreteDomain) {
+ Map<Object, Object> values = ((DiscreteDomain) domain).getValues();
+ int nbValues = values.size();
+ for (int i = 0; i < nbValues; i++) {
+ vector += "as.integer(" + i + "),";
+ }
+ }
+
+ vector = vector.substring(0, vector.length() - 1);
+
+ vector += ")";
+
+ engine.voidEval(vector);
+
+
+ }
+
+ factorsNames = factorsNames.substring(0,factorsNames.length()-1);
+ factorNames = factorNames.substring(0,factorNames.length()-1);
+
+
+ //X<-expand.grid(vector=???,weight=???)
+ String expandGrid = "x<-expand.grid(%s)";
+
+ String rCall = String.format(expandGrid,factorsNames);
+
+ if (param_modifR) {
+ rCall = editRInstruction(rCall);
+ }
+
+ engine.voidEval(rCall);
+
+ engine.eval("expPlan<-as.data.frame(x)");
+ RDataFrame dataFrame = (RDataFrame)engine.eval("expPlan");
+ dataFrame.setVariable("expPlan");
+ int nbExperiments = (Integer)engine.eval("dim(x)[1]");
+
+ List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
+ for (int j = 0; j < nbExperiments; j++) {
+ Scenario experimentScenario = new Scenario();
+ for (int i = 0; i < factorsNb; i++) {
+ Factor factor = factors.get(i);
+ factor.setValueForIdentifier(dataFrame.get(i, j));
+ experimentScenario.addFactor(factor);
+ }
+ thisExperimentScenarios.add(experimentScenario);
+ thisExperiment.setScenarios(thisExperimentScenarios);
+ }
+
+
+ String factorDistribution = "isis.factor.distribution<-data.frame(" +
+ "NomFacteur=c(%s)," +
+ "NomDistribution=c(%s)," +
+ "ParametreDistribution=c(%s))";
+
+ String distribution = "";
+ String parameters = "";
+
+ for (int i = 0; i < factorsNb; i++) {
+ Domain domain = factors.get(i).getDomain();
+ if (i != 0) {
+ distribution += ",";
+ parameters += ",";
+ }
+ if (domain instanceof ContinuousDomain){
+ ContinuousDomain contDomain = (ContinuousDomain)domain;
+ distribution += "\"qunif\"";
+ parameters += "\"[" + contDomain.getMinBound()
+ + ";" + contDomain.getMaxBound()
+ + "]\"";
+ } else {
+ DiscreteDomain discDomain = (DiscreteDomain)domain;
+ distribution += "\"discrete\"";
+ parameters+="\"[";
+ Map<Object, Object> values = discDomain.getValues();
+ int count=0;
+ Collection<Object> collecValues = values.values();
+ for (Object value:collecValues){
+ if (count!=0){
+ parameters += ",";
+ }
+ parameters += value;
+ count++;
+ }
+ parameters+="]\"";
+ }
+ }
+ engine.voidEval(String.format(factorDistribution, factorNames,
+ distribution, parameters));
+
+ engine.voidEval("call<-\"" +
+ String.format(expandGrid,factorsNames) + "\"");
+ engine.voidEval("isis.MethodExp<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"call\"=call)");
+ engine.voidEval("attr(isis.MethodExp," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+ engine.voidEval("isis.simule<-x");
+ engine.voidEval("attr(isis.simule," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+ engine.voidEval("names(isis.simule)<-isis.factors[[1]]");
+
+ // Save Isis R session
+ engine.saveRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+
+ } catch (RException eee) {
+ throw new SensitivityException("Can't generate scenarios", eee);
+ }
+
+ return thisExperiment;
+ }
+
+ @Override
+ public void analyzeResult(List<SimulationStorage> simulationStorages,
+ File outputDirectory) throws SensitivityException {
+
+ try {
+
+ REngine engine = new RProxy();
+
+ //Get Isis R session
+ engine.loadRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ //Get back the factors number
+ int factorNumber = (Integer)engine.eval("dim(x)[2]");
+
+ SimulationParameter param = simulationStorages.get(0).getParameter();
+ int sensitivityNumber = param.getSensitivityExport().size();
+
+ SimulationStorage firstStorage = simulationStorages.get(0);
+
+ String firstStorageName = firstStorage.getName().replaceAll("-", "");
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ SensitivityExport sensitivityExport =
+ param.getSensitivityExport().get(k);
+
+ String name = sensitivityExport.getExportFilename();
+
+ String rInstruction = createImportInstruction(sensitivityExport,
+ simulationStorages);
+
+ // Send the simulation results
+ engine.voidEval(rInstruction);
+
+ //Put results in isis.simule
+ engine.voidEval("isis.simule<-data.frame(isis.simule,"
+ + name + ")");
+
+ //Create the dataforaov data.frame
+ String dataFrame = "dataforaov<-data.frame(x,"
+ + name + "=" + name + ")";
+ engine.voidEval(dataFrame);
+
+ //Call aov()
+ String aovCall = "aovresult<-aov(" + name + "~(";
+ for (int j = 0; j < factorNumber; j++) {
+ if (j < (factorNumber - 1)) {
+ aovCall = aovCall
+ + engine.eval("names(x)[" + (j + 1) + "]")
+ + "+";
+ } else {
+ aovCall = aovCall
+ + engine.eval("names(x)[" + (j + 1) + "]")
+ + ")";
+ if(param_order>1){
+ aovCall+="^" + param_order + ",data=dataforaov)";
+ }else{
+ aovCall+=",data=dataforaov)";
+ }
+ }
+ }
+ engine.voidEval(aovCall);
+
+ /*Export the results
+ *Export format is csv, data separated by ','
+ *Results Export name is sensitivityExportName_Results.csv
+ *Sensitivity Indices export name is sensitivityExportName_SensitivityIndices.csv
+ */
+
+ //Compute Sum of Squares and Sensitivity indices
+ engine.voidEval("SoS<-summary(aovresult)[[1]][1:dim(summary(aovresult)[[1]])[1],2]");
+ engine.voidEval("names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:dim(summary(aovresult)[[1]])[1]]");
+ engine.voidEval("IndSensibilite<-SoS/sum(SoS)");
+
+ //Create a data.frame to export sensitivity important results in one file.
+ engine.voidEval("exportsensitivity<-data.frame(" +
+ "SoS[1:dim(summary(aovresult)[[1]])[1]]," +
+ "IndSensibilite[1:dim(summary(aovresult)[[1]])[1]])");
+ engine.voidEval("names(exportsensitivity)<-c(" +
+ "\"Sum Of Squares\"," +
+ "\"Sensitivity indices\")");
+ engine.voidEval("row.names(exportsensitivity)<-dimnames(summary(aovresult)[[1]])[1][[1]][1:dim(summary(aovresult)[[1]])[1]]");
+
+ /*Set the export directory
+ *Export directory is the first simulation export directory.
+ */
+ engine.setwd(outputDirectory);
+
+ //Save the results with the scenarios.
+ engine.voidEval("write.csv(dataforaov,\""
+ + param.getSensitivityExport().get(k)
+
+ .getExportFilename() + "_Results.csv\")");
+
+ //Save the sensitivity indices
+ engine.voidEval("write.csv(exportsensitivity,\""
+ + param.getSensitivityExport().get(k)
+ .getExportFilename()
+ + "_SensitivityIndices.csv\")");
+ //FIXME export through java to enable export when using Rserve (when distant Rserve).
+
+ //creating isis.methodAnalyse
+ engine.voidEval("isis.methodAnalyse<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"isis.simule\"=isis.simule," +
+ "\"call_method\"=\"" + aovCall + "\"," +
+ "\"analysis_result\"=list(aovresult,IndSensibilite))");
+
+ engine.voidEval("attr(isis.methodAnalyse," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ String renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-isis.methodAnalyse";
+ engine.voidEval(String.format(renameIsisMethodAnalyse,
+ firstStorageName + "." + name));
+
+ }
+
+ //Rename R objects for saving purpose
+
+ renameObjects(engine, firstStorageName);
+
+ //Save Isis R session
+ engine.saveRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ engine.terminate();
+
+ } catch (Exception e) {
+ throw new SensitivityException("Can't evaluate results", e);
+ }
+
+ }
+
+ @Override
+ public String getDescription() {
+ return "Implementation of Expand Grid method using R";
+ }
+}
Property changes on: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRExpandGrid.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Deleted: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRFast.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivity/SensitivityCalculatorRFast.java 2011-06-14 13:21:14 UTC (rev 3392)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRFast.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,616 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-
-package sensitivity;
-
-import java.io.File;
-import java.util.List;
-import java.util.Vector;
-
-import javax.swing.Box;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JScrollPane;
-import javax.swing.JTextPane;
-
-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 org.codelutin.math.matrix.MatrixFactory;
-import org.codelutin.math.matrix.MatrixND;
-import org.codelutin.util.FileUtil;
-import org.rosuda.JRI.REXP;
-
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.simulator.SimulationParameter;
-import fr.ifremer.isisfish.simulator.sensitivity.AbstractSensitivityCalculator;
-import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan;
-import fr.ifremer.isisfish.simulator.sensitivity.Domain;
-import fr.ifremer.isisfish.simulator.sensitivity.Factor;
-import fr.ifremer.isisfish.simulator.sensitivity.Scenario;
-import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.DiscreteDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.EquationContinuousDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.MatrixContinuousDomain;
-import fr.ifremer.isisfish.util.Doc;
-
-/**
- * Implementation of Fast method using R.
- *
- * @author jcouteau
- * @version $Revision$
- *
- * Last update : $Date$ By :
- * $Author: jcouteau $
- */
-public class SensitivityCalculatorRFast extends AbstractSensitivityCalculator {
-
- /** to use log facility, just put in your code: log.info("..."); */
- private static Log log = LogFactory
- .getLog(SensitivityCalculatorRFast.class);
-
- @Doc("an integer giving the sample size, i.e. the length of the discretization of the s-space (see Cukier et al.). (default=20)")
- public int param_n = 20;
-
- @Doc("an integer specifying the interference parameter, i.e. the number of harmonics to sum in the Fourier series decomposition (see Cukier et al.). (default=6)")
- public int param_M = 6;
-
- @Doc("True to be able to modify the code sent to R")
- public boolean param_modifR = false;
-
- //public int[] param_omega;
-
- /**
- * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
- * continue.
- *
- * @return <tt>true</tt> s'il sait la gerer
- */
- @Override
- public boolean canManageCardinality() {
- return true;
- }
-
- @Override
- public SensitivityScenarios compute(DesignPlan plan, File outputdirectory) {
-
- setIsisFactorsR(plan, outputdirectory);
-
- double[] dataframe = new double[0];
- int nbExperiments = 0;
- int factorNumber = plan.getFactors().size();
- List<Factor<?, ?>> factors = plan.getFactors();
- SensitivityScenarios thisExperiment = new SensitivityScenarios();
- List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
-
- //Test all factors, if one is discrete, return null
- for (int i = 0; i < factorNumber; i++) {
- if (factors.get(i).getDomain() instanceof DiscreteDomain) {
- JOptionPane
- .showMessageDialog(
- null,
- factors.get(i).getName()
- + " has a discrete domain, this is not acceptable for this method.",
- "Error", JOptionPane.ERROR_MESSAGE);
- return null;
- }
- }
- String rInstruction = "a<-fast99(model=NULL,factors=%s, n=%s, M=%s, q = \"qunif\", q.arg=list(min=0,max=1))";
- String rCall = String.format(rInstruction, factors.size(), param_n,
- param_M);
-
- if (param_modifR) {
- JLabel label = new JLabel(
- "Modifier le code R envoyé si vous le souhaitez");
- JTextPane text = new JTextPane();
- text.setText(rCall);
- text.setSize(400, 400);
- text.setPreferredSize(text.getSize());
-
- Box box = Box.createVerticalBox();
- box.add(label);
- box.add(new JScrollPane(text));
-
- JOptionPane.showMessageDialog(null, box, "R modif",
- JOptionPane.QUESTION_MESSAGE);
- rCall = text.getText();
- }
-
- REngine engine = new RProxy();
- try {
-
- //Clear session
- log.info("rm(list=ls())");
- engine.voidEval("rm(list=ls())");
-
- //Set working directory to get Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- //Get Isis R session
- log.info("load(\"" + outputdirectory.getName() + ".RData\")");
- engine
- .voidEval("load(\"" + outputdirectory.getName()
- + ".RData\")");
-
- // Load sensitivity package into R (if package already loaded,
- // nothing happens.
- engine.voidEval("library(sensitivity)");
- log.info("Message sent to R" + "library(sensitivity)");
-
- // Run sensitivity analysis
- engine.voidEval(rCall);
- log.info("Message sent to R" + rCall);
-
- // Creating the factors vector.
- rInstruction = "factornames<-c(";
- for (int i = 0; i < factorNumber; i++) {
- if (i != (factorNumber - 1)) {
- rInstruction = rInstruction + "\""
- + factors.get(i).getName() + "\",";
- } else {
- rInstruction = rInstruction + "\""
- + factors.get(i).getName() + "\"";
- }
- }
-
- rInstruction += ")";
-
- engine.voidEval(rInstruction);
- log.info("Message sent to R" + rInstruction);
-
- // Set output directory
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- log.info("Message sent to R" + "setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- // Export the fast99 object for the second run in a .fast99 file
- engine.voidEval("dput(a,file=\".fast99\")");
- log.info("Message sent to R" + "dput(a,file=\".fast99\")");
-
- // Export the factornames object for the second run in a .factornames file
- engine.voidEval("dput(factornames,file=\".factornames\")");
- log.info("Message sent to R"
- + "dput(factornames,file=\".factornames\")");
-
- // Get back experiment plan
-
- Vector<REXP> dataframeVector = (Vector<REXP>) engine.eval("a$X");
- dataframe = new double[dataframeVector.size()
- * dataframeVector.get(0).asDoubleArray().length];
- for (int i = 0; i < dataframeVector.size(); i++) {
- for (int j = 0; j < dataframeVector.get(0).asDoubleArray().length; j++) {
- if (String.valueOf(
- dataframeVector.get(i).asDoubleArray()[j])
- .toString().equals("NaN")) {
- log
- .error("Wrong parameters for the fast method, non-numeric values were generated");
- JOptionPane
- .showMessageDialog(
- null,
- "The parameters for this method need to be changed, non-numeric values where generated (you may want to increase the n parameter)",
- "Error", JOptionPane.ERROR_MESSAGE);
- return null;
- }
- dataframe[i * dataframeVector.get(0).asDoubleArray().length
- + j] = dataframeVector.get(i).asDoubleArray()[j];
- }
- }
-
- log.info("Message sent to R" + "a$X");
-
- if (log.isDebugEnabled()) {
- log.debug("rInstruction = " + rInstruction);
- }
-
- nbExperiments = dataframe.length / factorNumber;
-
- String isisFactorDistribution = "isis.factor.distribution<-data.frame(NomFacteur=c(%s),NomDistribution=c(%s),ParametreDistribution=c(%s))";
-
- // Creating the vectors.
- String distribution = "";
- String parameters = "";
- String factorNames = "";
-
- for (int i = 0; i < factorNumber; i++) {
- Domain domain = factors.get(i).getDomain();
- if (i != 0) {
- distribution += ",";
- parameters += ",";
- factorNames += ",";
- }
-
- distribution += "\"qunif\"";
- parameters += "\"[" + ((ContinuousDomain) domain).getMinBound()
- + ";" + ((ContinuousDomain) domain).getMaxBound()
- + "]\"";
- factorNames += "\"" + factors.get(i).getName() + "\"";
- }
-
- log.info("Message sent to R : "
- + String.format(isisFactorDistribution, factorNames,
- distribution, parameters));
- engine.voidEval(String.format(isisFactorDistribution, factorNames,
- distribution, parameters));
-
- log.info("Message sent to R : " + "call<-a$call");
- engine.voidEval("call<-a$call");
-
- log
- .info("Message sent to R : "
- + "isis.MethodExp<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"call\"=call)");
- engine
- .voidEval("isis.MethodExp<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"call\"=call)");
-
- log
- .info("Message sent to R : "
- + "attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : " + "isis.simule<-data.frame(a$X)");
- engine.voidEval("isis.simule<-data.frame(a$X)");
-
- log
- .info("Message sent to R : "
- + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : "
- + "names(isis.simule)<-isis.factors[[1]]");
- engine.voidEval("names(isis.simule)<-isis.factors[[1]]");
-
- //Set working directory to save Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- // Save Isis R session
- log.info("save.image(file=\"" + outputdirectory.getName()
- + ".RData\")");
- engine.voidEval("save.image(file=\"" + outputdirectory.getName()
- + ".RData\")");
-
- } catch (RException eee) {
- eee.printStackTrace();
- throw new RuntimeException("R evaluation failed", eee);
- // Error while retrieving scenario
- }
-
- // Transform the result from R in a matrix
- MatrixND fast = MatrixFactory.getInstance().create(dataframe,
- new int[] { factorNumber, nbExperiments });
-
- // Setting up the scenarios.
- for (int j = 0; j < nbExperiments; j++) {
- Scenario experimentScenario = new Scenario();
- for (int i = 0; i < factorNumber; i++) {
- Factor factor = plan.getFactors().get(i);
- if ((factor.getDomain() instanceof MatrixContinuousDomain)
- || (factor.getDomain() instanceof EquationContinuousDomain)) {
- factor.setValueForIdentifier(fast
- .getValue(new int[] { i, j }));
- } else {
- Double value = (Double) ((ContinuousDomain) factor
- .getDomain()).getMinBound()
- + ((Double) ((ContinuousDomain) factor.getDomain())
- .getMaxBound() - (Double) ((ContinuousDomain) factor
- .getDomain()).getMinBound())
- * fast.getValue(new int[] { i, j });
- factor.setValueForIdentifier(value);
- }
- experimentScenario.addFactor(factor);
- }
- thisExperimentScenarios.add(experimentScenario);
- thisExperiment.setScenarios(thisExperimentScenarios);
- }
- return thisExperiment;
-
- }
-
- @Override
- public void analyzeResult(List<SimulationStorage> simulationStorages,
- File outputdirectory) {
-
- REngine engine = new RProxy();
- try {
-
- //Clear session
- log.info("rm(list=ls())");
- engine.voidEval("rm(list=ls())");
-
- //Set working directory to get Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- //Get Isis R session
- log.info("load(\"" + outputdirectory.getName() + ".RData\")");
- engine
- .voidEval("load(\"" + outputdirectory.getName()
- + ".RData\")");
-
- // Call R
- // Load sensitivity package into R (if package already loaded,
- // nothing happens.
- engine.voidEval("library(sensitivity)");
- log.info("Message sent to R : " + "library(sensitivity)");
-
- //Set the working directory (for import and exports)
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- log.info("Message sent to R : " + "setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- // Export the morris object for the second run in a .morris file
- engine.voidEval("a<-dget(\".fast99\")");
- log.info("Message sent to R : " + "a<-dget(\".fast99\")");
-
- // Get the factornames object in the .factornames file
- engine.voidEval("factornames<-dget(\".factornames\")");
- log.info("Message sent to R : "
- + "factornames<-dget(\".factornames\")");
-
- /*int scenariosNumber = sensitivityScenarios.getScenarios().size();*/
- int scenariosNumber = (Integer) engine.eval("length(a$X[,1])");
- log.info("Message sent to R : " + "length(a$X[,1])");
-
- SimulationParameter param = simulationStorages.get(0)
- .getParameter();
- int sensitivityNumber = param.getSensitivityExport().size();
-
- for (int k = 0; k < sensitivityNumber; k++) {
-
- // Creates the R expression to import results in R
- String name = param.getSensitivityExport().get(k)
- .getExportFilename();
- String rInstruction = name + "<-c(";
- for (int l = 0; l < scenariosNumber; l++) {
- File importFile = new File(simulationStorages.get(l)
- .getDirectory().toString()
- + File.separator
- + SimulationStorage.RESULT_EXPORT_DIRECTORY, param
- .getSensitivityExport().get(k).getExportFilename()
- + param.getSensitivityExport().get(k)
- .getExtensionFilename());
- String simulResult = FileUtil.readAsString(importFile);
- double simulationResult = Double.valueOf(simulResult);
- if (l < simulationStorages.size() - 1) {
- rInstruction = rInstruction + simulationResult + ",";
- } else {
- rInstruction = rInstruction + simulationResult;
- }
- }
- rInstruction = rInstruction + ")";
-
- log.info("Message sent to R : " + rInstruction);
-
- // Send the simulation results
- engine.voidEval(rInstruction);
-
- // Send the simulation results
- engine.voidEval(rInstruction);
-
- //Put results in isis.simule
- engine.voidEval("isis.simule<-data.frame(isis.simule," + name
- + ")");
- log.info("Message sent to R : "
- + "isis.simule<-data.frame(isis.simule," + name + ")");
-
- }
-
- //adding attribute to isis.Simule
- log
- .info("Message sent to R : "
- + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : "
- + "attr(isis.simule,\"call\")<-isis.MethodExp$call");
- engine.voidEval("attr(isis.simule,\"call\")<-isis.MethodExp$call");
-
- for (int k = 0; k < sensitivityNumber; k++) {
-
- // Creates the R expression to import results in R
- String name = param.getSensitivityExport().get(k)
- .getExportFilename();
-
- //Compute results
- engine.voidEval("tell(a,y=" + name + ")");
- log.info("Message sent to R : " + "tell(a,y=" + name + ")");
-
- //creating isis.methodAnalyse
- log
- .info("Message sent to R : "
- + "isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\"tell(a,y="
- + name + ")" + "\",\"analysis_result\"=a)");
- engine
- .voidEval("isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\"tell(a,y="
- + name + ")" + "\",\"analysis_result\"=a)");
-
- //setting isis.methodAnalyse attributes
- log
- .info("attr(isis.methodAnalyse,\"nomModel\")<-\"isis-fish-externe-R\")");
- engine
- .voidEval("attr(isis.methodAnalyse,\"nomModel\")<-\"isis-fish-externe-R\")");
-
- //Create the data.frame of scenarios and results for export purpose
- engine.voidEval("dfresults=data.frame(a$X,results)");
- log.info("Message sent to R : "
- + "dfresults=data.frame(a$X,results)");
-
- //Set working directory
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
- log.info("Message sent to R : setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
-
- // Get the factornames object in the .factornames file
- engine.voidEval("factornames<-dget(\".factornames\")");
- log.info("Message sent to R : "
- + "factornames<-dget(\".factornames\")");
-
- //Set V names
- engine.voidEval("names(a$V)<-factornames");
- log.info("Message sent to R : " + "names(a$V)<-factornames");
-
- //Export V
- engine.voidEval("write.csv(a$V,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_V.csv\")");
- log.info("Message sent to R : "
- + "write.csv(a$V,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_V.csv\")");
-
- //Set D1 names
- engine.voidEval("names(a$D1)<-factornames");
- log.info("Message sent to R : " + "names(a$D1)<-factornames");
-
- //Export D1
- engine.voidEval("write.csv(a$D1,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_D1.csv\")");
- log.info("Message sent to R : "
- + "write.csv(a$D1,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_D1.csv\")");
-
- //Set Dt names
- engine.voidEval("names(a$Dt)<-factornames");
- log.info("Message sent to R : " + "names(a$Dt)<-factornames");
-
- //Export Dt
- engine.voidEval("write.csv(a$Dt,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Dt.csv\")");
- log.info("Message sent to R : "
- + "write.csv(a$Dt,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Dt.csv\")");
- //Set dfresults names
- engine.voidEval("resultsnames<-c(factornames,\"Result\")");
- log.info("Message sent to R : "
- + "resultsnames<-c(factornames,\"Result\")");
- engine.voidEval("names(dfresults)<-resultsnames");
- log.info("Message sent to R : "
- + "names(dfresults)<-resultsnames");
-
- //Export results
- engine.voidEval("write.csv(dfresults,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Results.csv\")");
- log.info("Message sent to R : "
- + "write.csv(results,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Results.csv\")");
- //FIXME export through java to enable export when using Rserve
-
- String renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-isis.methodAnalyse";
- String simulationName = simulationStorages.get(0).getName()
- .replaceAll("-", "");
- log.info("Message sent to R : "
- + String.format(renameIsisMethodAnalyse, simulationName
- + "." + name));
- engine.voidEval(String.format(renameIsisMethodAnalyse,
- simulationName + "." + name));
-
- }
-
- //Rename R objects for saving purpose
-
- String renameIsisSimule = "%s.isis.simule<-isis.simule";
- String renameIsisFactorDistribution = "%s.isis.factor.distribution<-isis.factor.distribution";
- String renameIsisFactor = "%s.isis.factor<-isis.factors";
- String renameIsisMethodExp = "%s.isis.methodExp<-isis.MethodExp";
-
- String simulationName = simulationStorages.get(0).getName()
- .replaceAll("-", "");
-
- log.info("Message sent to R : "
- + String.format(renameIsisSimule, simulationName));
- engine.voidEval(String.format(renameIsisSimule, simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisFactorDistribution,
- simulationName));
- engine.voidEval(String.format(renameIsisFactorDistribution,
- simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisFactor, simulationName));
- engine.voidEval(String.format(renameIsisFactor, simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisMethodExp, simulationName));
- engine.voidEval(String.format(renameIsisMethodExp, simulationName));
-
- //Set working directory to save Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- // Save Isis R session
- log.info("save.image(file=\"" + outputdirectory.getName()
- + ".RData\")");
- engine.voidEval("save.image(file=\"" + outputdirectory.getName()
- + ".RData\")");
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public String getDescription() {
- return "Implementation of FAST method using R";
- }
-
-}
Copied: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRFast.java (from rev 3393, isis-fish/trunk/src/test/resources/test-database/sensitivity/SensitivityCalculatorRFast.java)
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRFast.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRFast.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -0,0 +1,351 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+
+package sensitivityanalysis;
+
+import java.io.File;
+import java.util.List;
+
+import fr.ifremer.isisfish.simulator.sensitivity.*;
+import org.nuiton.j2r.REngine;
+import org.nuiton.j2r.RException;
+import org.nuiton.j2r.RProxy;
+
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.export.SensitivityExport;
+import fr.ifremer.isisfish.simulator.SimulationParameter;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.DiscreteDomain;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.EquationContinuousDomain;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.MatrixContinuousDomain;
+import fr.ifremer.isisfish.util.Doc;
+import org.nuiton.j2r.types.RDataFrame;
+
+/**
+ * Implementation of Fast method using R.
+ *
+ * @author jcouteau
+ * @version $Revision$
+ *
+ * Last update : $Date$ By :
+ * $Author: jcouteau $
+ */
+public class SensitivityCalculatorRFast extends AbstractSensitivityAnalysis {
+
+ @Doc("an integer giving the sample size, i.e. the length of the " +
+ "discretization of the s-space (see Cukier et al.). (default=20)")
+ public int param_n = 20;
+
+ @Doc("an integer specifying the interference parameter, i.e. the number " +
+ "of harmonics to sum in the Fourier series decomposition (see Cukier et " +
+ "al.). (default=6)")
+ public int param_M = 6;
+
+ @Doc("True to be able to modify the code sent to R")
+ public boolean param_modifR = false;
+
+ /**
+ * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
+ * continue.
+ *
+ * @return <tt>true</tt> s'il sait la gerer
+ */
+ @Override
+ public boolean canManageCardinality() {
+ return true;
+ }
+
+ @Override
+ public SensitivityScenarios compute(DesignPlan plan, File outputDirectory)
+ throws SensitivityException {
+
+ setIsisFactorsR(plan, outputDirectory);
+
+ RDataFrame dataFrame;
+ int nbExperiments;
+ int factorNumber = plan.getFactors().size();
+ List<Factor> factors = plan.getFactors();
+ SensitivityScenarios thisExperiment = new SensitivityScenarios();
+ List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
+
+ //Test all factors, if one is discrete, return null
+ for (int i = 0; i < factorNumber; i++) {
+ if (factors.get(i).getDomain() instanceof DiscreteDomain) {
+ throw new SensitivityException(factors.get(i).getName() +
+ " has a discrete domain, this is not acceptable for fast " +
+ "method.");
+ }
+ }
+ String rInstruction = "a<-fast99(" +
+ "model=NULL," +
+ "factors=%s, " +
+ "n=%s, " +
+ "M=%s, " +
+ "q = \"qunif\", " +
+ "q.arg=list(min=0,max=1))";
+ String rCall = String.format(rInstruction, factors.size(), param_n,
+ param_M);
+
+ if (param_modifR) {
+ rCall = editRInstruction(rCall);
+ }
+
+ try {
+
+ REngine engine = new RProxy();
+
+ engine.clearSession();
+ engine.loadRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ // Load sensitivity package into R (if package already loaded,
+ // nothing happens.
+ engine.voidEval("library(sensitivity)");
+
+ // Run sensitivity analysis
+ engine.voidEval(rCall);
+
+ // Creating the factors vector.
+ rInstruction = "factornames<-c(";
+ for (int i = 0; i < factorNumber; i++) {
+ String factorName = factors.get(i).getName();
+ if (i != (factorNumber - 1)) {
+ rInstruction += "\"" + factorName + "\",";
+ } else {
+ rInstruction += "\"" + factorName + "\"";
+ }
+ }
+
+ rInstruction += ")";
+
+ engine.voidEval(rInstruction);
+
+ // Get back experiment plan
+ dataFrame = (RDataFrame) engine.eval("a$X");
+ dataFrame.setVariable("a$X");
+
+ nbExperiments = (Integer)engine.eval("dim(a$X)[1]");
+
+ String factorDistribution = "isis.factor.distribution<-data.frame(" +
+ "NomFacteur=c(%s)," +
+ "NomDistribution=c(%s)," +
+ "ParametreDistribution=c(%s))";
+
+ // Creating the vectors.
+ String distribution = "";
+ String parameters = "";
+ String factorNames = "";
+
+ for (int i = 0; i < factorNumber; i++) {
+ Factor factor = factors.get(i);
+ ContinuousDomain domain = (ContinuousDomain) factor.getDomain();
+ if (i != 0) {
+ distribution += ",";
+ parameters += ",";
+ factorNames += ",";
+ }
+
+ distribution += "\"qunif\"";
+ parameters += "\"[" + domain.getMinBound() + ";" +
+ domain.getMaxBound() + "]\"";
+ factorNames += "\"" + factor.getName() + "\"";
+ }
+ engine.voidEval(String.format(factorDistribution, factorNames,
+ distribution, parameters));
+
+ engine.voidEval("call<-a$call");
+
+
+ engine.voidEval("isis.MethodExp<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"call\"=call)");
+
+ engine.voidEval("attr(isis.MethodExp,\"nomModel\")<-" +
+ "\"isis-fish-externe-R\"");
+
+ engine.voidEval("isis.simule<-data.frame(a$X)");
+
+ engine.voidEval("attr(isis.simule,\"nomModel\")<-" +
+ "\"isis-fish-externe-R\"");
+
+ engine.voidEval("names(isis.simule)<-isis.factors[[1]]");
+
+ // Save Isis R session
+ engine.saveRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ // Setting up the scenarios.
+ for (int j = 0; j < nbExperiments; j++) {
+ Scenario experimentScenario = new Scenario();
+ for (int i = 0; i < factorNumber; i++) {
+ Factor factor = plan.getFactors().get(i);
+ Domain domain = factor.getDomain();
+ if ((domain instanceof MatrixContinuousDomain)
+ || (domain instanceof EquationContinuousDomain)) {
+ factor.setValueForIdentifier((Double)dataFrame.get(i,j));
+ } else {
+ ContinuousDomain continuousDomain = (ContinuousDomain)domain;
+ Double min = continuousDomain.getCalculatorMinBound();
+ Double max = continuousDomain.getCalculatorMaxBound();
+ Double dFValue = (Double)dataFrame.get(i,j);
+ Double value = min + (max - min) * dFValue;
+ factor.setValueForIdentifier(value);
+ }
+ experimentScenario.addFactor(factor);
+ }
+ thisExperimentScenarios.add(experimentScenario);
+ thisExperiment.setScenarios(thisExperimentScenarios);
+ }
+ } catch (RException eee) {
+ throw new SensitivityException("Can't generate scenarios", eee);
+ }
+ return thisExperiment;
+
+ }
+
+ @Override
+ public void analyzeResult(List<SimulationStorage> simulationStorages,
+ File outputDirectory) throws SensitivityException {
+
+ SimulationStorage storage = simulationStorages.get(0);
+ String simulationName = storage.getName().replaceAll("-", "");
+
+ try {
+
+ REngine engine = new RProxy();
+
+ //Clear session
+ engine.clearSession();
+
+ //Get Isis R session
+ engine.loadRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ engine.setwd(outputDirectory);
+
+ // Call R
+ // Load sensitivity package into R (if package already loaded,
+ // nothing happens.
+ engine.voidEval("library(sensitivity)");
+
+ SimulationParameter param = simulationStorages.get(0).getParameter();
+
+ int sensitivityNumber = param.getSensitivityExport().size();
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ SensitivityExport sensitivityExport =
+ param.getSensitivityExport().get(k);
+
+ String rInstruction = createImportInstruction(sensitivityExport,
+ simulationStorages);
+
+ // Send the simulation results
+ engine.voidEval(rInstruction);
+
+ //Put results in isis.simule
+ engine.voidEval("isis.simule<-data.frame(isis.simule," +
+ sensitivityExport.getExportFilename() + ")");
+ }
+
+ //adding attribute to isis.Simule
+ engine.voidEval("attr(isis.simule,\"nomModel\")<-" +
+ "\"isis-fish-externe-R\"");
+ engine.voidEval("attr(isis.simule,\"call\")<-isis.MethodExp$call");
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ // Creates the R expression to import results in R
+ String name = param.getSensitivityExport().get(k)
+ .getExportFilename();
+
+ //Compute results
+ engine.voidEval("tell(a,y=" + name + ")");
+
+ engine.voidEval("names(a$V)<-factornames");
+ engine.voidEval("names(a$X)<-factornames");
+ engine.voidEval("names(a$D1)<-factornames");
+ engine.voidEval("names(a$Dt)<-factornames");
+
+ //creating isis.methodAnalyse
+ engine.voidEval("isis.methodAnalyse<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"isis.simule\"=isis.simule," +
+ "call_method=\"tell(a,y=" + name + ")" + "\"," +
+ "\"analysis_result\"=a)");
+
+ //setting isis.methodAnalyse attributes
+ engine.voidEval("attr(isis.methodAnalyse,\"nomModel\")<-" +
+ "\"isis-fish-externe-R\")");
+
+ //Create the data.frame of scenarios and results for export purpose
+ engine.voidEval("dfresults<-data.frame(a$X,a$y)");
+
+ //Set working directory
+ engine.setwd(outputDirectory);
+
+ //Export V
+ engine.voidEval("write.csv(a$V,\"" + name + "_V.csv\")");
+
+ //Export D1
+ engine.voidEval("write.csv(a$D1,\"" + name + "_D1.csv\")");
+
+ //Export Dt
+ engine.voidEval("write.csv(a$Dt,\"" + name + "_Dt.csv\")");
+ //Set dfresults names
+ engine.voidEval("resultsnames<-c(factornames,\"Result\")");
+ engine.voidEval("names(dfresults)<-resultsnames");
+
+ //Export results
+ engine.voidEval("write.csv(dfresults,\"" + name +
+ "_Results.csv\")");
+ //FIXME export through java to enable export when using Rserve
+
+ String renameIsisMethodAnalyse = "%s.isis.methodAnalyse" +
+ "<-isis.methodAnalyse";
+
+ engine.voidEval(String.format(renameIsisMethodAnalyse,
+ simulationName + "." + name));
+
+ }
+
+ //Rename R objects for saving purpose
+ renameObjects(engine, simulationName);
+
+ // Save Isis R session
+ engine.saveRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ } catch (Exception e) {
+ throw new SensitivityException("Can't evaluate results", e);
+ }
+ }
+
+ @Override
+ public String getDescription() {
+ return "Implementation of FAST method using R (needs the sensitivity " +
+ "package to work)";
+ }
+
+}
Deleted: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRFrF2.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivity/SensitivityCalculatorRFrF2.java 2011-06-14 13:21:14 UTC (rev 3392)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRFrF2.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,532 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-
-package sensitivity;
-
-import java.io.File;
-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 org.codelutin.math.matrix.MatrixFactory;
-import org.codelutin.math.matrix.MatrixND;
-import org.codelutin.util.FileUtil;
-
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.simulator.SimulationParameter;
-import fr.ifremer.isisfish.simulator.sensitivity.AbstractSensitivityCalculator;
-import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan;
-import fr.ifremer.isisfish.simulator.sensitivity.Factor;
-import fr.ifremer.isisfish.simulator.sensitivity.Scenario;
-import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.DiscreteDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.EquationContinuousDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.MatrixContinuousDomain;
-import fr.ifremer.isisfish.util.Doc;
-
-/**
- * Implementation of FrF2 method using R.
- *
- * @author jcouteau
- * @version $Revision$
- *
- * Last update : $Date$ By :
- * $Author: chatellier $
- */
-public class SensitivityCalculatorRFrF2 extends AbstractSensitivityCalculator {
-
- /** to use log facility, just put in your code: log.info("..."); */
- private static Log log = LogFactory
- .getLog(SensitivityCalculatorRFrF2.class);
-
- @Doc("is the arabic numeral for the requested resolution of the design( 3 <= resolution <= 5). (if resolution=3, model = sum(Xi), if resolution = 4 or 5, model = sum(Xi)+sum(XiXj)")
- public int param_resolution;
-
- /**
- * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
- * continue.
- *
- * @return <tt>true</tt> s'il sait la gerer
- */
- @Override
- public boolean canManageCardinality() {
- return true;
- }
-
- @Override
- public SensitivityScenarios compute(DesignPlan plan, File outputdirectory) {
-
- double[] dataframe = new double[0];
- int nbExperiments = 0;
- int factorNumber = plan.getFactors().size();
- List<Factor<?, ?>> factors = plan.getFactors();
- SensitivityScenarios thisExperiment = new SensitivityScenarios();
- List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
-
- //Test all factors, if one is discrete, return null
- for (int i = 0; i < factorNumber; i++) {
- if (factors.get(i).getDomain() instanceof DiscreteDomain) {
- return null;
- }
- }
-
- REngine engine = new RProxy();
-
- try {
- //Clear session
- log.info("rm(list=ls())");
- engine.voidEval("rm(list=ls())");
-
- engine.voidEval("library(FrF2)");
- log.info("Message sent to R : " + "library(FrF2)");
-
- //Set the working directory (for import and exports)
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- log.info("Message sent to R : " + "setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- String rInstruction = "a<-FrF2(nfactors=" + factorNumber
- + ",resolution=" + param_resolution + ")";
-
- engine.voidEval(rInstruction);
- log.info("Message sent to R : " + rInstruction);
-
- // Export the FrF2 object for the second run in a .FrF2 file
- engine.voidEval("dput(a,file=\".FrF2\")");
- log.info("Message sent to R" + "dput(a,file=\".FrF2\")");
-
- // Get back experiment plan
- dataframe = (double[]) engine.eval("a$desnum");
- /*Vector<REXP> dataframeVector = (Vector<REXP>) engine.eval("a$X");
- dataframe = new double[dataframeVector.size()
- * dataframeVector.get(0).asDoubleArray().length];
- for (int i = 0; i < dataframeVector.size(); i++) {
- for (int j = 0; j < dataframeVector.get(0).asDoubleArray().length; j++) {
- dataframe[i * dataframeVector.get(0).asDoubleArray().length
- + j] = dataframeVector.get(i).asDoubleArray()[j];
- }
- }*/
- log.info("Message sent to R : " + "a$desnum");
-
- // Creating the factors vector.
- rInstruction = "factornames<-c(";
- for (int i = 0; i < factorNumber; i++) {
- if (i != (factorNumber - 1)) {
- rInstruction = rInstruction + "\""
- + factors.get(i).getName() + "\",";
- } else {
- rInstruction = rInstruction + "\""
- + factors.get(i).getName() + "\"";
- }
- }
-
- rInstruction += ")";
-
- engine.voidEval(rInstruction);
- log.info("Message sent to R : " + rInstruction);
-
- // Export the factornames object for the second run in a .factornames file
- engine.voidEval("dput(factornames,file=\".factornames\")");
- log.info("Message sent to R : "
- + "dput(factornames,file=\".factornames\")");
-
- } catch (RException e) {
- e.printStackTrace();
- }
-
- nbExperiments = dataframe.length / factorNumber;
-
- // Transform the result from R in a matrix
- MatrixND frf2 = MatrixFactory.getInstance().create(dataframe,
- new int[] { factorNumber, nbExperiments });
-
- // Setting up the scenarios.
- for (int j = 0; j < nbExperiments; j++) {
- Scenario experimentScenario = new Scenario();
- for (int i = 0; i < factorNumber; i++) {
- Factor factor = plan.getFactors().get(i);
- if ((factor.getDomain() instanceof MatrixContinuousDomain)
- || (factor.getDomain() instanceof EquationContinuousDomain)) {
- if (frf2.getValue(new int[] { i, j }) == -1) {
- factor.setValueForIdentifier(0);
- }
-
- if (frf2.getValue(new int[] { i, j }) == 1) {
- factor.setValueForIdentifier(1);
- }
- } else {
- if (frf2.getValue(new int[] { i, j }) == -1) {
- factor.setValueForIdentifier(((ContinuousDomain) factor
- .getDomain()).getMinBound());
- }
-
- if (frf2.getValue(new int[] { i, j }) == 1) {
- factor.setValueForIdentifier(((ContinuousDomain) factor
- .getDomain()).getMaxBound());
- }
- }
- experimentScenario.addFactor(factor);
- }
- thisExperimentScenarios.add(experimentScenario);
- thisExperiment.setScenarios(thisExperimentScenarios);
- }
- try {
- //Create the factors vectors
- for (int j = 0; j < factorNumber; j++) {
- Factor factor = thisExperimentScenarios.get(0).getFactors()
- .get(j);
- if (factor.getDomain() instanceof EquationContinuousDomain) {
-
- String vector = "factor" + j + "<-c(";
- for (int i = 0; i < nbExperiments; i++) {
- if (i < (nbExperiments - 1)) {
- vector = vector
- + ((EquationContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue() + ",";
- } else {
- vector = vector
- + ((EquationContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue();
- }
-
- }
- vector = vector + ")";
- engine.voidEval(vector);
- log.info("Message sent to R : " + vector);
- } else if (factor.getDomain() instanceof MatrixContinuousDomain) {
- String vector = "factor" + j + "<-c(";
- for (int i = 0; i < nbExperiments; i++) {
- if (i < (nbExperiments - 1)) {
- vector = vector
- + ((MatrixContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue() + ",";
- } else {
- vector = vector
- + ((MatrixContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue();
- }
-
- }
- vector = vector + ")";
- engine.voidEval(vector);
- log.info("Message sent to R : " + vector);
- } else {
- String vector = "factor" + j + "<-c(";
- for (int i = 0; i < nbExperiments; i++) {
- if (i < (nbExperiments - 1)) {
- vector = vector
- + thisExperimentScenarios.get(i)
- .getFactors().get(j).getValue()
- + ",";
- } else {
- vector = vector
- + thisExperimentScenarios.get(i)
- .getFactors().get(j).getValue();
- }
-
- }
- vector = vector + ")";
- engine.voidEval(vector);
- log.info("Message sent to R : " + vector);
- }
- }
-
- //Create the data data.frame from the factors
- String data = "data<-data.frame(";
- for (int j = 0; j < factorNumber; j++) {
- if (j < factorNumber - 1) {
- data = data + "factor" + j + "=factor(factor" + j + "),";
- } else {
- data = data + "factor" + j + "=factor(factor" + j + "))";
- }
-
- }
- engine.voidEval(data);
- log.info("Message sent to R : " + data);
-
- // Set output directory
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- log.info("Message sent to R : " + "setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- // Export the scenario matrix for the second run in a .FrF2.csv file
- engine.voidEval("write.csv(data,file=\".FrF2.csv\")");
- log.info("Message sent to R : "
- + "write.csv(data,file=\".FrF2.csv\")");
-
- engine.terminate();
-
- } catch (RException e) {
- e.printStackTrace();
- }
- return thisExperiment;
-
- }
-
- @Override
- public void analyzeResult(List<SimulationStorage> simulationStorages,
- File outputdirectory) {
-
- REngine engine = new RProxy();
- try {
-
- //Clear session
- log.info("rm(list=ls())");
- engine.voidEval("rm(list=ls())");
-
- SimulationParameter param = simulationStorages.get(0)
- .getParameter();
- int sensitivityNumber = param.getSensitivityExport().size();
-
- for (int k = 0; k < sensitivityNumber; k++) {
-
- engine.voidEval("library(FrF2)");
- log.info("Message sent to R : " + "library(FrF2)");
-
- // Set output directory
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
- log.info("Message sent to R : setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
-
- //Get back the FrF2 object
- engine.voidEval("a<-dget(\".FrF2\")");
- log.info("Message sent to R : a<-dget(\".FrF2\")");
-
- //Get back the scenarios
- engine.voidEval("factors<-read.csv(\".FrF2.csv\")");
- log
- .info("Message sent to R : factors<-read.csv(\".FrF2.csv\")");
-
- // Get the factornames object in the .factornames file
- engine.voidEval("factornames<-dget(\".factornames\")");
- log.info("Message sent to R : "
- + "factornames<-dget(\".factornames\")");
-
- //Get back the factors number
- int factorNumber = ((Double) engine.eval("length(factors)-1"))
- .intValue();
-
- // Creates the R expression to import results in R
- String name = param.getSensitivityExport().get(k)
- .getExportFilename();
- String rInstruction = name + "<-c(";
- for (int l = 0; l < simulationStorages.size(); l++) {
- File importFile = new File(simulationStorages.get(l)
- .getDirectory().toString()
- + File.separator
- + SimulationStorage.RESULT_EXPORT_DIRECTORY, param
- .getSensitivityExport().get(k).getExportFilename()
- + param.getSensitivityExport().get(k)
- .getExtensionFilename());
- String simulResult = FileUtil.readAsString(importFile);
- double simulationResult = Double.valueOf(simulResult);
- if (l < simulationStorages.size() - 1) {
- rInstruction = rInstruction + simulationResult + ",";
- } else {
- rInstruction = rInstruction + simulationResult;
- }
- }
- rInstruction = rInstruction + ")";
-
- log.info("Message sent to R : " + rInstruction);
-
- // Send the simulation results
- engine.voidEval(rInstruction);
-
- //Create the dataforaov data.frame
- String dataframe = "dataforaov<-data.frame(factors,result=result)";
- engine.voidEval(dataframe);
- log.info("Message sent to R : " + dataframe);
-
- //get back the resolution
- int resolution = (Integer) engine.eval("res.catlg(a$catentry)");
- log.info("Message sent to R : " + "res.catlg(a$catentry)");
-
- String aovCall;
-
- switch (resolution) {
- case 3:
- //Call aov()
- aovCall = "aovresult<-aov(result~";
- for (int j = 0; j < factorNumber; j++) {
- if (j < (factorNumber - 1)) {
- aovCall = aovCall + "factor" + j + "+";
- } else {
- aovCall = aovCall + "factor" + j
- + ",data=dataforaov)";
- }
- }
- engine.voidEval(aovCall);
- log.info("Message sent to R : " + aovCall);
- break;
- case 4:
- aovCall = "aovresult<-aov(result~";
- for (int j = 0; j < factorNumber; j++) {
- aovCall = aovCall + "factor" + j + "+";
- }
- for (int i = 0; i < factorNumber; i++) {
- for (int j = 0; j < factorNumber; j++) {
- if (i < j) {
- aovCall = aovCall + "factor" + i + "*factor"
- + j + "+";
- }
- }
- }
- aovCall = aovCall.substring(0, aovCall.length() - 1);
- aovCall = aovCall + ",data=dataforaov)";
- engine.voidEval(aovCall);
- log.info("Message sent to R : " + aovCall);
- break;
- case 5:
- aovCall = "aovresult<-aov(result~";
- for (int j = 0; j < factorNumber; j++) {
- aovCall = aovCall + "factor" + j + "+";
- }
- for (int i = 0; i < factorNumber; i++) {
- for (int j = 0; j < factorNumber; j++) {
- if (i < j) {
- aovCall = aovCall + "factor" + i + "*factor"
- + j + "+";
- }
- }
- }
- aovCall = aovCall.substring(0, aovCall.length() - 1);
- aovCall = aovCall + ",data=dataforaov)";
- engine.voidEval(aovCall);
- log.info("Message sent to R : " + aovCall);
- break;
- default:
- log.info("This resolution is not managed");
- break;
- }
-
- /*Export the results
- *Export format is csv, data separated by ','
- *Results Export name is sensitivityExportName_Results.csv
- *Sensitivity Indices export name is sensitivityExportName_SensitivityIndices.csv
- */
-
- //Compute Sum of Squares and Sensitivity indices
- engine.voidEval("SoS<-summary(aovresult)[[1]][1:"
- + factorNumber + ",2]");
- log.info("Message sent to R : SoS<-summary(aovresult)[[1]][1:"
- + factorNumber + ",2]");
- engine
- .voidEval("names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:"
- + factorNumber + "]");
- log
- .info("Message sent to R : names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:"
- + factorNumber + "]");
- engine.voidEval("IndSensibilite<-SoS/sum(SoS)");
- log.info("Message sent to R : IndSensibilite<-SoS/sum(SoS)");
-
- //Create a data.frame to export sensitivity important results in one file.
- engine.voidEval("exportsensitivity=data.frame(SoS[1:"
- + factorNumber + "],IndSensibilite[1:" + factorNumber
- + "])");
- log
- .info("Message sent to R : exportsensitivity=data.frame(SoS[1:"
- + factorNumber
- + "],IndSensibilite[1:"
- + factorNumber + "])");
- engine
- .voidEval("names(exportsensitivity)<-c(\"Sum Of Squares\",\"Sensitivity indices\")");
- log
- .info("Message sent to R : names(exportsensitivity)<-c(\"Sum Of Squares\",\"Sensitivity indices\")");
-
- engine.voidEval("row.names(exportsensitivity)<-factornames");
- log.info("Message sent to R : "
- + "row.names(exportsensitivity)<-factornames");
-
- /*Set the export directory
- *Export directory is the first simulation export directory.
- */
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
- log.info("Message sent to R : setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
-
- //Set dataforaov names
- engine
- .voidEval("resultsnames<-c(\"Simulation\",factornames,\"Result\")");
- log
- .info("Message sent to R : "
- + "resultsnames<-c(\"Simulation\",factornames,\"Result\")");
- engine.voidEval("names(dataforaov)<-resultsnames");
- log.info("Message sent to R : "
- + "names(dataforaov)<-resultsnames");
-
- //Save the results with the scenarios.
- engine.voidEval("write.csv(dataforaov,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Results.csv\")");
- log.info("Message sent to R : write.csv(dataforaov,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Results.csv\")");
-
- //Save the sensitivity indices
- engine.voidEval("write.csv(exportsensitivity,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename()
- + "_SensitivityIndices.csv\")");
- log.info("Message sent to R : write.csv(exportsensitivity,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename()
- + "_SensitivityIndices.csv\")");
- //FIXME export through java to enable export when using Rserve (when distant Rserve).
- engine.terminate();
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- // Error while processing
- }
-
- }
-
- @Override
- public String getDescription() {
- return "Implementation of FrF2 method method using R, at least 4 factors need to be declared";
- }
-}
Copied: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRFrF2.java (from rev 3393, isis-fish/trunk/src/test/resources/test-database/sensitivity/SensitivityCalculatorRFrF2.java)
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRFrF2.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRFrF2.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -0,0 +1,389 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+
+package sensitivityanalysis;
+
+import java.io.File;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.j2r.REngine;
+import org.nuiton.j2r.RException;
+import org.nuiton.j2r.RProxy;
+import org.nuiton.math.matrix.MatrixFactory;
+import org.nuiton.math.matrix.MatrixND;
+import org.nuiton.util.FileUtil;
+
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.simulator.SimulationParameter;
+import fr.ifremer.isisfish.simulator.sensitivity.AbstractSensitivityAnalysis;
+import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan;
+import fr.ifremer.isisfish.simulator.sensitivity.Factor;
+import fr.ifremer.isisfish.simulator.sensitivity.Scenario;
+import fr.ifremer.isisfish.simulator.sensitivity.SensitivityException;
+import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios;
+import fr.ifremer.isisfish.util.Doc;
+
+/**
+ * Implementation of FrF2 method using R.
+ *
+ * @author jcouteau
+ * @version $Revision$
+ *
+ * Last update : $Date$ By :
+ * $Author: chatellier $
+ */
+public class SensitivityCalculatorRFrF2 extends AbstractSensitivityAnalysis {
+
+ //TODO jcouteau 20110607 need to use new ethods on REngine instead of coding R sentences by hand.
+
+ /** to use log facility, just put in your code: log.info("..."); */
+ private static Log log = LogFactory
+ .getLog(SensitivityCalculatorRFrF2.class);
+
+ @Doc("is the arabic numeral for the requested resolution of the design( 3 <= resolution <= 5). (if resolution=3, model = sum(Xi), if resolution = 4 or 5, model = sum(Xi)+sum(XiXj)")
+ public int param_resolution;
+
+ /**
+ * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
+ * continue.
+ *
+ * @return <tt>true</tt> s'il sait la gerer
+ */
+ @Override
+ public boolean canManageCardinality() {
+ return true;
+ }
+
+ @Override
+ public SensitivityScenarios compute(DesignPlan plan, File outputdirectory)
+ throws SensitivityException {
+
+ double[] dataframe;
+ int nbExperiments;
+ int factorNumber = plan.getFactors().size();
+ List<Factor> factors = plan.getFactors();
+ SensitivityScenarios thisExperiment = new SensitivityScenarios();
+ List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
+
+ testNoDiscrete(factors);
+
+ try {
+ REngine engine = new RProxy();
+
+ //Clear session
+ engine.voidEval("rm(list=ls())");
+
+ engine.voidEval("library(FrF2)");
+
+ //Set the working directory (for import and exports)
+ engine.voidEval("setwd(\""
+ + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
+ + "\")");
+
+ String rInstruction = "a<-FrF2(nfactors=" + factorNumber
+ + ",resolution=" + param_resolution + ")";
+
+ engine.voidEval(rInstruction);
+
+ // Export the FrF2 object for the second run in a .FrF2 file
+ engine.voidEval("dput(a,file=\".FrF2\")");
+
+ // Get back experiment plan
+ dataframe = (double[]) engine.eval("a$desnum");
+
+ // Creating the factors vector.
+ rInstruction = "factornames<-c(";
+ for (int i = 0; i < factorNumber; i++) {
+ if (i != (factorNumber - 1)) {
+ rInstruction = rInstruction + "\""
+ + factors.get(i).getName() + "\",";
+ } else {
+ rInstruction = rInstruction + "\""
+ + factors.get(i).getName() + "\"";
+ }
+ }
+
+ rInstruction += ")";
+
+ engine.voidEval(rInstruction);
+
+ // Export the factornames object for the second run in a .factornames file
+ engine.voidEval("dput(factornames,file=\".factornames\")");
+
+
+ nbExperiments = dataframe.length / factorNumber;
+
+ // Transform the result from R in a matrix
+ MatrixND frf2 = MatrixFactory.getInstance().create(dataframe,
+ new int[] { factorNumber, nbExperiments });
+
+ // Setting up the scenarios.
+ for (int j = 0; j < nbExperiments; j++) {
+ Scenario experimentScenario = new Scenario();
+ for (int i = 0; i < factorNumber; i++) {
+ Factor factor = plan.getFactors().get(i);
+
+ if (frf2.getValue(new int[]{i, j}) == -1) {
+ factor.setValueForIdentifier(0);
+ } else if (frf2.getValue(new int[]{i, j}) == 1) {
+ factor.setValueForIdentifier(1);
+ }
+
+ experimentScenario.addFactor(factor);
+ }
+ thisExperimentScenarios.add(experimentScenario);
+ thisExperiment.setScenarios(thisExperimentScenarios);
+ }
+
+ //Create the factors vectors
+ for (int j = 0; j < factorNumber; j++) {
+ Factor factor = thisExperimentScenarios.get(0).getFactors()
+ .get(j);
+
+ String vector = "factor" + j + "<-c(";
+ for (int i = 0; i < nbExperiments; i++) {
+ if (i < (nbExperiments - 1)) {
+ vector = vector + factor.getDisplayedValue() + ",";
+ } else {
+ vector = vector + factor.getDisplayedValue();
+ }
+
+ }
+ vector = vector + ")";
+ engine.voidEval(vector);
+ }
+
+ //Create the data data.frame from the factors
+ String data = "data<-data.frame(";
+ for (int j = 0; j < factorNumber; j++) {
+ if (j < factorNumber - 1) {
+ data = data + "factor" + j + "=factor(factor" + j + "),";
+ } else {
+ data = data + "factor" + j + "=factor(factor" + j + "))";
+ }
+
+ }
+ engine.voidEval(data);
+
+ // Set output directory
+ engine.voidEval("setwd(\""
+ + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
+ + "\")");
+
+ // Export the scenario matrix for the second run in a .FrF2.csv file
+ engine.voidEval("write.csv(data,file=\".FrF2.csv\")");
+
+ engine.terminate();
+
+ } catch (RException e) {
+ throw new SensitivityException("Can't generate scenarios", e);
+ }
+ return thisExperiment;
+
+ }
+
+ @Override
+ public void analyzeResult(List<SimulationStorage> simulationStorages,
+ File outputdirectory) throws SensitivityException {
+
+ try {
+
+ REngine engine = new RProxy();
+
+ //Clear session
+ engine.voidEval("rm(list=ls())");
+
+ SimulationParameter param = simulationStorages.get(0)
+ .getParameter();
+ int sensitivityNumber = param.getSensitivityExport().size();
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ engine.voidEval("library(FrF2)");
+
+ // Set output directory
+ engine.voidEval("setwd(\""
+ + outputdirectory.getAbsolutePath().replaceAll("\\\\",
+ "/") + "\")");
+
+ //Get back the FrF2 object
+ engine.voidEval("a<-dget(\".FrF2\")");
+
+ //Get back the scenarios
+ engine.voidEval("factors<-read.csv(\".FrF2.csv\")");
+
+ // Get the factornames object in the .factornames file
+ engine.voidEval("factornames<-dget(\".factornames\")");
+
+ //Get back the factors number
+ int factorNumber = ((Double) engine.eval("length(factors)-1"))
+ .intValue();
+
+ // Creates the R expression to import results in R
+ String name = param.getSensitivityExport().get(k)
+ .getExportFilename();
+ String rInstruction = name + "<-c(";
+ for (int l = 0; l < simulationStorages.size(); l++) {
+ File importFile = new File(simulationStorages.get(l)
+ .getDirectory().toString()
+ + File.separator
+ + SimulationStorage.RESULT_EXPORT_DIRECTORY, param
+ .getSensitivityExport().get(k).getExportFilename()
+ + param.getSensitivityExport().get(k)
+ .getExtensionFilename());
+ String simulResult = FileUtil.readAsString(importFile);
+ double simulationResult = Double.valueOf(simulResult);
+ if (l < simulationStorages.size() - 1) {
+ rInstruction = rInstruction + simulationResult + ",";
+ } else {
+ rInstruction = rInstruction + simulationResult;
+ }
+ }
+ rInstruction = rInstruction + ")";
+
+ // Send the simulation results
+ engine.voidEval(rInstruction);
+
+ //Create the dataforaov data.frame
+ String dataframe = "dataforaov<-data.frame(factors,result=result)";
+ engine.voidEval(dataframe);
+
+ //get back the resolution
+ int resolution = (Integer) engine.eval("res.catlg(a$catentry)");
+
+ String aovCall;
+
+ switch (resolution) {
+ case 3:
+ //Call aov()
+ aovCall = "aovresult<-aov(result~";
+ for (int j = 0; j < factorNumber; j++) {
+ if (j < (factorNumber - 1)) {
+ aovCall = aovCall + "factor" + j + "+";
+ } else {
+ aovCall = aovCall + "factor" + j
+ + ",data=dataforaov)";
+ }
+ }
+ engine.voidEval(aovCall);
+ break;
+ case 4:
+ aovCall = "aovresult<-aov(result~";
+ for (int j = 0; j < factorNumber; j++) {
+ aovCall = aovCall + "factor" + j + "+";
+ }
+ for (int i = 0; i < factorNumber; i++) {
+ for (int j = 0; j < factorNumber; j++) {
+ if (i < j) {
+ aovCall = aovCall + "factor" + i + "*factor"
+ + j + "+";
+ }
+ }
+ }
+ aovCall = aovCall.substring(0, aovCall.length() - 1);
+ aovCall = aovCall + ",data=dataforaov)";
+ engine.voidEval(aovCall);
+ break;
+ case 5:
+ aovCall = "aovresult<-aov(result~";
+ for (int j = 0; j < factorNumber; j++) {
+ aovCall = aovCall + "factor" + j + "+";
+ }
+ for (int i = 0; i < factorNumber; i++) {
+ for (int j = 0; j < factorNumber; j++) {
+ if (i < j) {
+ aovCall = aovCall + "factor" + i + "*factor"
+ + j + "+";
+ }
+ }
+ }
+ aovCall = aovCall.substring(0, aovCall.length() - 1);
+ aovCall = aovCall + ",data=dataforaov)";
+ engine.voidEval(aovCall);
+ break;
+ default:
+ log.info("This resolution is not managed");
+ break;
+ }
+
+ /*Export the results
+ *Export format is csv, data separated by ','
+ *Results Export name is sensitivityExportName_Results.csv
+ *Sensitivity Indices export name is sensitivityExportName_SensitivityIndices.csv
+ */
+
+ //Compute Sum of Squares and Sensitivity indices
+ engine.voidEval("SoS<-summary(aovresult)[[1]][1:"
+ + factorNumber + ",2]");
+ engine.voidEval("names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:"
+ + factorNumber + "]");
+ engine.voidEval("IndSensibilite<-SoS/sum(SoS)");
+
+ //Create a data.frame to export sensitivity important results in one file.
+ engine.voidEval("exportsensitivity=data.frame(SoS[1:"
+ + factorNumber + "],IndSensibilite[1:" + factorNumber
+ + "])");
+ engine.voidEval("names(exportsensitivity)<-c(" +
+ "\"Sum Of Squares\",\"Sensitivity indices\")");
+
+ engine.voidEval("row.names(exportsensitivity)<-factornames");
+
+ /*Set the export directory
+ *Export directory is the first simulation export directory.
+ */
+ engine.voidEval("setwd(\""
+ + outputdirectory.getAbsolutePath().replaceAll("\\\\",
+ "/") + "\")");
+
+ //Set dataforaov names
+ engine.voidEval("resultsnames<-c(\"Simulation\"," +
+ "factornames,\"Result\")");
+ engine.voidEval("names(dataforaov)<-resultsnames");
+
+ //Save the results with the scenarios.
+ engine.voidEval("write.csv(dataforaov,\""
+ + param.getSensitivityExport().get(k)
+ .getExportFilename() + "_Results.csv\")");
+
+ //Save the sensitivity indices
+ engine.voidEval("write.csv(exportsensitivity,\""
+ + param.getSensitivityExport().get(k)
+ .getExportFilename()
+ + "_SensitivityIndices.csv\")");
+
+ //FIXME export through java to enable export when using Rserve (when distant Rserve).
+ engine.terminate();
+ }
+
+ } catch (Exception e) {
+ throw new SensitivityException("Can't evaluate results", e);
+ }
+
+ }
+
+ @Override
+ public String getDescription() {
+ return "Implementation of FrF2 method method using R, at least 4 factors need to be declared (nneds the 'sensitivity' package to work)";
+ }
+}
Deleted: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRMorris.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivity/SensitivityCalculatorRMorris.java 2011-06-14 13:21:14 UTC (rev 3392)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRMorris.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,579 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-
-package sensitivity;
-
-import java.io.File;
-import java.util.List;
-
-import javax.swing.Box;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JScrollPane;
-import javax.swing.JTextPane;
-
-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 org.codelutin.math.matrix.MatrixFactory;
-import org.codelutin.math.matrix.MatrixND;
-import org.codelutin.util.FileUtil;
-
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.simulator.SimulationParameter;
-import fr.ifremer.isisfish.simulator.sensitivity.AbstractSensitivityCalculator;
-import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan;
-import fr.ifremer.isisfish.simulator.sensitivity.Domain;
-import fr.ifremer.isisfish.simulator.sensitivity.Factor;
-import fr.ifremer.isisfish.simulator.sensitivity.Scenario;
-import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.DiscreteDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.EquationContinuousDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.MatrixContinuousDomain;
-import fr.ifremer.isisfish.util.Doc;
-
-/**
- * Implementation of Morris method using R.
- *
- * @author jcouteau
- * @version $Revision$
- *
- * Last update : $Date$ By :
- * $Author: jcouteau $
- */
-public class SensitivityCalculatorRMorris extends AbstractSensitivityCalculator {
-
- @Doc("Integer giving the number of repetitions of the design, i.e. the number of elementary effect computed per factor. (Default value : 4)")
- public int param_r = 4;
-
- @Doc("True to be able to modify the code sent to R")
- public boolean param_modifR = false;
-
- /** to use log facility, just put in your code: log.info("..."); */
- private static Log log = LogFactory
- .getLog(SensitivityCalculatorRMorris.class);
-
- /**
- * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
- * continue.
- *
- * @return <tt>true</tt> s'il sait la gerer
- */
- @Override
- public boolean canManageCardinality() {
- return false;
- }
-
- @Override
- public SensitivityScenarios compute(DesignPlan plan, File outputdirectory) {
-
- setIsisFactorsR(plan, outputdirectory);
-
- double[] dataframe = new double[0];
- int nbExperiments = 0;
- int factorNumber = plan.getFactors().size();
- List<Factor<?, ?>> factors = plan.getFactors();
-
- if (param_r == 0) {
- param_r = 4;
- }
-
- //Test all factors, if one is discrete, return null
- for (int i = 0; i < factorNumber; i++) {
- if (factors.get(i).getDomain() instanceof DiscreteDomain) {
- JOptionPane
- .showMessageDialog(
- null,
- "Error",
- factors.get(i).getName()
- + " has a discrete domain, this is not acceptable for this method.",
- JOptionPane.ERROR_MESSAGE);
- return null;
- }
- }
-
- // Creating the vectors.
- String factorNames = "";
- String levels = "";
- String gridJump = "";
- String binf = "";
- String bsup = "";
- for (int i = 0; i < factorNumber; i++) {
- Domain domain = factors.get(i).getDomain();
- if (i != 0) {
- factorNames += ",";
- levels += ",";
- gridJump += ",";
- binf += ",";
- bsup += ",";
- }
-
- factorNames += "\"" + factors.get(i).getName() + "\"";
-
- levels += ((ContinuousDomain) domain).getCardinality();
-
- gridJump += (Integer) (((ContinuousDomain) domain).getCardinality() / 2);
-
- binf += ((ContinuousDomain) domain).getMinBound();
-
- bsup += ((ContinuousDomain) domain).getMaxBound();
- }
-
- String rInstruction = "a<-morris(model=NULL,factors=c(%s),r=%s,design=list(type=\"oat\",levels=c(%s),grid.jump=c(%s)),binf=c(%s),bsup=c(%s))";
-
- String rCall = String.format(rInstruction, factorNames, param_r,
- levels, gridJump, binf, bsup);
-
- if (param_modifR) {
- JLabel label = new JLabel(
- "Modifier le code R envoyé si vous le souhaitez");
- JTextPane text = new JTextPane();
- text.setText(rCall);
- text.setSize(400, 400);
- text.setPreferredSize(text.getSize());
-
- Box box = Box.createVerticalBox();
- box.add(label);
- box.add(new JScrollPane(text));
-
- JOptionPane.showMessageDialog(null, box, "R modif",
- JOptionPane.QUESTION_MESSAGE);
- rCall = text.getText();
- }
-
- REngine engine = new RProxy();
- try {
- //Set working directory to get Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- //Get Isis R session
- log.info("load(\"" + outputdirectory.getName() + ".RData\")");
- engine
- .voidEval("load(\"" + outputdirectory.getName()
- + ".RData\")");
-
- // Load sensitivity package into R (if package already loaded,
- // nothing happens.
- engine.voidEval("library(sensitivity)");
- log.info("Message sent to R : " + "library(sensitivity)");
-
- // Run sensitivity analysis
- engine.voidEval(rCall);
- log.info("Message sent to R : " + rCall);
-
- // Creating the factors vector.
- rInstruction = "factornames<-c(%s)";
- rCall = String.format(rInstruction, factorNames);
-
- engine.voidEval(rCall);
- log.info("Message sent to R : " + rCall);
-
- // Set output directory
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- log.info("Message sent to R : " + "setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- // Export the morris object for the second run in a .morris file
- engine.voidEval("dput(a,file=\".morris\")");
- log.info("Message sent to R : " + "dput(a,file=\".morris\")");
-
- // Export the factornames object for the second run in a .factornames file
- engine.voidEval("dput(factornames,file=\".factornames\")");
- log.info("Message sent to R : "
- + "dput(factornames,file=\".factornames\")");
-
- // Get back experiment plan
- dataframe = (double[]) engine.eval("a$X");
- log.info("Message sent to R : " + "a$X");
-
- if (log.isDebugEnabled()) {
- log.debug("rInstruction = " + rInstruction);
- }
-
- nbExperiments = dataframe.length / factorNumber;
-
- String isisFactorDistribution = "isis.factor.distribution<-data.frame(NomFacteur=c(%s),NomDistribution=c(%s),ParametreDistribution=c(%s))";
-
- String distribution = "";
- String parameters = "";
-
- for (int i = 0; i < factorNumber; i++) {
- Domain domain = factors.get(i).getDomain();
- if (i != 0) {
- distribution += ",";
- parameters += ",";
- }
-
- distribution += "\"qunif\"";
- parameters += "\"[" + ((ContinuousDomain) domain).getMinBound()
- + ";" + ((ContinuousDomain) domain).getMaxBound()
- + "]\"";
- }
-
- log.info("Message sent to R : "
- + String.format(isisFactorDistribution, factorNames,
- distribution, parameters));
- engine.voidEval(String.format(isisFactorDistribution, factorNames,
- distribution, parameters));
-
- log.info("Message sent to R : " + "call<-a$call");
- engine.voidEval("call<-a$call");
-
- log
- .info("Message sent to R : "
- + "isis.MethodExp<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"call\"=call)");
- engine
- .voidEval("isis.MethodExp<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"call\"=call)");
-
- log
- .info("Message sent to R : "
- + "attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : " + "isis.simule<-data.frame(a$X)");
- engine.voidEval("isis.simule<-data.frame(a$X)");
-
- log
- .info("Message sent to R : "
- + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : "
- + "names(isis.simule)<-isis.factors[[1]]");
- engine.voidEval("names(isis.simule)<-isis.factors[[1]]");
-
- //Set working directory to save Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- // Save Isis R session
- log.info("save.image(file=\"" + outputdirectory.getName() + ".RData\")");
- engine.voidEval("save.image(file=\"" + outputdirectory.getName()
- + ".RData\")");
-
- } catch (RException eee) {
- eee.printStackTrace();
- throw new RuntimeException("R evaluation failed", eee);
- // Error while retrieving scenario
- }
-
- // Transform the result from R in a matrix
- MatrixND morris = MatrixFactory.getInstance().create(dataframe,
- new int[] { factorNumber, nbExperiments });
-
- // Setting up the scenarios.
- SensitivityScenarios thisExperiment = new SensitivityScenarios();
- List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
- for (int j = 0; j < nbExperiments; j++) {
- Scenario experimentScenario = new Scenario();
- for (int i = 0; i < factorNumber; i++) {
- Factor factor = factors.get(i);
- if ((factor.getDomain() instanceof MatrixContinuousDomain)
- || (factor.getDomain() instanceof EquationContinuousDomain)) {
- factor
- .setValueForIdentifier((Double) morris.getValue(i,
- j));
- } else {
- factor.setValueForIdentifier(morris.getValue(new int[] { i,
- j }));
- }
- experimentScenario.addFactor(factor);
- }
- thisExperimentScenarios.add(experimentScenario);
- thisExperiment.setScenarios(thisExperimentScenarios);
- }
- return thisExperiment;
-
- }
-
- @Override
- public void analyzeResult(List<SimulationStorage> simulationStorages,
- File outputdirectory) {
-
- REngine engine = new RProxy();
- try {
-
- //Set working directory to get Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- //Get Isis R session
- log.info("load(\"" + outputdirectory.getName() + ".RData\")");
- engine
- .voidEval("load(\"" + outputdirectory.getName()
- + ".RData\")");
-
- // Call R
- // Load sensitivity package into R (if package already loaded,
- // nothing happens.
- engine.voidEval("library(sensitivity)");
- log.info("Message sent to R : " + "library(sensitivity)");
-
- //Set the working directory (for import and exports)
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- log.info("Message sent to R : " + "setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- // Export the morris object for the second run in a .morris file
- engine.voidEval("a<-dget(\".morris\")");
- log.info("Message sent to R : " + "a<-dget(\".morris\")");
-
- // Get the factornames object in the .factornames file
- engine.voidEval("factornames<-dget(\".factornames\")");
- log.info("Message sent to R : "
- + "factornames<-dget(\".factornames\")");
-
- int scenariosNumber = ((Double) engine
- .eval("length(a$X)/length(a$factors)")).intValue();
- log.info("Message sent to R : " + "length(a$X)/length(a$factors)");
-
- SimulationParameter param = simulationStorages.get(0)
- .getParameter();
- int sensitivityNumber = param.getSensitivityExport().size();
-
- for (int k = 0; k < sensitivityNumber; k++) {
-
- // Creates the R expression to import results in R
- String name = param.getSensitivityExport().get(k)
- .getExportFilename();
- String rInstruction = name + "<-c(";
- for (int l = 0; l < scenariosNumber; l++) {
- File importFile = new File(simulationStorages.get(l)
- .getDirectory().toString()
- + File.separator
- + SimulationStorage.RESULT_EXPORT_DIRECTORY, param
- .getSensitivityExport().get(k).getExportFilename()
- + param.getSensitivityExport().get(k)
- .getExtensionFilename());
- String simulResult = FileUtil.readAsString(importFile);
- double simulationResult = Double.valueOf(simulResult);
- if (l < simulationStorages.size() - 1) {
- rInstruction = rInstruction + simulationResult + ",";
- } else {
- rInstruction = rInstruction + simulationResult;
- }
- }
- rInstruction = rInstruction + ")";
-
- log.info("Message sent to R : " + rInstruction);
-
- // Send the simulation results
- engine.voidEval(rInstruction);
-
- //Put results in isis.simule
- engine.voidEval("isis.simule<-data.frame(isis.simule," + name
- + ")");
- log.info("Message sent to R : "
- + "isis.simule<-data.frame(isis.simule," + name + ")");
- }
-
- //adding attribute to isis.Simule
- log
- .info("Message sent to R : "
- + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : "
- + "attr(isis.simule,\"call\")<-isis.MethodExp$call");
- engine.voidEval("attr(isis.simule,\"call\")<-isis.MethodExp$call");
-
- for (int k = 0; k < sensitivityNumber; k++) {
-
- // Creates the R expression to import results in R
- String name = param.getSensitivityExport().get(k)
- .getExportFilename();
-
- //Compute results
- engine.voidEval("tell(a,y=" + name + ")");
- log.info("Message sent to R : " + "tell(a,y=" + name + ")");
-
- //creating isis.methodAnalyse
- log
- .info("Message sent to R : "
- + "isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\"tell(a,y="
- + name + ")" + "\",\"analysis_result\"=a)");
- engine
- .voidEval("isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\"tell(a,y="
- + name + ")" + "\",\"analysis_result\"=a)");
-
- //setting isis.methodAnalyse attributes
- log
- .info("attr(isis.methodAnalyse,\"nomModel\")<-\"isis-fish-externe-R\")");
- engine
- .voidEval("attr(isis.methodAnalyse,\"nomModel\")<-\"isis-fish-externe-R\")");
-
- // Get back the sensitivity results, mu, mu star and sigma.
- engine.voidEval("mu<-apply(a$ee, 2, mean)");
- log.info("Message sent to R : " + "mu<-apply(a$ee, 2, mean)");
- engine
- .voidEval("mu.star <- apply(a$ee, 2, function(a) mean(abs(a)))");
- log
- .info("Message sent to R : "
- + "mu.star <- apply(a$ee, 2, function(a) mean(abs(a)))");
- engine.voidEval("sigma <- apply(a$ee, 2, sd)");
- log
- .info("Message sent to R : "
- + "sigma <- apply(a$ee, 2, sd)");
-
- //Create the data.frame of sensitivity indices for export purpose
- engine.voidEval("df=data.frame(mu,mu.star,sigma)");
- log.info("Message sent to R : "
- + "df=data.frame(mu,mu.star,sigma)");
- engine.voidEval("row.names(df)<-factornames");
- log.info("Message sent to R : " + "row.names(df)<-factornames");
-
- //Create the data.frame of scenarios and results for export purpose
- engine.voidEval("dfresults=data.frame(a$X,name)");
- log.info("Message sent to R : "
- + "dfresults=data.frame(a$X,name)");
-
- //Set dfresults names
- engine
- .voidEval("resultsnames<-c(\"Simulation\",factornames,\"Result\")");
- log
- .info("Message sent to R : "
- + "resultsnames<-c(\"Simulation\",factornames,\"Result\")");
- engine.voidEval("names(dfresults)<-resultsnames");
- log.info("Message sent to R : "
- + "names(dfresults)<-resultsnames");
-
- //Set working directory
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
- log.info("Message sent to R : setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
-
- //Export sensitivity indices
- engine.voidEval("write.csv(df,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename()
- + "_SensitivityIndices.csv\")");
- log.info("Message sent to R : "
- + "write.csv(df,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename()
- + "_SensitivityIndices.csv\")");
-
- //Export results
- engine.voidEval("write.csv(dfresults,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Results.csv\")");
- log.info("Message sent to R : "
- + "write.csv(results,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Results.csv\")");
- //FIXME export through java to enable export when using Rserve
-
- String renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-isis.methodAnalyse";
- String simulationName = simulationStorages.get(0).getName()
- .replaceAll("-", "");
- log.info("Message sent to R : "
- + String.format(renameIsisMethodAnalyse, simulationName
- + "." + name));
- engine.voidEval(String.format(renameIsisMethodAnalyse,
- simulationName + "." + name));
-
- }
-
- //Rename R objects for saving purpose
-
- String renameIsisSimule = "%s.isis.simule<-isis.simule";
- String renameIsisFactorDistribution = "%s.isis.factor.distribution<-isis.factor.distribution";
- String renameIsisFactor = "%s.isis.factor<-isis.factors";
- String renameIsisMethodExp = "%s.isis.methodExp<-isis.MethodExp";
-
- String simulationName = simulationStorages.get(0).getName()
- .replaceAll("-", "");
-
- log.info("Message sent to R : "
- + String.format(renameIsisSimule, simulationName));
- engine.voidEval(String.format(renameIsisSimule, simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisFactorDistribution,
- simulationName));
- engine.voidEval(String.format(renameIsisFactorDistribution,
- simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisFactor, simulationName));
- engine.voidEval(String.format(renameIsisFactor, simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisMethodExp, simulationName));
- engine.voidEval(String.format(renameIsisMethodExp, simulationName));
-
- //Set working directory to save Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- // Save Isis R session
- log.info("save.image(file=\"" + outputdirectory.getName() + ".RData\")");
- engine.voidEval("save.image(file=\"" + outputdirectory.getName()
- + ".RData\")");
-
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
-
- @Override
- public String getDescription() {
- return "Implementation of Morris method using R";
- }
-
-}
Copied: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRMorris.java (from rev 3393, isis-fish/trunk/src/test/resources/test-database/sensitivity/SensitivityCalculatorRMorris.java)
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRMorris.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRMorris.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -0,0 +1,342 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+
+package sensitivityanalysis;
+
+import java.io.File;
+import java.util.List;
+
+import fr.ifremer.isisfish.export.SensitivityExport;
+import org.nuiton.j2r.REngine;
+import org.nuiton.j2r.RException;
+import org.nuiton.j2r.RProxy;
+import org.nuiton.j2r.types.RDataFrame;
+
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.simulator.SimulationParameter;
+import fr.ifremer.isisfish.simulator.sensitivity.AbstractSensitivityAnalysis;
+import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan;
+import fr.ifremer.isisfish.simulator.sensitivity.Factor;
+import fr.ifremer.isisfish.simulator.sensitivity.Scenario;
+import fr.ifremer.isisfish.simulator.sensitivity.SensitivityException;
+import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
+import fr.ifremer.isisfish.util.Doc;
+
+/**
+ * Implementation of Morris method using R.
+ *
+ * @author jcouteau
+ * @version $Revision$
+ *
+ * Last update : $Date$ By :
+ * $Author: chatellier $
+ */
+public class SensitivityCalculatorRMorris extends AbstractSensitivityAnalysis {
+
+ @Doc("Integer giving the number of repetitions of the design, i.e. the number of elementary effect computed per factor. (Default value : 4)")
+ public int param_r = 4;
+
+ @Doc("True to be able to modify the code sent to R")
+ public boolean param_modifR = false;
+
+ /**
+ * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
+ * continus.
+ *
+ * @return <tt>true</tt> s'il sait la gerer
+ */
+ @Override
+ public boolean canManageCardinality() {
+ return false;
+ }
+
+ @Override
+ public SensitivityScenarios compute(DesignPlan plan, File outputDirectory)
+ throws SensitivityException {
+
+ setIsisFactorsR(plan, outputDirectory);
+
+ RDataFrame dataFrame;
+ int nbExperiments;
+ int factorNumber = plan.getFactors().size();
+
+ SensitivityScenarios thisExperiment = new SensitivityScenarios();
+
+ List<Factor> factors = plan.getFactors();
+
+ if (param_r == 0) {
+ param_r = 4;
+ }
+
+ testNoDiscrete(factors);
+
+ // Creating the vectors.
+ String factorNames = "";
+ String levels = "";
+ String gridJump = "";
+ String binf = "";
+ String bsup = "";
+ for (int i = 0; i < factorNumber; i++) {
+ ContinuousDomain domain = (ContinuousDomain) factors.get(i).getDomain();
+ if (i != 0) {
+ factorNames += ",";
+ levels += ",";
+ gridJump += ",";
+ binf += ",";
+ bsup += ",";
+ }
+
+ factorNames += "\"" + factors.get(i).getName() + "\"";
+
+ levels += domain.getCardinality();
+
+ gridJump += domain.getCardinality() / 2;
+
+ binf += domain.getCalculatorMinBound();
+
+ bsup += domain.getCalculatorMaxBound();
+ }
+
+ String rInstruction = "a<-morris(model=NULL,factors=c(%s),r=%s," +
+ "design=list(type=\"oat\",levels=c(%s),grid.jump=c(%s))," +
+ "binf=c(%s),bsup=c(%s))";
+
+ String rCall = String.format(rInstruction, factorNames, param_r,
+ levels, gridJump, binf, bsup);
+
+ if (param_modifR) {
+ rCall = editRInstruction(rCall);
+ }
+
+ try {
+ REngine engine = new RProxy();
+
+ //Get Isis R session
+ engine.loadRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ // Load sensitivity package into R (if package already loaded,
+ // nothing happens.
+ engine.voidEval("library(sensitivity)");
+
+ // Run sensitivity analysis
+ engine.voidEval(rCall);
+
+ // Creating the factors vector.
+ rInstruction = "factornames<-c(%s)";
+ rCall = String.format(rInstruction, factorNames);
+
+ engine.voidEval(rCall);
+
+ // Set output directory
+ engine.setwd(outputDirectory);
+
+ // Get back experiment plan
+ engine.eval("expPlan<-as.data.frame(a$X)");
+ dataFrame = (RDataFrame) engine.eval("expPlan");
+ dataFrame.setVariable("expPlan");
+
+ nbExperiments = (Integer)engine.eval("dim(a$X)[1]");
+
+ String factorDistribution = "isis.factor.distribution<-data.frame(" +
+ "NomFacteur=c(%s)," +
+ "NomDistribution=c(%s)," +
+ "ParametreDistribution=c(%s))";
+
+ String distribution = "";
+ String parameters = "";
+
+ for (int i = 0; i < factorNumber; i++) {
+ Factor factor = factors.get(i);
+ ContinuousDomain domain = (ContinuousDomain) factor.getDomain();
+ if (i != 0) {
+ distribution += ",";
+ parameters += ",";
+ }
+
+ distribution += "\"qunif\"";
+ parameters += "\"[" + domain.getMinBound() + ";" +
+ domain.getMaxBound() + "]\"";
+ }
+ engine.voidEval(String.format(factorDistribution, factorNames,
+ distribution, parameters));
+
+ engine.voidEval("call<-a$call");
+ engine.voidEval("isis.MethodExp<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"call\"=call)");
+ engine.voidEval("attr(isis.MethodExp,\"nomModel\")<-" +
+ "\"isis-fish-externe-R\"");
+ engine.voidEval("isis.simule<-data.frame(a$X)");
+ engine.voidEval("attr(isis.simule,\"nomModel\")<-" +
+ "\"isis-fish-externe-R\"");
+ engine.voidEval("names(isis.simule)<-isis.factors[[1]]");
+
+ // Save Isis R session
+ engine.saveRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ // Setting up the scenarios.
+ List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
+ for (int j = 0; j < nbExperiments; j++) {
+ Scenario experimentScenario = new Scenario();
+ for (int i = 0; i < factorNumber; i++) {
+ Factor factor = factors.get(i);
+ factor.setValueForIdentifier(dataFrame.get(i, j));
+ experimentScenario.addFactor(factor);
+ }
+ thisExperimentScenarios.add(experimentScenario);
+ thisExperiment.setScenarios(thisExperimentScenarios);
+ }
+
+ } catch (RException eee) {
+ throw new SensitivityException("Can't generate scenarios", eee);
+ }
+
+ return thisExperiment;
+
+ }
+
+ @Override
+ public void analyzeResult(List<SimulationStorage> simulationStorages,
+ File outputDirectory) throws SensitivityException {
+
+ SimulationStorage storage = simulationStorages.get(0);
+ String simulationName = storage.getName().replaceAll("-", "");
+
+ try {
+ REngine engine = new RProxy();
+
+ //Get Isis R session
+ engine.loadRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ // Call R
+ // Load sensitivity package into R (if package already loaded,
+ // nothing happens.
+ engine.voidEval("library(sensitivity)");
+
+ //Set the working directory (for exports)
+ engine.setwd(outputDirectory);
+
+ SimulationParameter param = simulationStorages.get(0)
+ .getParameter();
+ int sensitivityNumber = param.getSensitivityExport().size();
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ SensitivityExport sensitivityExport =
+ param.getSensitivityExport().get(k);
+
+ String rInstruction = createImportInstruction(sensitivityExport,
+ simulationStorages);
+
+ // Send the simulation results
+ engine.voidEval(rInstruction);
+
+ //Put results in isis.simule
+ engine.voidEval("isis.simule<-data.frame(isis.simule," +
+ sensitivityExport.getExportFilename() + ")");
+ }
+
+ //adding attribute to isis.Simule
+ engine.voidEval("attr(isis.simule,\"nomModel\")<-" +
+ "\"isis-fish-externe-R\"");
+
+ engine.voidEval("attr(isis.simule,\"call\")<-isis.MethodExp$call");
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ // Creates the R expression to import results in R
+ String name = param.getSensitivityExport().get(k)
+ .getExportFilename();
+
+ //Compute results
+ engine.voidEval("tell(a,y=" + name + ")");
+
+ //creating isis.methodAnalyse
+ engine.voidEval("isis.methodAnalyse<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"isis.simule\"=isis.simule," +
+ "\"call_method\"=\"tell(a,y=" + name + ")" + "\"," +
+ "\"analysis_result\"=a)");
+
+ //setting isis.methodAnalyse attributes
+ engine.voidEval("attr(isis.methodAnalyse,\"nomModel\")<-" +
+ "\"isis-fish-externe-R\"");
+
+ // Get back the sensitivity results, mu, mu star and sigma.
+ engine.voidEval("mu<-apply(a$ee, 2, mean)");
+ engine.voidEval("mu.star <- apply(a$ee, 2, function(a) mean(abs(a)))");
+ engine.voidEval("sigma <- apply(a$ee, 2, sd)");
+
+ //Create the data.frame of sensitivity indices for export purpose
+ engine.voidEval("df<-data.frame(mu,mu.star,sigma)");
+ engine.voidEval("row.names(df)<-factornames");
+
+ //Create the data.frame of scenarios and results for export purpose
+ engine.voidEval("dfresults<-data.frame(a$X," + name + ")");
+
+ //Set dfresults names
+ engine.voidEval("resultsnames<-c(factornames,\"Result\")");
+ engine.voidEval("names(dfresults)<-resultsnames");
+
+ //Export sensitivity indices
+ engine.voidEval("write.csv(df," +
+ "\"" + name + "_SensitivityIndices.csv\")");
+
+ //Export results
+ engine.voidEval("write.csv(dfresults," +
+ "\"" + name + "_Results.csv\")");
+ //FIXME export through java to enable export when using Rserve
+
+ String renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-" +
+ "isis.methodAnalyse";
+
+ engine.voidEval(String.format(renameIsisMethodAnalyse,
+ simulationName + "." + name));
+
+ }
+
+ //Rename R objects for saving purpose
+ renameObjects(engine,simulationName);
+
+ // Save Isis R session
+ engine.saveRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ } catch (Exception e) {
+ throw new SensitivityException("Can't evaluate results", e);
+ }
+
+ }
+
+ @Override
+ public String getDescription() {
+ return "Implementation of Morris method using R (needs the sensitivity" +
+ " package to work)";
+ }
+
+}
Deleted: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorROptimumLHS.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivity/SensitivityCalculatorROptimumLHS.java 2011-06-14 13:21:14 UTC (rev 3392)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorROptimumLHS.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,731 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-
-package sensitivity;
-
-import java.io.File;
-import java.util.List;
-
-import javax.swing.Box;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JScrollPane;
-import javax.swing.JTextPane;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.codelutin.j2r.REngine;
-import org.codelutin.j2r.RProxy;
-import org.codelutin.math.matrix.MatrixFactory;
-import org.codelutin.math.matrix.MatrixND;
-import org.codelutin.util.FileUtil;
-
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.simulator.SimulationParameter;
-import fr.ifremer.isisfish.simulator.sensitivity.AbstractSensitivityCalculator;
-import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan;
-import fr.ifremer.isisfish.simulator.sensitivity.Domain;
-import fr.ifremer.isisfish.simulator.sensitivity.Factor;
-import fr.ifremer.isisfish.simulator.sensitivity.Scenario;
-import fr.ifremer.isisfish.simulator.sensitivity.SensitivityException;
-import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.DiscreteDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.EquationContinuousDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.MatrixContinuousDomain;
-import fr.ifremer.isisfish.util.Doc;
-
-/**
- * save.image() Implementation of Optimum Latin Hypercube method using R.
- *
- * @author jcouteau
- * @version $Revision$
- */
-public class SensitivityCalculatorROptimumLHS extends
- AbstractSensitivityCalculator {
-
- /** to use log facility, just put in your code: log.info("..."); */
- static private Log log = LogFactory
- .getLog(SensitivityCalculatorROptimumLHS.class);
-
- @Doc("Number of simulations (default=10)")
- public int param_simulationNumber = 10;
- @Doc("The maximum number of times the Columnwise Pairwise algorithm is applied to all the columns(default=2).")
- public int param_MaxSweeps = 2;
- @Doc("The optimal stopping criterion (between 0 and 1) (default=0.1).")
- public double param_eps = 0.1;
- @Doc("True to be able to modify the code sent to R")
- public boolean param_modifR = false;
-
- /**
- * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
- * continue.
- *
- * @return <tt>true</tt> s'il sait la gerer
- */
- @Override
- public boolean canManageCardinality() {
- return true;
- }
-
- @Override
- public SensitivityScenarios compute(DesignPlan plan, File outputdirectory)
- throws SensitivityException {
-
- setIsisFactorsR(plan, outputdirectory);
-
- int factornumber = plan.getFactors().size();
- List<Factor<?, ?>> factors = plan.getFactors();
- double[] dataframe = new double[0];
- SensitivityScenarios thisExperiment = new SensitivityScenarios();
- List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
-
- //Test all factors, if one is discrete, return null
- for (int i = 0; i < factornumber; i++) {
- if (factors.get(i).getDomain() instanceof DiscreteDomain) {
- JOptionPane
- .showMessageDialog(
- null,
- "Error",
- factors.get(i).getName()
- + " has a discrete domain, this is not acceptable for this method.",
- JOptionPane.ERROR_MESSAGE);
- return null;
- }
- }
-
- REngine engine = new RProxy();
-
- if ((Integer) param_simulationNumber == 0) {
- param_simulationNumber = 10;
- }
- if ((Integer) param_MaxSweeps == 0) {
- param_MaxSweeps = 2;
- }
-
- if ((Double) param_eps == 0) {
- param_eps = 0.1;
- }
-
- try {
-
- //Clear session
- log.info("rm(list=ls())");
- engine.voidEval("rm(list=ls())");
-
- //Set working directory to get Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- //Get Isis R session
- log.info("load(\"" + outputdirectory.getName() + ".RData\")");
- engine
- .voidEval("load(\"" + outputdirectory.getName()
- + ".RData\")");
-
- //Load the lhs library
- engine.voidEval("library(lhs)");
- log.info("Message sent to R : " + "library(lhs)");
-
- //Remove all objects that will be used
- engine.voidEval("remove(\"isis.factor.distribution\")");
- engine.voidEval("remove(\"isis.simule\")");
- engine.voidEval("remove(\"isis.MethodExp\")");
- engine.voidEval("remove(\"isis.methodAnalyse\")");
-
- String rInstruction = "x<-optimumLHS(n=%s,k=%s,maxSweeps=%s,eps=%s)";
-
- String rCall = String.format(rInstruction, param_simulationNumber,
- factornumber, param_MaxSweeps, param_eps);
-
- if (param_modifR) {
- JLabel label = new JLabel(
- "Modifier le code R envoyé si vous le souhaitez");
- JTextPane text = new JTextPane();
- text.setText(rCall);
- text.setSize(400, 400);
- text.setPreferredSize(text.getSize());
-
- Box box = Box.createVerticalBox();
- box.add(label);
- box.add(new JScrollPane(text));
-
- JOptionPane.showMessageDialog(null, box, "R modif",
- JOptionPane.QUESTION_MESSAGE);
- rCall = text.getText();
- }
-
- //Create the scenarios
- engine.voidEval(rCall);
- log.info("Message sent to R : " + rCall);
-
- // Get back experiment plan
- dataframe = (double[]) engine.eval("x");
- log.info("Message sent to R : " + "x");
-
- // Transform the result from R in a matrix
- MatrixND morris = MatrixFactory.getInstance().create(dataframe,
- new int[] { factornumber, param_simulationNumber });
-
- // Setting up the scenarios.
- for (int j = 0; j < param_simulationNumber; j++) {
- Scenario experimentScenario = new Scenario();
- for (int i = 0; i < factornumber; i++) {
- Factor factor = plan.getFactors().get(i);
- if ((factor.getDomain() instanceof MatrixContinuousDomain)
- || (factor.getDomain() instanceof EquationContinuousDomain)) {
- factor.setValueForIdentifier(morris.getValue(new int[] {
- i, j }));
- } else {
- Double value = (Double) ((ContinuousDomain) factor
- .getDomain()).getMinBound()
- + ((Double) ((ContinuousDomain) factor
- .getDomain()).getMaxBound() - (Double) ((ContinuousDomain) factor
- .getDomain()).getMinBound())
- * morris.getValue(new int[] { i, j });
- factor.setValueForIdentifier(value);
- }
- experimentScenario.addFactor(factor);
- }
- thisExperimentScenarios.add(experimentScenario);
- thisExperiment.setScenarios(thisExperimentScenarios);
- }
-
- String isisFactorDistribution = "isis.factor.distribution<-data.frame(NomFacteur=c(%s),NomDistribution=c(%s),ParametreDistribution=c(%s))";
-
- String distribution = "";
- String parameters = "";
- String factorNames = "";
-
- for (int i = 0; i < factors.size(); i++) {
- Domain domain = factors.get(i).getDomain();
- if (i != 0) {
- distribution += ",";
- factorNames += ",";
- parameters += ",";
- }
-
- factorNames += "\"" + factors.get(i).getName() + "\"";
- distribution += "\"qunif\"";
- parameters += "\"[" + ((ContinuousDomain) domain).getMinBound()
- + ";" + ((ContinuousDomain) domain).getMaxBound()
- + "]\"";
- }
-
- log.info("Message sent to R : "
- + String.format(isisFactorDistribution, factorNames,
- distribution, parameters));
- engine.voidEval(String.format(isisFactorDistribution, factorNames,
- distribution, parameters));
-
- log.info("Message sent to R : " + "call<-" + "\"x<-optimumLHS(n="
- + param_simulationNumber + ",k=" + factornumber
- + ",maxSweeps=" + param_MaxSweeps + ",eps=" + param_eps
- + ")\"");
- engine.voidEval("call<-" + "\"x<-optimumLHS(n="
- + param_simulationNumber + ",k=" + factornumber
- + ",maxSweeps=" + param_MaxSweeps + ",eps=" + param_eps
- + ")\"");
-
- log
- .info("Message sent to R : "
- + "isis.MethodExp<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"call\"=call)");
- engine
- .voidEval("isis.MethodExp<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"call\"=call)");
-
- log
- .info("Message sent to R : "
- + "attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : " + "isis.simule<-data.frame(x)");
- engine.voidEval("isis.simule<-data.frame(x)");
-
- log
- .info("Message sent to R : "
- + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : "
- + "names(isis.simule)<-isis.factors[[1]]");
- engine.voidEval("names(isis.simule)<-isis.factors[[1]]");
-
- String data = "data<-data.frame(";
-
- //Create the factors vectors and the dataframe instruction
- for (int j = 0; j < factors.size(); j++) {
- Factor factor = thisExperimentScenarios.get(0).getFactors()
- .get(j);
- if (factor.getDomain() instanceof EquationContinuousDomain) {
-
- //String vector = "factor" + j + "<-c(";
- String vector = factor.getName().replaceAll(" ", "")
- + "<-c(";
- for (int i = 0; i < param_simulationNumber; i++) {
- if (i < (param_simulationNumber - 1)) {
- vector = vector
- + ((EquationContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue() + ",";
- } else {
- vector = vector
- + ((EquationContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue();
- }
-
- }
- vector = vector + ")";
- engine.voidEval(vector);
- log.info("Message sent to R : " + vector);
- } else if (factor.getDomain() instanceof MatrixContinuousDomain) {
- //String vector = "factor" + j + "<-c(";
- String vector = factor.getName().replaceAll(" ", "")
- + "<-c(";
- for (int i = 0; i < param_simulationNumber; i++) {
- if (i < (param_simulationNumber - 1)) {
- vector = vector
- + ((MatrixContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue() + ",";
- } else {
- vector = vector
- + ((MatrixContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue();
- }
-
- }
- vector = vector + ")";
- engine.voidEval(vector);
- log.info("Message sent to R : " + vector);
- } else {
- //String vector = "factor" + j + "<-c(";
- String vector = factor.getName().replaceAll(" ", "")
- + "<-c(";
- for (int i = 0; i < param_simulationNumber; i++) {
- if (i < (param_simulationNumber - 1)) {
- vector = vector
- + thisExperimentScenarios.get(i)
- .getFactors().get(j).getValue()
- + ",";
- } else {
- vector = vector
- + thisExperimentScenarios.get(i)
- .getFactors().get(j).getValue();
- }
-
- }
- vector = vector + ")";
- engine.voidEval(vector);
- log.info("Message sent to R : " + vector);
- }
-
- if (j < factors.size() - 1) {
- data += factor.getName().replaceAll(" ", "") + "=factor("
- + factor.getName().replaceAll(" ", "") + "),";
- } else {
- data += factor.getName().replaceAll(" ", "") + "=factor("
- + factor.getName().replaceAll(" ", "") + "))";
- }
-
- }
- engine.voidEval(data);
- log.info("Message sent to R : " + data);
-
- // Creating the factors vector.
- rInstruction = "factornames<-c(";
- for (int i = 0; i < factornumber; i++) {
- if (i != (factornumber - 1)) {
- rInstruction = rInstruction + "\""
- + factors.get(i).getName() + "\",";
- } else {
- rInstruction = rInstruction + "\""
- + factors.get(i).getName() + "\"";
- }
- }
-
- rInstruction += ")";
-
- engine.voidEval(rInstruction);
- log.info("Message sent to R" + rInstruction);
-
- // Set output directory
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- log.info("Message sent to R : " + "setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- // Export the scenario matrix for the second run in a .optimumlhs.csv file
- engine.voidEval("write.csv(data,file=\".optimumlhs.csv\")");
- log.info("Message sent to R : "
- + "write.csv(data,file=\".optimumlhs.csv\")");
-
- // Export the factornames object for the second run in a .factornames file
- engine.voidEval("dput(factornames,file=\".factornames\")");
- log.info("Message sent to R"
- + "dput(factornames,file=\".factornames\")");
-
- //Set working directory to save Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- // Save Isis R session
- log.info("save.image(file=\"" + outputdirectory.getName() + ".RData\")");
- engine.voidEval("save.image(file=\"" + outputdirectory.getName()
- + ".RData\")");
-
- engine.terminate();
-
- } catch (Exception e) {
- e.printStackTrace();
- // Error while processing
- }
-
- return thisExperiment;
- }
-
- @Override
- public void analyzeResult(List<SimulationStorage> simulationStorages,
- File outputdirectory) throws SensitivityException {
-
- if ((Integer) param_simulationNumber == 0) {
- param_simulationNumber = 10;
- }
- if ((Integer) param_MaxSweeps == 0) {
- param_MaxSweeps = 2;
- }
-
- if ((Double) param_eps == 0) {
- param_eps = 0.1;
- }
-
- REngine engine = new RProxy();
- try {
-
- //Clear session
- log.info("rm(list=ls())");
- engine.voidEval("rm(list=ls())");
-
- //Set working directory to get Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- //Get Isis R session
- log.info("load(\"" + outputdirectory.getName() + ".RData\")");
- engine
- .voidEval("load(\"" + outputdirectory.getName()
- + ".RData\")");
-
- // Set output directory
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- log.info("Message sent to R : setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- //Get back the scenarios
- engine.voidEval("factors<-read.csv(\".optimumlhs.csv\")");
- log
- .info("Message sent to R : factors<-read.csv(\".optimumlhs.csv\")");
-
- // Get the factornames object in the .factornames file
- engine.voidEval("factornames<-dget(\".factornames\")");
- log.info("Message sent to R : "
- + "factornames<-dget(\".factornames\")");
-
- //Get back the factors number
- int factorNumber = ((Double) engine.eval("length(factors)-1"))
- .intValue();
-
- //Get back the simulation number
- param_simulationNumber = (Integer) (engine
- .eval("length(factors[,1])"));
-
- SimulationParameter param = simulationStorages.get(0)
- .getParameter();
- int sensitivityNumber = param.getSensitivityExport().size();
-
- for (int k = 0; k < sensitivityNumber; k++) {
-
- // Creates the R expression to import results in R
- String name = param.getSensitivityExport().get(k)
- .getExportFilename();
- String rInstruction = name + "<-c(";
- for (int l = 0; l < param_simulationNumber; l++) {
- File importFile = new File(simulationStorages.get(l)
- .getDirectory().toString()
- + File.separator
- + SimulationStorage.RESULT_EXPORT_DIRECTORY, param
- .getSensitivityExport().get(k).getExportFilename()
- + param.getSensitivityExport().get(k)
- .getExtensionFilename());
- String simulResult = FileUtil.readAsString(importFile);
- double simulationResult = Double.valueOf(simulResult);
- if (l < simulationStorages.size() - 1) {
- rInstruction = rInstruction + simulationResult + ",";
- } else {
- rInstruction = rInstruction + simulationResult;
- }
- }
- rInstruction = rInstruction + ")";
-
- log.info("Message sent to R : " + rInstruction);
-
- // Send the simulation results
- engine.voidEval(rInstruction);
-
- // Send the simulation results
- engine.voidEval(rInstruction);
-
- //Put results in isis.simule
- engine.voidEval("isis.simule<-data.frame(isis.simule," + name
- + ")");
- log.info("Message sent to R : "
- + "isis.simule<-data.frame(isis.simule," + name + ")");
- }
-
- //adding attribute to isis.Simule
- log
- .info("Message sent to R : "
- + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : "
- + "attr(isis.simule,\"call\")<-isis.MethodExp$call");
- engine.voidEval("attr(isis.simule,\"call\")<-isis.MethodExp$call");
-
- for (int k = 0; k < sensitivityNumber; k++) {
-
- // Creates the R expression to import results in R
- String name = param.getSensitivityExport().get(k)
- .getExportFilename();
-
- //Create the dataforaov data.frame
- String dataframe = "dataforaov<-data.frame(factors," + name
- + "=" + name + ")";
- engine.voidEval(dataframe);
- log.info("Message sent to R : " + dataframe);
-
- //Call aov()
- String aovCall = "aovresult<-aov(" + name + "~";
- for (int j = 0; j < factorNumber; j++) {
- log.info("Message sent to R : " + "names(factors)["
- + (j + 2) + "]");
-
- if (j < (factorNumber - 1)) {
- aovCall = aovCall
- + engine
- .eval("names(factors)[" + (j + 2) + "]")
- + "+";
- } else {
- aovCall = aovCall
- + engine
- .eval("names(factors)[" + (j + 2) + "]")
- + ",data=dataforaov)";
- }
- }
- engine.voidEval(aovCall);
- log.info("Message sent to R : " + aovCall);
-
- /*Export the results
- *Export format is csv, data separated by ','
- *Results Export name is sensitivityExportName_Results.csv
- *Sensitivity Indices export name is sensitivityExportName_SensitivityIndices.csv
- */
-
- //Compute Sum of Squares and Sensitivity indices
- engine.voidEval("SoS<-summary(aovresult)[[1]][1:"
- + factorNumber + ",2]");
- log.info("Message sent to R : SoS<-summary(aovresult)[[1]][1:"
- + factorNumber + ",2]");
- engine
- .voidEval("names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:"
- + factorNumber + "]");
- log
- .info("Message sent to R : names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:"
- + factorNumber + "]");
- engine.voidEval("IndSensibilite<-SoS/sum(SoS)");
- log.info("Message sent to R : IndSensibilite<-SoS/sum(SoS)");
-
- //Create a data.frame to export sensitivity important results in one file.
- engine.voidEval("exportsensitivity=data.frame(SoS[1:"
- + factorNumber + "],IndSensibilite[1:" + factorNumber
- + "])");
- log
- .info("Message sent to R : exportsensitivity=data.frame(SoS[1:"
- + factorNumber
- + "],IndSensibilite[1:"
- + factorNumber + "])");
- engine
- .voidEval("names(exportsensitivity)<-c(\"Sum Of Squares\",\"Sensitivity indices\")");
- log
- .info("Message sent to R : names(exportsensitivity)<-c(\"Sum Of Squares\",\"Sensitivity indices\")");
- engine.voidEval("row.names(exportsensitivity)<-factornames");
- log.info("Message sent to R : "
- + "row.names(exportsensitivity)<-factornames");
-
- //Set dataforaov names
- engine
- .voidEval("resultsnames<-c(\"Simulation\",factornames,\"Result\")");
- log
- .info("Message sent to R : "
- + "resultsnames<-c(\"Simulation\",factornames,\"Result\")");
- engine.voidEval("names(dataforaov)<-resultsnames");
- log.info("Message sent to R : "
- + "names(dataforaov)<-resultsnames");
-
- /*Set the export directory
- *Export directory is the first simulation export directory.
- */
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
- log.info("Message sent to R : setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
-
- //Save the results with the scenarios.
- engine.voidEval("write.csv(dataforaov,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Results.csv\")");
- log.info("Message sent to R : write.csv(dataforaov,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Results.csv\")");
-
- //Save the sensitivity indices
- engine.voidEval("write.csv(exportsensitivity,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename()
- + "_SensitivityIndices.csv\")");
- log.info("Message sent to R : write.csv(exportsensitivity,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename()
- + "_SensitivityIndices.csv\")");
- //FIXME export through java to enable export when using Rserve (when distant Rserve).
-
- //creating isis.methodAnalyse
- log
- .info("Message sent to R : "
- + "isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\""
- + aovCall + "\""
- + ",\"analysis_result\"=list(aovresult,IndSensibilite))");
- engine
- .voidEval("isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\""
- + aovCall
- + "\""
- + ",\"analysis_result\"=list(aovresult,IndSensibilite))");
-
- log
- .info("Message sent to R : "
- + "attr(isis.methodAnalyse,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.methodAnalyse,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- String renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-isis.methodAnalyse";
- String simulationName = simulationStorages.get(0).getName()
- .replaceAll("-", "");
- log.info("Message sent to R : "
- + String.format(renameIsisMethodAnalyse, simulationName
- + "." + name));
- engine.voidEval(String.format(renameIsisMethodAnalyse,
- simulationName + "." + name));
-
- }
-
- //Rename R objects for saving purpose
-
- String renameIsisSimule = "%s.isis.simule<-isis.simule";
- String renameIsisFactorDistribution = "%s.isis.factor.distribution<-isis.factor.distribution";
- String renameIsisFactor = "%s.isis.factor<-isis.factors";
- String renameIsisMethodExp = "%s.isis.methodExp<-isis.MethodExp";
-
- String simulationName = simulationStorages.get(0).getName()
- .replaceAll("-", "");
-
- log.info("Message sent to R : "
- + String.format(renameIsisSimule, simulationName));
- engine.voidEval(String.format(renameIsisSimule, simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisFactorDistribution,
- simulationName));
- engine.voidEval(String.format(renameIsisFactorDistribution,
- simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisFactor, simulationName));
- engine.voidEval(String.format(renameIsisFactor, simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisMethodExp, simulationName));
- engine.voidEval(String.format(renameIsisMethodExp, simulationName));
-
- //Set working directory to save Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- // Save Isis R session
- log.info("save.image(file=\"" + outputdirectory.getName() + ".RData\")");
- engine.voidEval("save.image(file=\"" + outputdirectory.getName()
- + ".RData\")");
-
- engine.terminate();
-
- } catch (Exception e) {
- e.printStackTrace();
- // Error while processing
- }
-
- }
-
- @Override
- public String getDescription() {
- return "Implementation of Random Latin Hypercube method method using R";
- }
-
-}
Copied: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorROptimumLHS.java (from rev 3393, isis-fish/trunk/src/test/resources/test-database/sensitivity/SensitivityCalculatorROptimumLHS.java)
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorROptimumLHS.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorROptimumLHS.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -0,0 +1,398 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+
+package sensitivityanalysis;
+
+import java.io.File;
+import java.util.List;
+
+import org.nuiton.j2r.REngine;
+import org.nuiton.j2r.RProxy;
+
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.export.SensitivityExport;
+import fr.ifremer.isisfish.simulator.SimulationParameter;
+import fr.ifremer.isisfish.simulator.sensitivity.AbstractSensitivityAnalysis;
+import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan;
+import fr.ifremer.isisfish.simulator.sensitivity.Factor;
+import fr.ifremer.isisfish.simulator.sensitivity.Scenario;
+import fr.ifremer.isisfish.simulator.sensitivity.SensitivityException;
+import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
+import fr.ifremer.isisfish.util.Doc;
+import org.nuiton.j2r.types.RDataFrame;
+
+/**
+ * Implementation of Optimum Latin Hypercube method using R.
+ *
+ * @author jcouteau
+ * @version $Revision$
+ */
+public class SensitivityCalculatorROptimumLHS extends
+ AbstractSensitivityAnalysis {
+
+ @Doc("Number of simulations (default=10)")
+ public int param_simulationNumber = 10;
+ @Doc("The maximum number of times the Columnwise Pairwise algorithm is applied to all the columns(default=2).")
+ public int param_MaxSweeps = 2;
+ @Doc("The optimal stopping criterion (between 0 and 1) (default=0.1).")
+ public double param_eps = 0.1;
+ @Doc("True to be able to modify the code sent to R")
+ public boolean param_modifR = false;
+
+ /**
+ * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
+ * continue.
+ *
+ * @return <tt>true</tt> s'il sait la gerer
+ */
+ @Override
+ public boolean canManageCardinality() {
+ return true;
+ }
+
+ @Override
+ public SensitivityScenarios compute(DesignPlan plan, File outputdirectory)
+ throws SensitivityException {
+
+ setIsisFactorsR(plan, outputdirectory);
+
+ int factorNumber = plan.getFactors().size();
+ List<Factor> factors = plan.getFactors();
+ RDataFrame dataFrame;
+ SensitivityScenarios thisExperiment = new SensitivityScenarios();
+ List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
+
+ //Test all factors, if one is discrete, return null
+ testNoDiscrete(factors);
+
+ try {
+ REngine engine = new RProxy();
+
+ //Clear session
+ engine.clearSession();
+
+ //Set working directory to get Isis R session
+ engine.loadRData(outputdirectory.getParentFile(),
+ outputdirectory.getName());
+
+ //Load the lhs library
+ engine.voidEval("library(lhs)");
+
+ String rInstruction = "x<-optimumLHS(n=%s,k=%s,maxSweeps=%s,eps=%s)";
+
+ String rCall = String.format(rInstruction, param_simulationNumber,
+ factorNumber, param_MaxSweeps, param_eps);
+
+ if (param_modifR) {
+ rCall = editRInstruction(rCall);
+ }
+
+ //Create the scenarios
+ engine.voidEval(rCall);
+
+ // Get back experiment plan
+ engine.eval("expPlan<-as.data.frame(x)");
+ dataFrame = (RDataFrame)engine.eval("expPlan");
+ dataFrame.setVariable("expPlan");
+
+ // Setting up the scenarios.
+ for (int j = 0; j < param_simulationNumber; j++) {
+ Scenario experimentScenario = new Scenario();
+ for (int i = 0; i < factorNumber; i++) {
+ Factor factor = plan.getFactors().get(i);
+ factor.setValueForIdentifier(dataFrame.get(i, j));
+ experimentScenario.addFactor(factor);
+ }
+ thisExperimentScenarios.add(experimentScenario);
+ thisExperiment.setScenarios(thisExperimentScenarios);
+ }
+
+ String isisFactorDistribution = "isis.factor.distribution<-" +
+ "data.frame(" +
+ "NomFacteur=c(%s)," +
+ "NomDistribution=c(%s)," +
+ "ParametreDistribution=c(%s))";
+
+ String distribution = "";
+ String parameters = "";
+ String factorNames = "";
+
+ for (int i = 0; i < factors.size(); i++) {
+ Factor tempFactor = factors.get(i);
+ ContinuousDomain domain = (ContinuousDomain) tempFactor.getDomain();
+ if (i != 0) {
+ distribution += ",";
+ factorNames += ",";
+ parameters += ",";
+ }
+
+ factorNames += "\"" + factors.get(i).getName() + "\"";
+ distribution += "\"qunif\"";
+ //add [min;max] to parameters
+ parameters += "\"[" + domain.getMinBound() + ";" +
+ domain.getMaxBound() + "]\"";
+ }
+
+ engine.voidEval(String.format(isisFactorDistribution, factorNames,
+ distribution, parameters));
+
+ engine.voidEval("call<-" + "\"x<-optimumLHS("
+ + "n=" + param_simulationNumber
+ + ",k=" + factorNumber
+ + ",maxSweeps=" + param_MaxSweeps
+ + ",eps=" + param_eps + ")\"");
+
+ engine.voidEval("isis.MethodExp<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"call\"=call)");
+
+ engine.voidEval("attr(isis.MethodExp," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ engine.voidEval("isis.simule<-data.frame(x)");
+
+ engine.voidEval("attr(isis.simule," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ engine.voidEval("names(isis.simule)<-isis.factors[[1]]");
+
+ String data = "data<-data.frame(";
+
+ //Create the factors vectors and the dataFrame instruction
+ for (int j = 0; j < factors.size(); j++) {
+ //The factor values vector
+ String vector;
+ //Get back the factor
+ Scenario scenario = thisExperimentScenarios.get(0);
+ Factor factor = scenario.getFactors().get(j);
+ String factorName = factor.getName().replaceAll(" ", "");
+
+ vector = factorName + "<-c(";
+ for (int i = 0; i < param_simulationNumber; i++) {
+ //Get back the displayed value the factor
+ Scenario tempScenario = thisExperimentScenarios.get(i);
+ Factor tempFactor = tempScenario.getFactors().get(j);
+ Object value = tempFactor.getDisplayedValue();
+
+ if (i < (param_simulationNumber - 1)) {
+ vector = vector + value + ",";
+ } else {
+ vector += value;
+ }
+
+ }
+ vector += ")";
+ engine.voidEval(vector);
+
+ if (j < factors.size() - 1) {
+ data += factorName + "=factor(" + factorName + "),";
+ } else {
+ data += factorName + "=factor(" + factorName + "))";
+ }
+ }
+ engine.voidEval(data);
+
+ // Creating the factors vector.
+ rInstruction = "factornames<-c(";
+ for (int i = 0; i < factorNumber; i++) {
+ if (i != (factorNumber - 1)) {
+ rInstruction = rInstruction + "\""
+ + factors.get(i).getName() + "\",";
+ } else {
+ rInstruction = rInstruction + "\""
+ + factors.get(i).getName() + "\"";
+ }
+ }
+
+ rInstruction += ")";
+
+ engine.voidEval(rInstruction);
+
+ // Save Isis R session
+ engine.saveRData(outputdirectory.getParentFile(),
+ outputdirectory.getName());
+
+ engine.terminate();
+
+ } catch (Exception e) {
+ throw new SensitivityException("Can't generate scenarios", e);
+ }
+
+ return thisExperiment;
+ }
+
+ @Override
+ public void analyzeResult(List<SimulationStorage> simulationStorages,
+ File outputDirectory) throws SensitivityException {
+
+ //The first storage to get the name and parameters all along the method
+ SimulationStorage storage = simulationStorages.get(0);
+
+ String simulationName = storage.getName().replaceAll("-", "");
+
+ try {
+
+ REngine engine = new RProxy();
+
+ //Clear session
+ engine.clearSession();
+
+ //Get Isis R session
+ engine.loadRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ engine.voidEval("factors<-data.frame(x)");
+ engine.voidEval("names(factors)<-factornames");
+
+ //Get back the factors number
+ int factorNumber = (Integer) engine.eval("length(factors[1,])");
+ //Get back the simulation number
+ param_simulationNumber = (Integer) (engine.eval("length(factors[,1])"));
+
+ SimulationParameter param = storage.getParameter();
+ int sensitivityNumber = param.getSensitivityExport().size();
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ SensitivityExport sensitivityExport =
+ param.getSensitivityExport().get(k);
+
+ String rInstruction = createImportInstruction(sensitivityExport,
+ simulationStorages);
+
+ // Send the simulation results
+ engine.voidEval(rInstruction);
+
+ //Put results in isis.simule
+ engine.voidEval("isis.simule<-data.frame(isis.simule," +
+ sensitivityExport.getExportFilename() + ")");
+ }
+
+ //adding attribute to isis.Simule
+ engine.voidEval("attr(isis.simule," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+ engine.voidEval("attr(isis.simule,\"call\")<-isis.MethodExp$call");
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ // Creates the R expression to import results in R
+ SensitivityExport export = param.getSensitivityExport().get(k);
+ String name = export.getExportFilename();
+
+ //Create the dataforaov data.frame
+ String dataframe = "dataforaov<-data.frame(factors," +
+ name + "=" + name + ")";
+ engine.voidEval(dataframe);
+
+ //Call aov()
+ String aovCall = "aovresult<-aov(" + name + "~";
+ for (int j = 0; j < factorNumber; j++) {
+
+ String factorName = (String) engine.eval("names(factors)[" + (j + 1) + "]");
+ factorName = factorName.replaceAll(" ", ".");
+
+ if (j < (factorNumber - 1)) {
+ aovCall += factorName +
+ "+";
+ } else {
+ aovCall += factorName + ",data=dataforaov)";
+ }
+ }
+ engine.voidEval(aovCall);
+
+ /*Export the results
+ *Export format is csv, data separated by ','
+ *Results Export name is sensitivityExportName_Results.csv
+ *Sensitivity Indices export name is sensitivityExportName_SensitivityIndices.csv
+ */
+
+ //Compute Sum of Squares and Sensitivity indices
+ engine.voidEval("SoS<-summary(aovresult)[[1]][1:dim(summary(aovresult)[[1]])[1],2]");
+ engine.voidEval("names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:dim(summary(aovresult)[[1]])[1]]");
+ engine.voidEval("IndSensibilite<-SoS/sum(SoS)");
+
+ //Create a data.frame to export sensitivity important results in one file.
+ engine.voidEval("exportsensitivity<-data.frame(" +
+ "SoS[1:dim(summary(aovresult)[[1]])[1]]," +
+ "IndSensibilite[1:dim(summary(aovresult)[[1]])[1]])");
+ engine.voidEval("names(exportsensitivity)<-c(" +
+ "\"Sum Of Squares\"," +
+ "\"Sensitivity indices\")");
+ engine.voidEval("row.names(exportsensitivity)<-dimnames(summary(aovresult)[[1]])[1][[1]][1:dim(summary(aovresult)[[1]])[1]]");
+
+
+ //Set dataforaov names
+ engine.voidEval("names(dataforaov)<-c(factornames,\"Result\")");
+
+ /*Set the export directory
+ *Export directory is the first simulation export directory.
+ */
+ engine.setwd(outputDirectory);
+
+ //Save the results with the scenarios.
+ engine.voidEval("write.csv(dataforaov,\"" +
+ name + "_Results.csv\")");
+
+ //Save the sensitivity indices
+ engine.voidEval("write.csv(exportsensitivity,\"" +
+ name + "_SensitivityIndices.csv\")");
+ //FIXME export through java to enable export when using Rserve (when distant Rserve).
+
+ //creating isis.methodAnalyse
+ engine.voidEval("isis.methodAnalyse<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"isis.simule\"=isis.simule," +
+ "call_method=\"" + aovCall + "\""+
+ ",\"analysis_result\"=list(aovresult,IndSensibilite))");
+
+ engine.voidEval("attr(isis.methodAnalyse," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ String renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-" +
+ "isis.methodAnalyse";
+
+ engine.voidEval(String.format(renameIsisMethodAnalyse,
+ simulationName + "." + name));
+
+ }
+
+ //Rename R objects for saving purpose
+ renameObjects(engine, simulationName);
+
+ engine.terminate();
+
+ } catch (Exception e) {
+ throw new SensitivityException("Can't evaluate results", e);
+ }
+
+ }
+
+ @Override
+ public String getDescription() {
+ return "Implementation of Random Latin Hypercube method method " +
+ "using R (needs 'lhs' package to work)";
+ }
+
+}
Deleted: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRRandomLHS.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivity/SensitivityCalculatorRRandomLHS.java 2011-06-14 13:21:14 UTC (rev 3392)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRRandomLHS.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,706 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-
-package sensitivity;
-
-import java.io.File;
-import java.util.List;
-
-import javax.swing.Box;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JScrollPane;
-import javax.swing.JTextPane;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.codelutin.j2r.REngine;
-import org.codelutin.j2r.RProxy;
-import org.codelutin.math.matrix.MatrixFactory;
-import org.codelutin.math.matrix.MatrixND;
-import org.codelutin.util.FileUtil;
-
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.simulator.SimulationParameter;
-import fr.ifremer.isisfish.simulator.sensitivity.AbstractSensitivityCalculator;
-import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan;
-import fr.ifremer.isisfish.simulator.sensitivity.Domain;
-import fr.ifremer.isisfish.simulator.sensitivity.Factor;
-import fr.ifremer.isisfish.simulator.sensitivity.Scenario;
-import fr.ifremer.isisfish.simulator.sensitivity.SensitivityException;
-import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.DiscreteDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.EquationContinuousDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.MatrixContinuousDomain;
-import fr.ifremer.isisfish.util.Doc;
-
-/**
- * Implementation of Random Latin Hypercube method using R.
- *
- * @author jcouteau
- * @version $Revision$
- */
-public class SensitivityCalculatorRRandomLHS extends
- AbstractSensitivityCalculator {
-
- /** to use log facility, just put in your code: log.info("..."); */
- static private Log log = LogFactory
- .getLog(SensitivityCalculatorRRandomLHS.class);
-
- @Doc("Simulation number (default=10)")
- public int param_simulationNumber = 10;
- @Doc("True to be able to modify the code sent to R")
- public boolean param_modifR = false;
-
- /**
- * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
- * continue.
- *
- * @return <tt>true</tt> s'il sait la gerer
- */
- @Override
- public boolean canManageCardinality() {
- return true;
- }
-
- @Override
- public SensitivityScenarios compute(DesignPlan plan, File outputdirectory)
- throws SensitivityException {
-
- setIsisFactorsR(plan, outputdirectory);
-
- int factornumber = plan.getFactors().size();
- double[] dataframe = new double[0];
- SensitivityScenarios thisExperiment = new SensitivityScenarios();
- List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
- List<Factor<?, ?>> factors = plan.getFactors();
-
- //Test all factors, if one is discrete, return null
- for (int i = 0; i < factors.size(); i++) {
- if (factors.get(i).getDomain() instanceof DiscreteDomain) {
- JOptionPane
- .showMessageDialog(
- null,
- "Error",
- factors.get(i).getName()
- + " has a discrete domain, this is not acceptable for this method.",
- JOptionPane.ERROR_MESSAGE);
- return null;
- }
- }
-
- if ((Integer) param_simulationNumber == 0) {
- param_simulationNumber = 10;
- }
-
- REngine engine = new RProxy();
- try {
-
- //Clear session
- log.info("rm(list=ls())");
- engine.voidEval("rm(list=ls())");
-
- //Set working directory to get Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- //Get Isis R session
- log.info("load(\"" + outputdirectory.getName() + ".RData\")");
- engine
- .voidEval("load(\"" + outputdirectory.getName()
- + ".RData\")");
-
- //Set working directory for other results
- log.info("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- //Load the lhs library
- engine.voidEval("library(lhs)");
- log.info("Message sent to R : " + "library(lhs)");
-
- //Create the scenarios
- String rInstruction = "x<-randomLHS(%s,%s)";
- String rCall = String.format(rInstruction, param_simulationNumber,
- factornumber);
-
- if (param_modifR) {
- JLabel label = new JLabel(
- "Modifier le code R envoyé si vous le souhaitez");
- JTextPane text = new JTextPane();
- text.setText(rCall);
- text.setSize(400, 400);
- text.setPreferredSize(text.getSize());
-
- Box box = Box.createVerticalBox();
- box.add(label);
- box.add(new JScrollPane(text));
-
- JOptionPane.showMessageDialog(null, box, "R modif",
- JOptionPane.QUESTION_MESSAGE);
- rCall = text.getText();
- }
-
- engine.voidEval(rCall);
- log.info("Message sent to R : " + rCall);
-
- // Get back experiment plan
- dataframe = (double[]) engine.eval("x");
- log.info("Message sent to R" + "x");
-
- // Transform the result from R in a matrix
- MatrixND morris = MatrixFactory.getInstance().create(dataframe,
- new int[] { factornumber, param_simulationNumber });
-
- // Setting up the scenarios.
- for (int j = 0; j < param_simulationNumber; j++) {
- Scenario experimentScenario = new Scenario();
- for (int i = 0; i < factornumber; i++) {
- Factor factor = plan.getFactors().get(i);
- if ((factor.getDomain() instanceof MatrixContinuousDomain)
- || (factor.getDomain() instanceof EquationContinuousDomain)) {
- factor.setValueForIdentifier(morris.getValue(new int[] {
- i, j }));
- } else {
- Double value = (Double) ((ContinuousDomain) factor
- .getDomain()).getMinBound()
- + ((Double) ((ContinuousDomain) factor
- .getDomain()).getMaxBound() - (Double) ((ContinuousDomain) factor
- .getDomain()).getMinBound())
- * morris.getValue(new int[] { i, j });
- factor.setValueForIdentifier(value);
- }
- experimentScenario.addFactor(factor);
- }
- thisExperimentScenarios.add(experimentScenario);
- thisExperiment.setScenarios(thisExperimentScenarios);
- }
-
- String isisFactorDistribution = "isis.factor.distribution<-data.frame(NomFacteur=c(%s),NomDistribution=c(%s),ParametreDistribution=c(%s))";
-
- String distribution = "";
- String parameters = "";
- String factorNames = "";
-
- for (int i = 0; i < factors.size(); i++) {
- Domain domain = factors.get(i).getDomain();
- if (i != 0) {
- distribution += ",";
- factorNames += ",";
- parameters += ",";
- }
-
- factorNames += "\"" + factors.get(i).getName() + "\"";
- distribution += "\"qunif\"";
- parameters += "\"[" + ((ContinuousDomain) domain).getMinBound()
- + ";" + ((ContinuousDomain) domain).getMaxBound()
- + "]\"";
- }
-
- log.info("Message sent to R : "
- + String.format(isisFactorDistribution, factorNames,
- distribution, parameters));
- engine.voidEval(String.format(isisFactorDistribution, factorNames,
- distribution, parameters));
-
- log.info("Message sent to R : " + "call<-" + "\"x<-randomLHS("
- + param_simulationNumber + "," + factornumber + ")\"");
- engine.voidEval("call<-" + "\"x<-randomLHS("
- + param_simulationNumber + "," + factornumber + ")\"");
-
- log
- .info("Message sent to R : "
- + "isis.MethodExp<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"call\"=call)");
- engine
- .voidEval("isis.MethodExp<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"call\"=call)");
-
- log
- .info("Message sent to R : "
- + "attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : " + "isis.simule<-data.frame(x)");
- engine.voidEval("isis.simule<-data.frame(x)");
-
- log
- .info("Message sent to R : "
- + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : "
- + "names(isis.simule)<-isis.factors[[1]]");
- engine.voidEval("names(isis.simule)<-isis.factors[[1]]");
-
- String data = "data<-data.frame(";
-
- //Create the factors vectors and the dataframe instruction
- for (int j = 0; j < factors.size(); j++) {
- Factor factor = thisExperimentScenarios.get(0).getFactors()
- .get(j);
- if (factor.getDomain() instanceof EquationContinuousDomain) {
-
- //String vector = "factor" + j + "<-c(";
- String vector = factor.getName().replaceAll(" ", "")
- + "<-c(";
- for (int i = 0; i < param_simulationNumber; i++) {
- if (i < (param_simulationNumber - 1)) {
- vector = vector
- + ((EquationContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue() + ",";
- } else {
- vector = vector
- + ((EquationContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue();
- }
-
- }
- vector = vector + ")";
- engine.voidEval(vector);
- log.info("Message sent to R : " + vector);
- } else if (factor.getDomain() instanceof MatrixContinuousDomain) {
- //String vector = "factor" + j + "<-c(";
- String vector = factor.getName().replaceAll(" ", "")
- + "<-c(";
- for (int i = 0; i < param_simulationNumber; i++) {
- if (i < (param_simulationNumber - 1)) {
- vector = vector
- + ((MatrixContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue() + ",";
- } else {
- vector = vector
- + ((MatrixContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue();
- }
-
- }
- vector = vector + ")";
- engine.voidEval(vector);
- log.info("Message sent to R : " + vector);
- } else {
- //String vector = "factor" + j + "<-c(";
- String vector = factor.getName().replaceAll(" ", "")
- + "<-c(";
- for (int i = 0; i < param_simulationNumber; i++) {
- if (i < (param_simulationNumber - 1)) {
- vector = vector
- + thisExperimentScenarios.get(i)
- .getFactors().get(j).getValue()
- + ",";
- } else {
- vector = vector
- + thisExperimentScenarios.get(i)
- .getFactors().get(j).getValue();
- }
-
- }
- vector = vector + ")";
- engine.voidEval(vector);
- log.info("Message sent to R : " + vector);
- }
-
- if (j < factors.size() - 1) {
- data += factor.getName().replaceAll(" ", "") + "=factor("
- + factor.getName().replaceAll(" ", "") + "),";
- } else {
- data += factor.getName().replaceAll(" ", "") + "=factor("
- + factor.getName().replaceAll(" ", "") + "))";
- }
-
- }
- engine.voidEval(data);
- log.info("Message sent to R : " + data);
-
- // Creating the factors vector.
- rInstruction = "factornames<-c(";
- for (int i = 0; i < factornumber; i++) {
- if (i != (factornumber - 1)) {
- rInstruction = rInstruction + "\""
- + factors.get(i).getName() + "\",";
- } else {
- rInstruction = rInstruction + "\""
- + factors.get(i).getName() + "\"";
- }
- }
-
- rInstruction += ")";
-
- engine.voidEval(rInstruction);
- log.info("Message sent to R" + rInstruction);
-
- // Set output directory
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- log.info("Message sent to R : " + "setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- // Export the scenario matrix for the second run in a .randomlhs.csv file
- engine.voidEval("write.csv(data,file=\".randomlhs.csv\")");
- log.info("Message sent to R : "
- + "write.csv(data,file=\".randomlhs.csv\")");
-
- // Export the factornames object for the second run in a .factornames file
- engine.voidEval("dput(factornames,file=\".factornames\")");
- log.info("Message sent to R"
- + "dput(factornames,file=\".factornames\")");
-
- //Set working directory to save Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- // Save Isis R session
- log.info("save.image(file=\"" + outputdirectory.getName() + ".RData\")");
- engine.voidEval("save.image(file=\"" + outputdirectory.getName()
- + ".RData\")");
-
- engine.terminate();
-
- } catch (Exception e) {
- e.printStackTrace();
- // Error while processing
- }
-
- return thisExperiment;
- }
-
- @Override
- public void analyzeResult(List<SimulationStorage> simulationStorages,
- File outputdirectory) throws SensitivityException {
-
- if ((Integer) param_simulationNumber == 0) {
- param_simulationNumber = 10;
- }
-
- REngine engine = new RProxy();
- try {
-
- //Clear session
- log.info("rm(list=ls())");
- engine.voidEval("rm(list=ls())");
-
- //Set working directory to get Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- //Get Isis R session
- log.info("load(\"" + outputdirectory.getName() + ".RData\")");
- engine
- .voidEval("load(\"" + outputdirectory.getName()
- + ".RData\")");
-
- // Set output directory
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- log.info("Message sent to R : setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- //Get back the scenarios
- engine.voidEval("factors<-read.csv(\".randomlhs.csv\")");
- log
- .info("Message sent to R : factors<-read.csv(\".randomlhs.csv\")");
-
- // Get the factornames object in the .factornames file
- engine.voidEval("factornames<-dget(\".factornames\")");
- log.info("Message sent to R : "
- + "factornames<-dget(\".factornames\")");
-
- //Get back the factors number
- int factorNumber = ((Double) engine.eval("length(factors)-1"))
- .intValue();
-
- //Get back the simulation number
- param_simulationNumber = (Integer) (engine
- .eval("length(factors[,1])"));
-
- SimulationParameter param = simulationStorages.get(0)
- .getParameter();
- int sensitivityNumber = param.getSensitivityExport().size();
-
- for (int k = 0; k < sensitivityNumber; k++) {
-
- // Creates the R expression to import results in R
- String name = param.getSensitivityExport().get(k)
- .getExportFilename();
- String rInstruction = name + "<-c(";
- for (int l = 0; l < simulationStorages.size(); l++) {
- File importFile = new File(simulationStorages.get(l)
- .getDirectory().toString()
- + File.separator
- + SimulationStorage.RESULT_EXPORT_DIRECTORY, param
- .getSensitivityExport().get(k).getExportFilename()
- + param.getSensitivityExport().get(k)
- .getExtensionFilename());
- String simulResult = FileUtil.readAsString(importFile);
- double simulationResult = Double.valueOf(simulResult);
- if (l < simulationStorages.size() - 1) {
- rInstruction = rInstruction + simulationResult + ",";
- } else {
- rInstruction = rInstruction + simulationResult;
- }
- }
- rInstruction = rInstruction + ")";
-
- log.info("Message sent to R : " + rInstruction);
-
- // Send the simulation results
- engine.voidEval(rInstruction);
-
- //Put results in isis.simule
- engine.voidEval("isis.simule<-data.frame(isis.simule," + name
- + ")");
- log.info("Message sent to R : "
- + "isis.simule<-data.frame(isis.simule," + name + ")");
- }
-
- //adding attribute to isis.Simule
- log
- .info("Message sent to R : "
- + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : "
- + "attr(isis.simule,\"call\")<-isis.MethodExp$call");
- engine.voidEval("attr(isis.simule,\"call\")<-isis.MethodExp$call");
-
- for (int k = 0; k < sensitivityNumber; k++) {
-
- // Creates the R expression to import results in R
- String name = param.getSensitivityExport().get(k)
- .getExportFilename();
-
- //Create the dataforaov data.frame
- String dataframe = "dataforaov<-data.frame(factors," + name
- + "=" + name + ")";
- engine.voidEval(dataframe);
- log.info("Message sent to R : " + dataframe);
-
- //Call aov()
- String aovCall = "aovresult<-aov(" + name + "~";
- for (int j = 0; j < factorNumber; j++) {
- log.info("Message sent to R : " + "names(factors)["
- + (j + 2) + "]");
-
- if (j < (factorNumber - 1)) {
- aovCall = aovCall
- + engine
- .eval("names(factors)[" + (j + 2) + "]")
- + "+";
- } else {
- aovCall = aovCall
- + engine
- .eval("names(factors)[" + (j + 2) + "]")
- + ",data=dataforaov)";
- }
- }
- engine.voidEval(aovCall);
- log.info("Message sent to R : " + aovCall);
-
- /*Export the results
- *Export format is csv, data separated by ','
- *Results Export name is sensitivityExportName_Results.csv
- *Sensitivity Indices export name is sensitivityExportName_SensitivityIndices.csv
- */
-
- //Compute Sum of Squares and Sensitivity indices
- engine.voidEval("SoS<-summary(aovresult)[[1]][1:"
- + factorNumber + ",2]");
- log.info("Message sent to R : SoS<-summary(aovresult)[[1]][1:"
- + factorNumber + ",2]");
- engine
- .voidEval("names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:"
- + factorNumber + "]");
- log
- .info("Message sent to R : names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:"
- + factorNumber + "]");
- engine.voidEval("IndSensibilite<-SoS/sum(SoS)");
- log.info("Message sent to R : IndSensibilite<-SoS/sum(SoS)");
-
- //Create a data.frame to export sensitivity important results in one file.
- engine.voidEval("exportsensitivity=data.frame(SoS[1:"
- + factorNumber + "],IndSensibilite[1:" + factorNumber
- + "])");
- log
- .info("Message sent to R : exportsensitivity=data.frame(SoS[1:"
- + factorNumber
- + "],IndSensibilite[1:"
- + factorNumber + "])");
- engine
- .voidEval("names(exportsensitivity)<-c(\"Sum Of Squares\",\"Sensitivity indices\")");
- log
- .info("Message sent to R : names(exportsensitivity)<-c(\"Sum Of Squares\",\"Sensitivity indices\")");
- engine.voidEval("row.names(exportsensitivity)<-factornames");
- log.info("Message sent to R : "
- + "row.names(exportsensitivity)<-factornames");
-
- //Set dataforaov names
- engine
- .voidEval("resultsnames<-c(\"Simulation\",factornames,\"Result\")");
- log
- .info("Message sent to R : "
- + "resultsnames<-c(\"Simulation\",factornames,\"Result\")");
- engine.voidEval("names(dataforaov)<-resultsnames");
- log.info("Message sent to R : "
- + "names(dataforaov)<-resultsnames");
-
- /*Set the export directory
- *Export directory is the first simulation export directory.
- */
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
- log.info("Message sent to R : setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
-
- //Save the results with the scenarios.
- engine.voidEval("write.csv(dataforaov,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Results.csv\")");
- log.info("Message sent to R : write.csv(dataforaov,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Results.csv\")");
-
- //Save the sensitivity indices
- engine.voidEval("write.csv(exportsensitivity,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename()
- + "_SensitivityIndices.csv\")");
- log.info("Message sent to R : write.csv(exportsensitivity,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename()
- + "_SensitivityIndices.csv\")");
- //FIXME export through java to enable export when using Rserve (when distant Rserve).
-
- //creating isis.methodAnalyse
- log
- .info("Message sent to R : "
- + "isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\""
- + aovCall + "\""
- + ",\"analysis_result\"=list(aovresult,IndSensibilite))");
- engine
- .voidEval("isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\""
- + aovCall
- + "\""
- + ",\"analysis_result\"=list(aovresult,IndSensibilite))");
-
- log
- .info("Message sent to R : "
- + "attr(isis.methodAnalyse,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.methodAnalyse,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- String renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-isis.methodAnalyse";
- String simulationName = simulationStorages.get(0).getName()
- .replaceAll("-", "");
- log.info("Message sent to R : "
- + String.format(renameIsisMethodAnalyse, simulationName
- + "." + name));
- engine.voidEval(String.format(renameIsisMethodAnalyse,
- simulationName + "." + name));
-
- }
-
- //Rename R objects for saving purpose
-
- String renameIsisSimule = "%s.isis.simule<-isis.simule";
- String renameIsisFactorDistribution = "%s.isis.factor.distribution<-isis.factor.distribution";
- String renameIsisFactor = "%s.isis.factor<-isis.factors";
- String renameIsisMethodExp = "%s.isis.methodExp<-isis.MethodExp";
-
- String simulationName = simulationStorages.get(0).getName()
- .replaceAll("-", "");
-
- log.info("Message sent to R : "
- + String.format(renameIsisSimule, simulationName));
- engine.voidEval(String.format(renameIsisSimule, simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisFactorDistribution,
- simulationName));
- engine.voidEval(String.format(renameIsisFactorDistribution,
- simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisFactor, simulationName));
- engine.voidEval(String.format(renameIsisFactor, simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisMethodExp, simulationName));
- engine.voidEval(String.format(renameIsisMethodExp, simulationName));
-
- //Set working directory to save Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- // Save Isis R session
- log.info("save.image(file=\"" + outputdirectory.getName() + ".RData\")");
- engine.voidEval("save.image(file=\"" + outputdirectory.getName()
- + ".RData\")");
-
- engine.terminate();
-
- } catch (Exception e) {
- e.printStackTrace();
- // Error while processing
- }
-
- }
-
- @Override
- public String getDescription() {
- return "Implementation of Random Latin Hypercube method method using R";
- }
-
-}
Copied: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRRandomLHS.java (from rev 3393, isis-fish/trunk/src/test/resources/test-database/sensitivity/SensitivityCalculatorRRandomLHS.java)
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRRandomLHS.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRRandomLHS.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -0,0 +1,389 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+
+package sensitivityanalysis;
+
+import java.io.File;
+import java.util.List;
+
+import fr.ifremer.isisfish.export.SensitivityExport;
+import org.nuiton.j2r.REngine;
+import org.nuiton.j2r.RProxy;
+import org.nuiton.j2r.types.RDataFrame;
+
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.simulator.SimulationParameter;
+import fr.ifremer.isisfish.simulator.sensitivity.AbstractSensitivityAnalysis;
+import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan;
+import fr.ifremer.isisfish.simulator.sensitivity.Factor;
+import fr.ifremer.isisfish.simulator.sensitivity.Scenario;
+import fr.ifremer.isisfish.simulator.sensitivity.SensitivityException;
+import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
+import fr.ifremer.isisfish.util.Doc;
+
+/**
+ * Implementation of Random Latin Hypercube method using R.
+ *
+ * @author jcouteau
+ * @version $Revision$
+ */
+public class SensitivityCalculatorRRandomLHS extends
+ AbstractSensitivityAnalysis {
+
+ @Doc("Simulation number (default=10)")
+ public int param_simulationNumber = 10;
+ @Doc("True to be able to modify the code sent to R")
+ public boolean param_modifR = false;
+
+ /**
+ * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
+ * continue.
+ *
+ * @return <tt>true</tt> s'il sait la gerer
+ */
+ @Override
+ public boolean canManageCardinality() {
+ return true;
+ }
+
+ @Override
+ public SensitivityScenarios compute(DesignPlan plan, File outputDirectory)
+ throws SensitivityException {
+
+ setIsisFactorsR(plan, outputDirectory);
+
+ int factorNumber = plan.getFactors().size();
+ RDataFrame dataFrame; //The dataframe to get back the scenarios from R
+ SensitivityScenarios thisExperiment = new SensitivityScenarios(); //The experiment we will build
+ List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios(); //The list of scenarios
+ List<Factor> factors = plan.getFactors(); //The factors
+
+ testNoDiscrete(factors);
+
+ try {
+
+ REngine engine = new RProxy(); //The R engine
+
+ //Clear session
+ engine.clearSession();
+
+ //Get Isis R session
+ engine.loadRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ //Load the lhs library
+ engine.voidEval("library(lhs)");
+
+ //Create the scenarios
+ String rInstruction = "x<-randomLHS(%s,%s)";
+ String rCall = String.format(rInstruction, param_simulationNumber,
+ factorNumber);
+
+ if (param_modifR) {
+ rCall = editRInstruction(rCall);
+ }
+
+ engine.voidEval(rCall);
+
+ // Get back experiment plan
+ engine.eval("expPlan<-as.data.frame(x)");
+ dataFrame = (RDataFrame)engine.eval("expPlan");
+ dataFrame.setVariable("expPlan");
+
+ // Setting up the scenarios.
+ for (int j = 0; j < param_simulationNumber; j++) {
+ Scenario experimentScenario = new Scenario();
+ for (int i = 0; i < factorNumber; i++) {
+ Factor factor = plan.getFactors().get(i); //The factor we are setting
+ factor.setValueForIdentifier(dataFrame.get(i,j));
+ experimentScenario.addFactor(factor);
+ }
+ thisExperimentScenarios.add(experimentScenario);
+ thisExperiment.setScenarios(thisExperimentScenarios);
+ }
+
+ String isisFactorDistribution = "isis.factor.distribution<-" +
+ "data.frame(" +
+ "NomFacteur=c(%s)," +
+ "NomDistribution=c(%s)," +
+ "ParametreDistribution=c(%s))";
+
+ String distribution = "";
+ String parameters = "";
+ String factorNames = "";
+
+
+ //Create the strings for the isis.MethodExp instruction
+ for (int i = 0; i < factors.size(); i++) {
+ ContinuousDomain domain = (ContinuousDomain)factors.get(i).getDomain();
+ if (i != 0) {
+ distribution += ","; //the distribution
+ factorNames += ","; //the factor names
+ parameters += ","; //the parameters
+ }
+
+ factorNames += "\"" + factors.get(i).getName() + "\"";
+ distribution += "\"qunif\""; //all distributions are qunif
+ double min = domain.getCalculatorMinBound();
+ double max = domain.getCalculatorMaxBound();
+ parameters += "\"[" + min + ";" + max + "]\"";
+ }
+ engine.voidEval(String.format(isisFactorDistribution, factorNames,
+ distribution, parameters));
+
+ engine.voidEval("call<-" + "\"x<-randomLHS("
+ + param_simulationNumber + "," + factorNumber + ")\"");
+
+ engine.voidEval("isis.MethodExp<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"call\"=call)");
+
+ engine.voidEval("attr(isis.MethodExp," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ engine.voidEval("isis.simule<-data.frame(x)");
+ engine.voidEval("attr(isis.simule," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+ engine.voidEval("names(isis.simule)<-isis.factors[[1]]");
+
+ String data = "data<-data.frame(";
+
+ //Create the factors vectors and the dataFrame instruction
+ for (int j = 0; j < factors.size(); j++) {
+ Scenario firstScenario = thisExperimentScenarios.get(0);
+ Factor factor = firstScenario.getFactors().get(j);
+ String factorName = factor.getName().replaceAll(" ", "");
+
+ //the vector of the factor values
+ //read all the values one by one from the already created
+ //scenarios.
+ String vector = factorName + "<-c(";
+ for (int i = 0; i < param_simulationNumber; i++) {
+ Scenario scenario = thisExperimentScenarios.get(i);
+ List<Factor> factorList = scenario.getFactors();
+ Factor factor1 = factorList.get(j);
+ if (i < (param_simulationNumber - 1)) {
+ vector += factor1.getDisplayedValue() + ",";
+ } else {
+ vector += factor1.getDisplayedValue();
+ }
+
+ }
+ vector = vector + ")";
+ engine.voidEval(vector);
+
+ //add factor1=factor(factor1) for each factor...
+ if (j < factors.size() - 1) {
+ data += factorName + "=factor(" + factorName + "),";
+ } else {
+ data += factorName + "=factor(" + factorName + "))";
+ }
+
+ }
+ engine.voidEval(data);
+
+ // Creating the factors vector.
+ rInstruction = "factornames<-c(";
+ for (int i = 0; i < factorNumber; i++) {
+ if (i != (factorNumber - 1)) {
+ rInstruction = rInstruction + "\""
+ + factors.get(i).getName() + "\",";
+ } else {
+ rInstruction = rInstruction + "\""
+ + factors.get(i).getName() + "\"";
+ }
+ }
+ rInstruction += ")";
+ engine.voidEval(rInstruction);
+
+ // Save Isis R session
+ engine.saveRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ engine.terminate();
+
+ } catch (Exception e) {
+ throw new SensitivityException("Can't generate scenarios", e);
+ }
+
+ return thisExperiment;
+ }
+
+ @Override
+ public void analyzeResult(List<SimulationStorage> simulationStorages,
+ File outputDirectory) throws SensitivityException {
+
+ SimulationStorage simulationStorage1 = simulationStorages.get(0);
+ String simName = simulationStorage1.getName();
+ String simulationName = simName.replaceAll("-", "");
+ SimulationParameter param = simulationStorage1.getParameter();
+ int sensitivityNumber = param.getSensitivityExport().size();
+ //List<SensitivityExport> export = param.getSensitivityExport();
+
+ try {
+ REngine engine = new RProxy();
+
+ //Clear session
+ engine.clearSession();
+
+ //Get Isis R session
+ engine.loadRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ engine.voidEval("factors<-data.frame(x)");
+
+ //Get back the factors number
+ int factorNumber = (Integer) engine.eval("length(factors)");
+
+ //Get back the simulation number
+ param_simulationNumber = (Integer) (engine.eval("length(factors[,1])"));
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ SensitivityExport sensitivityExport =
+ param.getSensitivityExport().get(k);
+
+ String rInstruction = createImportInstruction(sensitivityExport,
+ simulationStorages);
+
+ // Send the simulation results
+ engine.voidEval(rInstruction);
+
+ //Put results in isis.simule
+ engine.voidEval("isis.simule<-data.frame(isis.simule," +
+ sensitivityExport.getExportFilename() + ")");
+ }
+
+ //adding attribute to isis.Simule
+ engine.voidEval("attr(isis.simule," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ engine.voidEval("attr(isis.simule,\"call\")<-isis.MethodExp$call");
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ // Creates the R expression to import results in R
+ String name = param.getSensitivityExport().get(k)
+ .getExportFilename();
+
+ //Create the dataforaov data.frame
+ String dataframe = "dataforaov<-data.frame(factors," + name
+ + "=" + name + ")";
+ engine.voidEval(dataframe);
+
+ //Call aov()
+ String aovCall = "aovresult<-aov(" + name + "~";
+ for (int j = 0; j < factorNumber; j++) {
+
+ if (j < (factorNumber - 1)) {
+ aovCall += engine.eval("names(factors)[" + (j + 1) + "]")
+ + "+";
+ } else {
+ aovCall += engine.eval("names(factors)[" + (j + 1) + "]")
+ + ",data=dataforaov)";
+ }
+ }
+ engine.voidEval(aovCall);
+
+ /*Export the results
+ *Export format is csv, data separated by ','
+ *Results Export name is sensitivityExportName_Results.csv
+ *Sensitivity Indices export name is sensitivityExportName_SensitivityIndices.csv
+ */
+
+ //Compute Sum of Squares and Sensitivity indices
+ engine.voidEval("SoS<-summary(aovresult)[[1]][1:dim(summary(aovresult)[[1]])[1],2]");
+ engine.voidEval("names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:dim(summary(aovresult)[[1]])[1]]");
+ engine.voidEval("IndSensibilite<-SoS/sum(SoS)");
+
+ //Create a data.frame to export sensitivity important results in one file.
+ engine.voidEval("exportsensitivity<-data.frame(" +
+ "SoS[1:dim(summary(aovresult)[[1]])[1]]," +
+ "IndSensibilite[1:dim(summary(aovresult)[[1]])[1]])");
+ engine.voidEval("names(exportsensitivity)<-c(" +
+ "\"Sum Of Squares\"," +
+ "\"Sensitivity indices\")");
+ engine.voidEval("row.names(exportsensitivity)<-dimnames(summary(aovresult)[[1]])[1][[1]][1:dim(summary(aovresult)[[1]])[1]]");
+
+
+ //Set dataforaov names
+ engine.voidEval("resultsnames<-c(factornames,\"Result\")");
+ engine.voidEval("names(dataforaov)<-resultsnames");
+
+ /*Set the export directory
+ *Export directory is the first simulation export directory.
+ */
+ engine.setwd(outputDirectory);
+
+ //Save the results with the scenarios.
+ engine.voidEval("write.csv(dataforaov,\"" +
+ param.getSensitivityExport().get(k).getExportFilename() +
+ "_Results.csv\")");
+
+ //Save the sensitivity indices
+ engine.voidEval("write.csv(exportsensitivity,\"" +
+ param.getSensitivityExport().get(k).getExportFilename() +
+ "_SensitivityIndices.csv\")");
+ //FIXME export through java to enable export when using Rserve (when distant Rserve).
+
+ //creating isis.methodAnalyse
+ engine.voidEval("isis.methodAnalyse<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"isis.simule\"=isis.simule," +
+ "call_method=\"" + aovCall + "\"," +
+ "\"analysis_result\"=list(aovresult,IndSensibilite))");
+
+ engine.voidEval("attr(isis.methodAnalyse," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ String renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-" +
+ "isis.methodAnalyse";
+ engine.voidEval(String.format(renameIsisMethodAnalyse,
+ simulationName + "." + name));
+
+ }
+
+ //Rename R objects for saving purpose
+ renameObjects(engine, simulationName);
+
+ // Save Isis R session
+ engine.saveRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ engine.terminate();
+
+ } catch (Exception e) {
+ throw new SensitivityException("Can't evaluate results", e);
+ }
+
+ }
+
+ @Override
+ public String getDescription() {
+ return "Implementation of Random Latin Hypercube method method using" +
+ " R needs the 'lhs' package to work)";
+ }
+
+}
Deleted: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRSobol.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivity/SensitivityCalculatorRSobol.java 2011-06-14 13:21:14 UTC (rev 3392)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRSobol.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,603 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-
-package sensitivity;
-
-import java.io.File;
-import java.util.List;
-import java.util.Vector;
-
-import javax.swing.Box;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JScrollPane;
-import javax.swing.JTextPane;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.codelutin.j2r.REngine;
-import org.codelutin.j2r.RProxy;
-import org.codelutin.math.matrix.MatrixFactory;
-import org.codelutin.math.matrix.MatrixND;
-import org.codelutin.util.FileUtil;
-import org.rosuda.JRI.REXP;
-
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.simulator.SimulationParameter;
-import fr.ifremer.isisfish.simulator.sensitivity.AbstractSensitivityCalculator;
-import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan;
-import fr.ifremer.isisfish.simulator.sensitivity.Domain;
-import fr.ifremer.isisfish.simulator.sensitivity.Factor;
-import fr.ifremer.isisfish.simulator.sensitivity.Scenario;
-import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.DiscreteDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.EquationContinuousDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.MatrixContinuousDomain;
-import fr.ifremer.isisfish.util.Doc;
-
-/**
- * Implementation of Sobol method using R.
- *
- * @author jcouteau
- * @version $Revision$
- *
- * Last update : $Date$ By :
- * $Author: jcouteau $
- */
-public class SensitivityCalculatorRSobol extends AbstractSensitivityCalculator {
-
- /** to use log facility, just put in your code: log.info("..."); */
- private static Log log = LogFactory
- .getLog(SensitivityCalculatorRFast.class);
-
- @Doc("the size of the 2 random samples")
- public int param_n = 20;
-
- @Doc("the number of bootstrap replicates.")
- public int param_nboot = 20;
-
- @Doc("True to be able to modify the code sent to R")
- public boolean param_modifR = false;
-
- /**
- * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
- * continue.
- *
- * @return <tt>true</tt> s'il sait la gerer
- */
- @Override
- public boolean canManageCardinality() {
- return true;
- }
-
- @Override
- public SensitivityScenarios compute(DesignPlan plan, File outputdirectory) {
-
- setIsisFactorsR(plan, outputdirectory);
-
- double[] dataframe = new double[0];
- int nbExperiments = 0;
- int factorNumber = plan.getFactors().size();
- List<Factor<?, ?>> factors = plan.getFactors();
- SensitivityScenarios thisExperiment = new SensitivityScenarios();
- List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
-
- //Test all factors, if one is discrete, return null
- for (int i = 0; i < factorNumber; i++) {
- if (factors.get(i).getDomain() instanceof DiscreteDomain) {
- JOptionPane
- .showMessageDialog(
- null,
- "Error",
- factors.get(i).getName()
- + " has a discrete domain, this is not acceptable for this method.",
- JOptionPane.ERROR_MESSAGE);
- return null;
- }
- }
-
- String rInstruction = "a<-sobol2002(model=NULL,X1=X1,X2=X2,nboot=%s)";
- String rCall = String.format(rInstruction, param_nboot);
-
- if (param_modifR) {
- JLabel label = new JLabel(
- "Modifier le code R envoyé si vous le souhaitez");
- JTextPane text = new JTextPane();
- text.setText(rCall);
- text.setSize(400, 400);
- text.setPreferredSize(text.getSize());
-
- Box box = Box.createVerticalBox();
- box.add(label);
- box.add(new JScrollPane(text));
-
- JOptionPane.showMessageDialog(null, box, "R modif",
- JOptionPane.QUESTION_MESSAGE);
- rCall = text.getText();
- }
-
- REngine engine = new RProxy();
-
- try {
-
- //Clear session
- log.info("rm(list=ls())");
- engine.voidEval("rm(list=ls())");
-
- //Set working directory to get Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- //Get Isis R session
- log.info("load(\"" + outputdirectory.getName() + ".RData\")");
- engine
- .voidEval("load(\"" + outputdirectory.getName()
- + ".RData\")");
-
- engine.voidEval("library(sensitivity)");
- log.info("Message sent to R : " + "library(sensitivity)");
-
- //Set the working directory (for import and exports)
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- log.info("Message sent to R : " + "setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- engine.voidEval("X1<-data.frame(matrix(runif(" + factorNumber + "*"
- + param_n + "),nrow=" + param_n + "))");
- log
- .info("Message sent to R : "
- + "X1<-data.frame(matrix(runif(" + factorNumber
- + "*" + param_n + "),nrow=" + param_n + "))");
- engine.voidEval("X2<-data.frame(matrix(runif(" + factorNumber + "*"
- + param_n + "),nrow=" + param_n + "))");
- log
- .info("Message sent to R : "
- + "X2<-data.frame(matrix(runif(" + factorNumber
- + "*" + param_n + "),nrow=" + param_n + "))");
-
- engine.voidEval(rCall);
- log.info("Message sent to R : " + rCall);
-
- // Creating the factors vector.
- rInstruction = "factornames<-c(";
- for (int i = 0; i < factorNumber; i++) {
- if (i != (factorNumber - 1)) {
- rInstruction = rInstruction + "\""
- + factors.get(i).getName() + "\",";
- } else {
- rInstruction = rInstruction + "\""
- + factors.get(i).getName() + "\"";
- }
- }
-
- rInstruction += ")";
-
- engine.voidEval(rInstruction);
- log.info("Message sent to R" + rInstruction);
-
- // Export the sobol object for the second run in a .sobol file
- engine.voidEval("dput(a,file=\".sobol\")");
- log.info("Message sent to R" + "dput(a,file=\".sobol\")");
- // Export the X1 object for the second run in a .X1 file
- engine.voidEval("dput(X1,file=\".X1\")");
- log.info("Message sent to R" + "dput(a,file=\".sobol\")");
- // Export the X2 object for the second run in a .X2 file
- engine.voidEval("dput(X2,file=\".X2\")");
- log.info("Message sent to R" + "dput(a,file=\".sobol\")");
-
- // Export the factornames object for the second run in a .factornames file
- engine.voidEval("dput(factornames,file=\".factornames\")");
- log.info("Message sent to R"
- + "dput(factornames,file=\".factornames\")");
-
- // Get back experiment plan
- /*dataframe = (double[]) engine.eval("a$X");*/
-
- Vector<REXP> dataframeVector = (Vector<REXP>) engine.eval("a$X");
- int dataframevectorsize = dataframeVector.size();
- int dataframevectorlength = dataframeVector.get(0).asDoubleArray().length;
- dataframe = new double[dataframevectorsize * dataframevectorlength];
- for (int i = 0; i < dataframeVector.size(); i++) {
- for (int j = 0; j < dataframeVector.get(0).asDoubleArray().length; j++) {
- dataframe[i * dataframeVector.get(0).asDoubleArray().length
- + j] = dataframeVector.get(i).asDoubleArray()[j];
- }
- }
- log.info("Message sent to R : " + "a$X");
-
- nbExperiments = dataframe.length / factorNumber;
-
- String isisFactorDistribution = "isis.factor.distribution<-data.frame(NomFacteur=c(%s),NomDistribution=c(%s),ParametreDistribution=c(%s))";
-
- // Creating the vectors.
- String distribution = "";
- String parameters = "";
- String factorNames = "";
-
- for (int i = 0; i < factorNumber; i++) {
- Domain domain = factors.get(i).getDomain();
- if (i != 0) {
- distribution += ",";
- parameters += ",";
- factorNames += ",";
- }
-
- distribution += "\"qunif\"";
- parameters += "\"[" + ((ContinuousDomain) domain).getMinBound()
- + ";" + ((ContinuousDomain) domain).getMaxBound()
- + "]\"";
- factorNames += "\"" + factors.get(i).getName() + "\"";
- }
-
- log.info("Message sent to R : "
- + String.format(isisFactorDistribution, factorNames,
- distribution, parameters));
- engine.voidEval(String.format(isisFactorDistribution, factorNames,
- distribution, parameters));
-
- log.info("Message sent to R : " + "call<-a$call");
- engine.voidEval("call<-a$call");
-
- log
- .info("Message sent to R : "
- + "isis.MethodExp<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"call\"=call)");
- engine
- .voidEval("isis.MethodExp<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"call\"=call)");
-
- log
- .info("Message sent to R : "
- + "attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : " + "isis.simule<-data.frame(a$X)");
- engine.voidEval("isis.simule<-data.frame(a$X)");
-
- log
- .info("Message sent to R : "
- + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : "
- + "names(isis.simule)<-isis.factors[[1]]");
- engine.voidEval("names(isis.simule)<-isis.factors[[1]]");
-
- //Set working directory to save Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- // Save Isis R session
- log.info("save.image(file=\"" + outputdirectory.getName() + ".RData\")");
- engine.voidEval("save.image(file=\"" + outputdirectory.getName()
- + ".RData\")");
-
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- // Transform the result from R in a matrix
- MatrixND fast = MatrixFactory.getInstance().create(dataframe,
- new int[] { factorNumber, nbExperiments });
-
- // Setting up the scenarios.
- for (int j = 0; j < nbExperiments; j++) {
- Scenario experimentScenario = new Scenario();
- for (int i = 0; i < factorNumber; i++) {
- Factor factor = plan.getFactors().get(i);
- if ((factor.getDomain() instanceof MatrixContinuousDomain)
- || (factor.getDomain() instanceof EquationContinuousDomain)) {
- factor.setValueForIdentifier(fast
- .getValue(new int[] { i, j }));
- } else {
- Double value = (Double) ((ContinuousDomain) factor
- .getDomain()).getMinBound()
- + ((Double) ((ContinuousDomain) factor.getDomain())
- .getMaxBound() - (Double) ((ContinuousDomain) factor
- .getDomain()).getMinBound())
- * fast.getValue(new int[] { i, j });
- factor.setValueForIdentifier(value);
- }
- experimentScenario.addFactor(factor);
- }
- thisExperimentScenarios.add(experimentScenario);
- thisExperiment.setScenarios(thisExperimentScenarios);
- }
- return thisExperiment;
-
- }
-
- @Override
- public void analyzeResult(List<SimulationStorage> simulationStorages,
- File outputdirectory) {
-
- REngine engine = new RProxy();
- try {
-
- //Clear session
- log.info("rm(list=ls())");
- engine.voidEval("rm(list=ls())");
-
- //Set working directory to get Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- //Get Isis R session
- log.info("load(\"" + outputdirectory.getName() + ".RData\")");
- engine
- .voidEval("load(\"" + outputdirectory.getName()
- + ".RData\")");
-
- // Call R
- // Load sensitivity package into R (if package already loaded,
- // nothing happens.
- engine.voidEval("library(sensitivity)");
- log.info("Message sent to R : " + "library(sensitivity)");
-
- //Set the working directory (for import and exports)
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- log.info("Message sent to R : " + "setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- // Get the .X1 file
- engine.voidEval("X1<-dget(\".X1\")");
- log.info("Message sent to R : " + "X1<-dget(\".X1\")");
- // Get the .X2 file
- engine.voidEval("X2<-dget(\".X2\")");
- log.info("Message sent to R : " + "X2<-dget(\".X2\")");
- // Get the factornames object in the .factornames file
- engine.voidEval("factornames<-dget(\".factornames\")");
- log.info("Message sent to R : "
- + "factornames<-dget(\".factornames\")");
-
- //Set X1 names
- engine.voidEval("names(X1)<-factornames");
- log.info("Message sent to R : " + "names(X1)<-factornames");
- //Set X2 names
- engine.voidEval("names(X2)<-factornames");
- log.info("Message sent to R : " + "names(X2)<-factornames");
-
- // Get the .sobol file
- engine.voidEval("a<-dget(\".sobol\")");
- log.info("Message sent to R : " + "a<-dget(\".sobol\")");
-
- //Set a$X names
- engine.voidEval("names(a$X)<-factornames");
- log.info("Message sent to R : " + "names(a$X)<-factornames");
-
- int scenariosNumber = (Integer) engine.eval("length(a$X[,1])");
- log.info("Message sent to R : " + "length(a$X[,1])");
-
- SimulationParameter param = simulationStorages.get(0)
- .getParameter();
- int sensitivityNumber = param.getSensitivityExport().size();
-
- for (int k = 0; k < sensitivityNumber; k++) {
-
- // Creates the R expression to import results in R
- String name = param.getSensitivityExport().get(k)
- .getExportFilename();
- String rInstruction = name + "<-c(";
- for (int l = 0; l < scenariosNumber; l++) {
- File importFile = new File(simulationStorages.get(l)
- .getDirectory().toString()
- + File.separator
- + SimulationStorage.RESULT_EXPORT_DIRECTORY, param
- .getSensitivityExport().get(k).getExportFilename()
- + param.getSensitivityExport().get(k)
- .getExtensionFilename());
- String simulResult = FileUtil.readAsString(importFile);
- double simulationResult = Double.valueOf(simulResult);
- if (l < simulationStorages.size() - 1) {
- rInstruction = rInstruction + simulationResult + ",";
- } else {
- rInstruction = rInstruction + simulationResult;
- }
- }
- rInstruction = rInstruction + ")";
-
- log.info("Message sent to R : " + rInstruction);
-
- // Send the simulation results
- engine.voidEval(rInstruction);
-
- // Send the simulation results
- engine.voidEval(rInstruction);
-
- //Put results in isis.simule
- engine.voidEval("isis.simule<-data.frame(isis.simule," + name
- + ")");
- log.info("Message sent to R : "
- + "isis.simule<-data.frame(isis.simule," + name + ")");
- }
-
- //adding attribute to isis.Simule
- log
- .info("Message sent to R : "
- + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : "
- + "attr(isis.simule,\"call\")<-isis.MethodExp$call");
- engine.voidEval("attr(isis.simule,\"call\")<-isis.MethodExp$call");
-
- for (int k = 0; k < sensitivityNumber; k++) {
-
- // Creates the R expression to import results in R
- String name = param.getSensitivityExport().get(k)
- .getExportFilename();
-
- //Compute results
- engine.voidEval("tell(a,y=" + name + ")");
- log.info("Message sent to R : " + "tell(a,y=" + name + ")");
-
- //creating isis.methodAnalyse
- log
- .info("Message sent to R : "
- + "isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\"tell(a,y="
- + name + ")" + "\",\"analysis_result\"=a)");
- engine
- .voidEval("isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\"tell(a,y="
- + name + ")" + "\",\"analysis_result\"=a)");
-
- //setting isis.methodAnalyse attributes
- log
- .info("attr(isis.methodAnalyse,\"nomModel\")<-\"isis-fish-externe-R\")");
- engine
- .voidEval("attr(isis.methodAnalyse,\"nomModel\")<-\"isis-fish-externe-R\")");
-
- //Create the data.frame of scenarios and results for export purpose
- engine.voidEval("dfresults=data.frame(a$X,results)");
- log.info("Message sent to R : "
- + "dfresults=data.frame(a$X,results)");
-
- //Set working directory
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
- log.info("Message sent to R : setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
-
- //Export V
- engine.voidEval("write.csv(a$V,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename()
- + "_SensitivityIndices.csv\")");
- log.info("Message sent to R : "
- + "write.csv(a$V,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_V.csv\")");
-
- //Export DD
- engine.voidEval("write.csv(a$D,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_D.csv\")");
- log.info("Message sent to R : "
- + "write.csv(a$D,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_D.csv\")");
-
- //Export S
- engine.voidEval("write.csv(a$S,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_S.csv\")");
- log.info("Message sent to R : "
- + "write.csv(a$S,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_S.csv\")");
-
- //Export results
- engine.voidEval("write.csv(dfresults,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Results.csv\")");
- log.info("Message sent to R : "
- + "write.csv(results,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Results.csv\")");
- //FIXME export through java to enable export when using Rserve
-
- String renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-isis.methodAnalyse";
- String simulationName = simulationStorages.get(0).getName()
- .replaceAll("-", "");
- log.info("Message sent to R : "
- + String.format(renameIsisMethodAnalyse, simulationName
- + "." + name));
- engine.voidEval(String.format(renameIsisMethodAnalyse,
- simulationName + "." + name));
-
- }
-
- //Rename R objects for saving purpose
-
- String renameIsisSimule = "%s.isis.simule<-isis.simule";
- String renameIsisFactorDistribution = "%s.isis.factor.distribution<-isis.factor.distribution";
- String renameIsisFactor = "%s.isis.factor<-isis.factors";
- String renameIsisMethodExp = "%s.isis.methodExp<-isis.MethodExp";
-
- String simulationName = simulationStorages.get(0).getName()
- .replaceAll("-", "");
-
- log.info("Message sent to R : "
- + String.format(renameIsisSimule, simulationName));
- engine.voidEval(String.format(renameIsisSimule, simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisFactorDistribution,
- simulationName));
- engine.voidEval(String.format(renameIsisFactorDistribution,
- simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisFactor, simulationName));
- engine.voidEval(String.format(renameIsisFactor, simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisMethodExp, simulationName));
- engine.voidEval(String.format(renameIsisMethodExp, simulationName));
-
- //Set working directory to save Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- // Save Isis R session
- log.info("save.image(file=\"" + outputdirectory.getName() + ".RData\")");
- engine.voidEval("save.image(file=\"" + outputdirectory.getName()
- + ".RData\")");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public String getDescription() {
- return "Implementation of Sobol method using R (use of the R sobol2002 method)";
- }
-
-}
Copied: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRSobol.java (from rev 3393, isis-fish/trunk/src/test/resources/test-database/sensitivity/SensitivityCalculatorRSobol.java)
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRSobol.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRSobol.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -0,0 +1,336 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+
+package sensitivityanalysis;
+
+import java.io.File;
+import java.util.List;
+
+import fr.ifremer.isisfish.export.SensitivityExport;
+import org.nuiton.j2r.REngine;
+import org.nuiton.j2r.RProxy;
+
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.simulator.SimulationParameter;
+import fr.ifremer.isisfish.simulator.sensitivity.AbstractSensitivityAnalysis;
+import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan;
+import fr.ifremer.isisfish.simulator.sensitivity.Domain;
+import fr.ifremer.isisfish.simulator.sensitivity.Factor;
+import fr.ifremer.isisfish.simulator.sensitivity.Scenario;
+import fr.ifremer.isisfish.simulator.sensitivity.SensitivityException;
+import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
+import fr.ifremer.isisfish.util.Doc;
+import org.nuiton.j2r.types.RDataFrame;
+
+/**
+ * Implementation of Sobol method using R.
+ *
+ * @author jcouteau
+ * @version $Revision$
+ *
+ * Last update : $Date$ By :
+ * $Author: jcouteau $
+ */
+public class SensitivityCalculatorRSobol extends AbstractSensitivityAnalysis {
+
+ @Doc("the size of the 2 random samples")
+ public int param_n = 20;
+
+ @Doc("the number of bootstrap replicates.")
+ public int param_nboot = 20;
+
+ @Doc("True to be able to modify the code sent to R")
+ public boolean param_modifR = false;
+
+ /**
+ * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
+ * continue.
+ *
+ * @return <tt>true</tt> s'il sait la gerer
+ */
+ @Override
+ public boolean canManageCardinality() {
+ return true;
+ }
+
+ @Override
+ public SensitivityScenarios compute(DesignPlan plan, File outputdirectory)
+ throws SensitivityException {
+
+ setIsisFactorsR(plan, outputdirectory);
+
+ RDataFrame dataFrame;
+ int nbExperiments;
+ int factorNumber = plan.getFactors().size();
+ List<Factor> factors = plan.getFactors();
+ SensitivityScenarios thisExperiment = new SensitivityScenarios();
+ List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
+
+ testNoDiscrete(factors);
+
+ String rInstruction = "a<-sobol2002(model=NULL,X1=X1,X2=X2,nboot=%s)";
+ String rCall = String.format(rInstruction, param_nboot);
+
+ if (param_modifR) {
+ rCall = editRInstruction(rCall);
+ }
+
+ try {
+ REngine engine = new RProxy();
+
+ //Clear session
+ engine.clearSession();
+
+ //Get Isis R session
+ engine.loadRData(outputdirectory.getParentFile(),
+ outputdirectory.getName());
+
+ engine.voidEval("library(sensitivity)");
+
+ engine.voidEval("X1<-data.frame(matrix(runif(" + factorNumber + "*"
+ + param_n + "),nrow=" + param_n + "))");
+ engine.voidEval("X2<-data.frame(matrix(runif(" + factorNumber + "*"
+ + param_n + "),nrow=" + param_n + "))");
+
+ engine.voidEval(rCall);
+
+ // Creating the factors vector.
+ rInstruction = "factornames<-c(";
+ for (int i = 0; i < factorNumber; i++) {
+ String factorName = factors.get(i).getName();
+ if (i != (factorNumber - 1)) {
+ rInstruction += "\"" + factorName + "\",";
+ } else {
+ rInstruction += "\"" + factorName + "\"";
+ }
+ }
+
+ rInstruction += ")";
+
+ engine.voidEval(rInstruction);
+
+ // Get back experiment plan
+ dataFrame = (RDataFrame) engine.eval("a$X");
+ dataFrame.setVariable("a$X");
+
+ nbExperiments = dataFrame.dim()[0];
+
+ String isisFactorDistribution = "isis.factor.distribution<-" +
+ "data.frame(NomFacteur=c(%s)," +
+ "NomDistribution=c(%s)," +
+ "ParametreDistribution=c(%s))";
+
+ // Creating the vectors.
+ String distribution = "";
+ String parameters = "";
+ String factorNames = "";
+
+ for (int i = 0; i < factorNumber; i++) {
+ Factor factor = factors.get(i);
+ Domain domain = factor.getDomain();
+ if (i != 0) {
+ distribution += ",";
+ parameters += ",";
+ factorNames += ",";
+ }
+
+ distribution += "\"qunif\"";
+ ContinuousDomain continuousDomain = (ContinuousDomain) domain;
+ double min = continuousDomain.getCalculatorMinBound();
+ double max = continuousDomain.getCalculatorMaxBound();
+ parameters += "\"[" + min + ";" + max + "]\"";
+ factorNames += "\"" + factor.getName() + "\"";
+ }
+
+ engine.voidEval(String.format(isisFactorDistribution, factorNames,
+ distribution, parameters));
+
+ engine.voidEval("call<-a$call");
+
+ engine.voidEval("isis.MethodExp<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"call\"=call)");
+
+ engine.voidEval("attr(isis.MethodExp," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ engine.voidEval("isis.simule<-data.frame(a$X)");
+
+ engine.voidEval("attr(isis.simule," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ engine.voidEval("names(isis.simule)<-isis.factors[[1]]");
+
+ // Save Isis R session
+ engine.saveRData(outputdirectory.getParentFile(),
+ outputdirectory.getName());
+
+ // Setting up the scenarios.
+ for (int j = 0; j < nbExperiments; j++) {
+ Scenario experimentScenario = new Scenario();
+ for (int i = 0; i < factorNumber; i++) {
+ Factor factor = plan.getFactors().get(i);
+ Double dFValue = (Double) dataFrame.get(i, j);
+ factor.setValueForIdentifier(dFValue);
+ experimentScenario.addFactor(factor);
+ }
+ thisExperimentScenarios.add(experimentScenario);
+ }
+
+ } catch (Exception e) {
+ throw new SensitivityException("Can't generate scenarios", e);}
+
+
+ thisExperiment.setScenarios(thisExperimentScenarios);
+ return thisExperiment;
+
+ }
+
+ @Override
+ public void analyzeResult(List<SimulationStorage> simulationStorages,
+ File outputDirectory) throws SensitivityException {
+
+ SimulationStorage firstStorage = simulationStorages.get(0);
+ SimulationParameter param = firstStorage.getParameter();
+ int sensitivityNumber = param.getSensitivityExport().size();
+ String simulationName = firstStorage.getName().replaceAll("-", "");
+
+ try {
+
+ REngine engine = new RProxy();
+
+ //Clear session
+ engine.clearSession();
+
+ //Get Isis R session
+ engine.loadRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ // Call R
+ // Load sensitivity package into R (if package already loaded,
+ // nothing happens.
+ engine.voidEval("library(sensitivity)");
+
+ //Set X1 names
+ engine.voidEval("names(X1)<-factornames");
+ //Set X2 names
+ engine.voidEval("names(X2)<-factornames");
+
+ //Set a$X names
+ engine.voidEval("names(a$X)<-factornames");
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ SensitivityExport sensitivityExport =
+ param.getSensitivityExport().get(k);
+
+ String rInstruction = createImportInstruction(sensitivityExport,
+ simulationStorages);
+
+ // Send the simulation results
+ engine.voidEval(rInstruction);
+
+ //Put results in isis.simule
+ engine.voidEval("isis.simule<-data.frame(isis.simule," +
+ sensitivityExport.getExportFilename() + ")");
+ }
+
+ //adding attribute to isis.Simule
+ engine.voidEval("attr(isis.simule," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ engine.voidEval("attr(isis.simule,\"call\")<-isis.MethodExp$call");
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ SensitivityExport sensitivityExport = param.getSensitivityExport().get(k);
+ String name = sensitivityExport.getExportFilename();
+
+ //Compute results
+ engine.voidEval("tell(a,y=" + name + ")");
+
+ engine.voidEval("row.names(a$S)<-names(a$X)");
+ engine.voidEval("row.names(a$T)<-names(a$X)");
+ engine.voidEval("row.names(a$V)<-c(\"global\"," +
+ "names(a$X),paste(\"-\",names(a$X),sep=\"\"))");
+
+ //creating isis.methodAnalyse
+ engine.voidEval("isis.methodAnalyse<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"isis.simule\"=isis.simule," +
+ "call_method=\"tell(a,y=" + name + ")" + "\"," +
+ "\"analysis_result\"=a)");
+
+ //setting isis.methodAnalyse attributes
+ engine.voidEval("attr(isis.methodAnalyse," +
+ "\"nomModel\")<-\"isis-fish-externe-R\")");
+
+ //Create the data.frame of scenarios and results for export purpose
+ engine.voidEval("dfresults<-data.frame(a$X,a$y)");
+
+ //Set working directory
+ engine.setwd(outputDirectory);
+
+ //Export V
+ engine.voidEval("write.csv(a$V,\""
+ + name
+ + "_SensitivityIndices.csv\")");
+ //Export DD
+ engine.voidEval("write.csv(a$D,\""
+ + name + "_D.csv\")");
+
+ //Export S
+ engine.voidEval("write.csv(a$S,\""
+ + name + "_S.csv\")");
+
+ //Export results
+ engine.voidEval("write.csv(dfresults,\""
+ + name + "_Results.csv\")");
+ //FIXME export through java to enable export when using Rserve
+
+ String renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-" +
+ "isis.methodAnalyse";
+ engine.voidEval(String.format(renameIsisMethodAnalyse,
+ simulationName + "." + name));
+
+ }
+
+ //Rename R objects for saving purpose
+ renameObjects(engine, simulationName);
+
+ // Save Isis R session
+ engine.saveRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+ } catch (Exception e) {
+ throw new SensitivityException("Can't evaluate results", e);
+ }
+ }
+
+ @Override
+ public String getDescription() {
+ return "Implementation of Sobol method using R (use of the R " +
+ "sobol2002 method, needs the 'sensitivity' package to work)";
+ }
+}
Deleted: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRegularFractions.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivity/SensitivityCalculatorRegularFractions.java 2011-06-14 13:21:14 UTC (rev 3392)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRegularFractions.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,688 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-package sensitivity;
-
-import java.io.File;
-import java.util.List;
-
-import javax.swing.Box;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JScrollPane;
-import javax.swing.JTextPane;
-
-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 org.codelutin.math.matrix.MatrixFactory;
-import org.codelutin.math.matrix.MatrixND;
-import org.codelutin.util.FileUtil;
-
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.simulator.SimulationParameter;
-import fr.ifremer.isisfish.simulator.sensitivity.AbstractSensitivityCalculator;
-import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan;
-import fr.ifremer.isisfish.simulator.sensitivity.Domain;
-import fr.ifremer.isisfish.simulator.sensitivity.Factor;
-import fr.ifremer.isisfish.simulator.sensitivity.Scenario;
-import fr.ifremer.isisfish.simulator.sensitivity.SensitivityException;
-import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.DiscreteDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.EquationContinuousDomain;
-import fr.ifremer.isisfish.simulator.sensitivity.domain.MatrixContinuousDomain;
-import fr.ifremer.isisfish.util.Doc;
-
-public class SensitivityCalculatorRegularFractions extends
- AbstractSensitivityCalculator {
-
- /** to use log facility, just put in your code: log.info("..."); */
- private static Log log = LogFactory
- .getLog(SensitivityCalculatorRFrF2.class);
-
- @Doc("the path of the directory where the R function is stored (do not indicate the RegularFractions.R file name)")
- public String param_pathToFunction = "";
-
- @Doc("unique prime number of levels of all input and unit factors")
- public int param_p = 2;
-
- @Doc("number of unit factors (so that there are N=p^r units)")
- public int param_r = 2;
-
- @Doc("resolution of the fraction")
- public int param_resolution = 2;
-
- @Doc("True to be able to modify the code sent to R")
- public boolean param_modifR = false;
-
- /**
- * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
- * continue.
- *
- * @return <tt>true</tt> s'il sait la gerer
- */
- @Override
- public boolean canManageCardinality() {
- return true;
- }
-
- @Override
- public SensitivityScenarios compute(DesignPlan plan, File outputdirectory) {
-
- setIsisFactorsR(plan, outputdirectory);
-
- double[] dataframeplan = new double[0];
- int factorNumber = plan.getFactors().size();
- List<Factor<?, ?>> factors = plan.getFactors();
- SensitivityScenarios thisExperiment = new SensitivityScenarios();
- List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
-
- String factorNames = "";
-
- //Test all factors, if one is discrete, return null
- //Create a string with all factors names
- for (int i = 0; i < factorNumber; i++) {
- Domain domain = factors.get(i).getDomain();
- if (i != 0) {
- factorNames += ",";
- }
-
- factorNames += "\"" + factors.get(i).getName() + "\"";
-
- if (domain instanceof DiscreteDomain) {
- JOptionPane
- .showMessageDialog(
- null,
- "Error",
- factors.get(i).getName()
- + " has a discrete domain, this is not acceptable for this method.",
- JOptionPane.ERROR_MESSAGE);
- return null;
- }
- }
-
- REngine engine = new RProxy();
-
- try {
-
- //Clear session
- log.info("rm(list=ls())");
- engine.voidEval("rm(list=ls())");
-
- //Set working directory to get Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- //outputdirectory.getName();
-
- //Get Isis R session
- log.info("load(\"" + outputdirectory.getName() + ".RData\")");
- engine
- .voidEval("load(\"" + outputdirectory.getName()
- + ".RData\")");
-
- //Set the working directory (to import the R function)
- engine.voidEval("setwd(\""
- + param_pathToFunction.replaceAll("\\\\", "/") + "\")");
- log.info("Message sent to R : " + "setwd(\""
- + param_pathToFunction.replaceAll("\\\\", "/") + "\")");
-
- //Import the function
- log.info("source(\"regularfractions.R\")");
- engine.voidEval("source(\"regularfractions.R\")");
-
- //Create the instruction
- String rInstruction = "x<-regular.fraction(%s,%s,%s,%s)";
- String rCall = String.format(rInstruction, factors.size(), param_p,
- param_r, param_resolution);
-
- if (param_modifR) {
- JLabel label = new JLabel(
- "Modifier le code R envoyé si vous le souhaitez");
- JTextPane text = new JTextPane();
- text.setText(rCall);
- text.setSize(400, 400);
- text.setPreferredSize(text.getSize());
-
- Box box = Box.createVerticalBox();
- box.add(label);
- box.add(new JScrollPane(text));
-
- JOptionPane.showMessageDialog(null, box, "R modif",
- JOptionPane.QUESTION_MESSAGE);
- rCall = text.getText();
- }
-
- // Run function
- engine.voidEval(rCall);
- log.info("Message sent to R : " + rCall);
-
- // Run function
- engine.voidEval("call<-\"" + rCall + "\"");
- log.info("Message sent to R : " + "call<-\"" + rCall + "\"");
-
- // Creating the factors vector.
- rInstruction = "factornames<-c(%s)";
- rCall = String.format(rInstruction, factorNames);
-
- engine.voidEval(rCall);
- log.info("Message sent to R : " + rCall);
-
- // Set output directory
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- log.info("Message sent to R : " + "setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- // Export the result object for the second run in a .regularfractions file
- engine.voidEval("dput(x,file=\".regularfractions\")");
- log.info("Message sent to R : "
- + "dput(x,file=\".regularfractions\")");
-
- // Export the factornames object for the second run in a .factornames file
- engine.voidEval("dput(factornames,file=\".factornames\")");
- log.info("Message sent to R : "
- + "dput(factornames,file=\".factornames\")");
-
- // Get back experiment plan
- dataframeplan = (double[]) engine.eval("x[[1]]");
- log.info("Message sent to R : " + "x[[1]]");
-
- //Get back the simulation number
- log.info("length(x[[1]][,1])");
- int simulationNumber = (Integer) engine.eval("length(x[[1]][,1])");
-
- // Transform the result from R in a matrix
- MatrixND morris = MatrixFactory.getInstance().create(dataframeplan,
- new int[] { factors.size(), simulationNumber });
-
- // Setting up the scenarios.
- for (int j = 0; j < simulationNumber; j++) {
- Scenario experimentScenario = new Scenario();
- for (int i = 0; i < factors.size(); i++) {
- Factor factor = plan.getFactors().get(i);
- if ((factor.getDomain() instanceof MatrixContinuousDomain)
- || (factor.getDomain() instanceof EquationContinuousDomain)) {
- factor.setValueForIdentifier(morris.getValue(new int[] {
- i, j }));
- } else {
- Double value = (Double) ((ContinuousDomain) factor
- .getDomain()).getMinBound()
- + ((Double) ((ContinuousDomain) factor
- .getDomain()).getMaxBound() - (Double) ((ContinuousDomain) factor
- .getDomain()).getMinBound())
- * (morris.getValue(new int[] { i, j }) / (param_p - 1));
- factor.setValueForIdentifier(value);
- }
- experimentScenario.addFactor(factor);
- }
- thisExperimentScenarios.add(experimentScenario);
- thisExperiment.setScenarios(thisExperimentScenarios);
- }
-
- String dataframe = "data<-data.frame(";
-
- //Create the factors vectors and the dataframe instruction
- for (int j = 0; j < factorNumber; j++) {
- Factor factor = thisExperimentScenarios.get(0).getFactors()
- .get(j);
- if (factor.getDomain() instanceof EquationContinuousDomain) {
-
- String vector = factor.getName().replaceAll(" ", "")
- + "<-c(";
- for (int i = 0; i < simulationNumber; i++) {
- if (i < (simulationNumber - 1)) {
- vector = vector
- + ((EquationContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue() + ",";
- } else {
- vector = vector
- + ((EquationContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue();
- }
-
- }
- vector = vector + ")";
- engine.voidEval(vector);
- log.info("Message sent to R : " + vector);
- } else if (factor.getDomain() instanceof MatrixContinuousDomain) {
- String vector = factor.getName().replaceAll(" ", "")
- + "<-c(";
- for (int i = 0; i < simulationNumber; i++) {
- if (i < (simulationNumber - 1)) {
- vector = vector
- + ((MatrixContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue() + ",";
- } else {
- vector = vector
- + ((MatrixContinuousDomain) thisExperimentScenarios
- .get(i).getFactors().get(j)
- .getDomain()).getValue();
- }
-
- }
- vector = vector + ")";
- engine.voidEval(vector);
- log.info("Message sent to R : " + vector);
- } else {
- String vector = factor.getName().replaceAll(" ", "")
- + "<-c(";
- for (int i = 0; i < simulationNumber; i++) {
- if (i < (simulationNumber - 1)) {
- vector = vector
- + thisExperimentScenarios.get(i)
- .getFactors().get(j).getValue()
- + ",";
- } else {
- vector = vector
- + thisExperimentScenarios.get(i)
- .getFactors().get(j).getValue();
- }
-
- }
- vector = vector + ")";
- engine.voidEval(vector);
- log.info("Message sent to R : " + vector);
- }
-
- if (j < factorNumber - 1) {
- dataframe = dataframe
- + factor.getName().replaceAll(" ", "") + "=factor("
- + factor.getName().replaceAll(" ", "") + "),";
- } else {
- dataframe += factor.getName().replaceAll(" ", "")
- + "=factor(" + factor.getName().replaceAll(" ", "")
- + "))";
- }
-
- }
- engine.voidEval(dataframe);
- log.info("Message sent to R : " + dataframe);
-
- log.info("Message sent to R : "
- + "isis.factor.distribution<-c(0.0)");
- engine.voidEval("isis.factor.distribution<-c(0.0)");
-
- log
- .info("Message sent to R : "
- + "isis.MethodExp<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"call\"=call)");
- engine
- .voidEval("isis.MethodExp<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"call\"=call)");
-
- log
- .info("Message sent to R : "
- + "attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- //Create isis.Simule
- log.info("Message sent to R : " + "isis.simule<-data.frame(data)");
- engine.voidEval("isis.simule<-data.frame(data)");
-
- log
- .info("Message sent to R : "
- + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- log.info("Message sent to R : "
- + "names(isis.simule)<-isis.factors[[1]]");
- engine.voidEval("names(isis.simule)<-isis.factors[[1]]");
-
- // Export the data.frame object for the second run in a .data file
- engine.voidEval("write.csv(data,file=\".data.csv\")");
- log.info("Message sent to R : write.csv(data,file=\".data.csv\")");
-
- //Set working directory to save Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- // Save Isis R session
- log.info("save.image(file=\"" + outputdirectory.getName() + ".RData\")");
- engine.voidEval("save.image(file=\"" + outputdirectory.getName()
- + ".RData\")");
-
- engine.terminate();
-
- } catch (RException eee) {
- eee.printStackTrace();
- throw new RuntimeException("R evaluation failed", eee);
- }
-
- return thisExperiment;
-
- }
-
- @Override
- public void analyzeResult(List<SimulationStorage> simulationStorages,
- File outputdirectory) throws SensitivityException {
-
- REngine engine = new RProxy();
- try {
-
- //Clear session
- log.info("rm(list=ls())");
- engine.voidEval("rm(list=ls())");
-
- //Set working directory to get Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- //Get Isis R session
- log.info("load(\"" + outputdirectory.getName() + ".RData\")");
- engine
- .voidEval("load(\"" + outputdirectory.getName()
- + ".RData\")");
-
- // Set output directory
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
- log.info("Message sent to R : setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\", "/")
- + "\")");
-
- // Get the regularfractions object from the .regularfractions file
- engine.voidEval("x<-dget(\".regularfractions\")");
- log.info("Message sent to R : " + "x<-dget(\".regularfractions\")");
-
- // Get the factornames object from the .factornames file
- engine.voidEval("factornames<-dget(\".factornames\")");
- log.info("Message sent to R : "
- + "factornames<-dget(\".factornames\")");
-
- //Get back the scenarios
- engine.voidEval("factors<-read.csv(\".data.csv\")");
- log.info("Message sent to R : factors<-read.csv(\".data.csv\")");
-
- //Get back the factors number
- int factorNumber = ((Double) engine.eval("length(factors)-1"))
- .intValue();
-
- SimulationParameter param = simulationStorages.get(0)
- .getParameter();
- int sensitivityNumber = param.getSensitivityExport().size();
-
- for (int k = 0; k < sensitivityNumber; k++) {
-
- // Creates the R expression to import results in R
- String name = param.getSensitivityExport().get(k)
- .getExportFilename();
- String rInstruction = name + "<-c(";
- for (int l = 0; l < simulationStorages.size(); l++) {
- File importFile = new File(simulationStorages.get(l)
- .getDirectory().toString()
- + File.separator
- + SimulationStorage.RESULT_EXPORT_DIRECTORY, param
- .getSensitivityExport().get(k).getExportFilename()
- + param.getSensitivityExport().get(k)
- .getExtensionFilename());
- String simulResult = FileUtil.readAsString(importFile);
- double simulationResult = Double.valueOf(simulResult);
- if (l < simulationStorages.size() - 1) {
- rInstruction = rInstruction + simulationResult + ",";
- } else {
- rInstruction = rInstruction + simulationResult;
- }
- }
- rInstruction = rInstruction + ")";
-
- log.info("Message sent to R : " + rInstruction);
-
- // Send the simulation results
- engine.voidEval(rInstruction);
-
- //Put results in isis.simule
- engine.voidEval("isis.simule<-data.frame(isis.simule," + name
- + ")");
- log.info("Message sent to R : "
- + "isis.simule<-data.frame(isis.simule," + name + ")");
- }
-
- //adding attribute to isis.Simule
- log
- .info("Message sent to R : "
- + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- for (int k = 0; k < sensitivityNumber; k++) {
-
- // Creates the R expression to import results in R
- String name = param.getSensitivityExport().get(k)
- .getExportFilename();
-
- //Create the dataforaov data.frame
- String dataframe = "dataforaov<-data.frame(factors," + name
- + "=" + name + ")";
- engine.voidEval(dataframe);
- log.info("Message sent to R : " + dataframe);
-
- //Call aov()
- String aovCall = "aovresult<-aov(" + name + "~(";
- for (int j = 0; j < factorNumber; j++) {
- log.info("Message sent to R : " + "names(factors)["
- + (j + 2) + "]");
-
- if (j < (factorNumber - 1)) {
- aovCall = aovCall
- + engine
- .eval("names(factors)[" + (j + 2) + "]")
- + "+";
- } else {
- aovCall = aovCall
- + engine
- .eval("names(factors)[" + (j + 2) + "]")
- + ")";
- if (param_resolution <= 4) {
- aovCall += ",data=dataforaov)";
- } else {
- aovCall += "^2,data=dataforaov)";
- }
- }
- }
- engine.voidEval(aovCall);
- log.info("Message sent to R : " + aovCall);
-
- /*Export the results
- *Export format is csv, data separated by ','
- *Results Export name is sensitivityExportName_Results.csv
- *Sensitivity Indices export name is sensitivityExportName_SensitivityIndices.csv
- */
-
- //Compute Sum of Squares and Sensitivity indices
- engine.voidEval("SoS<-summary(aovresult)[[1]][1:"
- + factorNumber + ",2]");
- log.info("Message sent to R : SoS<-summary(aovresult)[[1]][1:"
- + factorNumber + ",2]");
- engine
- .voidEval("names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:"
- + factorNumber + "]");
- log
- .info("Message sent to R : names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:"
- + factorNumber + "]");
- engine.voidEval("IndSensibilite<-SoS/sum(SoS)");
- log.info("Message sent to R : IndSensibilite<-SoS/sum(SoS)");
-
- //Create a data.frame to export sensitivity important results in one file.
- engine.voidEval("exportsensitivity=data.frame(SoS[1:"
- + factorNumber + "],IndSensibilite[1:" + factorNumber
- + "])");
- log
- .info("Message sent to R : exportsensitivity=data.frame(SoS[1:"
- + factorNumber
- + "],IndSensibilite[1:"
- + factorNumber + "])");
- engine
- .voidEval("names(exportsensitivity)<-c(\"Sum Of Squares\",\"Sensitivity indices\")");
- log
- .info("Message sent to R : names(exportsensitivity)<-c(\"Sum Of Squares\",\"Sensitivity indices\")");
- engine.voidEval("row.names(exportsensitivity)<-factornames");
- log.info("Message sent to R : "
- + "row.names(exportsensitivity)<-factornames");
-
- //Set dataforaov names
- engine
- .voidEval("resultsnames<-c(\"Simulation\",factornames,\"Result\")");
- log
- .info("Message sent to R : "
- + "resultsnames<-c(\"Simulation\",factornames,\"Result\")");
- engine.voidEval("names(dataforaov)<-resultsnames");
- log.info("Message sent to R : "
- + "names(dataforaov)<-resultsnames");
-
- /*Set the export directory
- *Export directory is the first simulation export directory.
- */
- engine.voidEval("setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
- log.info("Message sent to R : setwd(\""
- + outputdirectory.getAbsolutePath().replaceAll("\\\\",
- "/") + "\")");
-
- //Save the results with the scenarios.
- engine.voidEval("write.csv(dataforaov,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Results.csv\")");
- log.info("Message sent to R : write.csv(dataforaov,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename() + "_Results.csv\")");
-
- //Save the sensitivity indices
- engine.voidEval("write.csv(exportsensitivity,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename()
- + "_SensitivityIndices.csv\")");
- log.info("Message sent to R : write.csv(exportsensitivity,\""
- + param.getSensitivityExport().get(k)
- .getExportFilename()
- + "_SensitivityIndices.csv\")");
- //FIXME export through java to enable export when using Rserve (when distant Rserve).
-
- //creating isis.methodAnalyse
- log
- .info("Message sent to R : "
- + "isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\""
- + aovCall + "\""
- + ",\"analysis_result\"=list(aovresult,IndSensibilite))");
- engine
- .voidEval("isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\""
- + aovCall
- + "\""
- + ",\"analysis_result\"=list(aovresult,IndSensibilite))");
-
- log
- .info("Message sent to R : "
- + "attr(isis.methodAnalyse,\"nomModel\")<-\"isis-fish-externe-R\"");
- engine
- .voidEval("attr(isis.methodAnalyse,\"nomModel\")<-\"isis-fish-externe-R\"");
-
- String renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-isis.methodAnalyse";
- String simulationName = simulationStorages.get(0).getName()
- .replaceAll("-", "");
- log.info("Message sent to R : "
- + String.format(renameIsisMethodAnalyse, simulationName
- + "." + name));
- engine.voidEval(String.format(renameIsisMethodAnalyse,
- simulationName + "." + name));
-
- }
-
- //Rename R objects for saving purpose
-
- String renameIsisSimule = "%s.isis.simule<-isis.simule";
- String renameIsisFactorDistribution = "%s.isis.factor.distribution<-isis.factor.distribution";
- String renameIsisFactor = "%s.isis.factor<-isis.factors";
- String renameIsisMethodExp = "%s.isis.methodExp<-isis.MethodExp";
-
- String simulationName = simulationStorages.get(0).getName()
- .replaceAll("-", "");
-
- log.info("Message sent to R : "
- + String.format(renameIsisSimule, simulationName));
- engine.voidEval(String.format(renameIsisSimule, simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisFactorDistribution,
- simulationName));
- engine.voidEval(String.format(renameIsisFactorDistribution,
- simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisFactor, simulationName));
- engine.voidEval(String.format(renameIsisFactor, simulationName));
-
- log.info("Message sent to R : "
- + String.format(renameIsisMethodExp, simulationName));
- engine.voidEval(String.format(renameIsisMethodExp, simulationName));
-
- //Set working directory to save Isis R session
- log.info("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
- engine.voidEval("setwd(\""
- + outputdirectory.getParent().replaceAll("\\\\", "/")
- + "\")");
-
- // Save Isis R session
- log.info("save.image(file=\"" + outputdirectory.getName() + ".RData\")");
- engine.voidEval("save.image(file=\"" + outputdirectory.getName()
- + ".RData\")");
-
- engine.terminate();
-
- } catch (Exception eee) {
- eee.printStackTrace();
- throw new RuntimeException("R evaluation failed", eee);
- }
-
- }
-
- @Override
- public String getDescription() {
- return "Implementation of Regular fractions method using R";
- }
-
-}
Copied: isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRegularFractions.java (from rev 3393, isis-fish/trunk/src/test/resources/test-database/sensitivity/SensitivityCalculatorRegularFractions.java)
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRegularFractions.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityanalysis/SensitivityCalculatorRegularFractions.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -0,0 +1,392 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+
+package sensitivityanalysis;
+
+import java.io.File;
+import java.util.List;
+
+import fr.ifremer.isisfish.export.SensitivityExport;
+import org.nuiton.j2r.REngine;
+import org.nuiton.j2r.RException;
+import org.nuiton.j2r.RProxy;
+import org.nuiton.j2r.types.RDataFrame;
+
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.simulator.SimulationParameter;
+import fr.ifremer.isisfish.simulator.sensitivity.AbstractSensitivityAnalysis;
+import fr.ifremer.isisfish.simulator.sensitivity.DesignPlan;
+import fr.ifremer.isisfish.simulator.sensitivity.Domain;
+import fr.ifremer.isisfish.simulator.sensitivity.Factor;
+import fr.ifremer.isisfish.simulator.sensitivity.Scenario;
+import fr.ifremer.isisfish.simulator.sensitivity.SensitivityException;
+import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.DiscreteDomain;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.EquationContinuousDomain;
+import fr.ifremer.isisfish.simulator.sensitivity.domain.MatrixContinuousDomain;
+import fr.ifremer.isisfish.util.Doc;
+
+public class SensitivityCalculatorRegularFractions extends
+ AbstractSensitivityAnalysis {
+
+ @Doc("the path of the directory where the R function is stored (do not indicate the RegularFractions.R file name)")
+ public String param_pathToFunction = "";
+
+ @Doc("unique prime number of levels of all input and unit factors")
+ public int param_p = 2;
+
+ @Doc("number of unit factors (so that there are N=p^r units)")
+ public int param_r = 2;
+
+ @Doc("resolution of the fraction")
+ public int param_resolution = 2;
+
+ @Doc("True to be able to modify the code sent to R")
+ public boolean param_modifR = false;
+
+ /**
+ * Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
+ * continue.
+ *
+ * @return <tt>true</tt> s'il sait la gerer
+ */
+ @Override
+ public boolean canManageCardinality() {
+ return true;
+ }
+
+ @Override
+ public SensitivityScenarios compute(DesignPlan plan, File outputDirectory)
+ throws SensitivityException {
+
+ setIsisFactorsR(plan, outputDirectory);
+
+ RDataFrame dataFrame;
+ int factorNumber = plan.getFactors().size();
+ List<Factor> factors = plan.getFactors();
+ SensitivityScenarios thisExperiment = new SensitivityScenarios();
+ List<Scenario> thisExperimentScenarios = thisExperiment.getScenarios();
+
+ String factorNames = "";
+
+ //Test all factors, if one is discrete, return null
+ //Create a string with all factors names
+ for (int i = 0; i < factorNumber; i++) {
+ Domain domain = factors.get(i).getDomain();
+ if (i != 0) {
+ factorNames += ",";
+ }
+
+ factorNames += "\"" + factors.get(i).getName() + "\"";
+
+ if (domain instanceof DiscreteDomain) {
+ throw new SensitivityException(factors.get(i).getName() +
+ " has a discrete domain, this is not acceptable for " +
+ "this method.");
+ }
+ }
+
+ try {
+
+ REngine engine = new RProxy();
+
+ //Clear session
+ engine.clearSession();
+
+ //Get Isis R session
+ engine.loadRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ //Set the working directory (to import the R function)
+ engine.setwd(new File(param_pathToFunction));
+
+ //Import the function
+ engine.voidEval("source(\"regularfractions.R\")");
+
+ //Create the instruction
+ String rInstruction = "x<-regular.fraction(%s,%s,%s,%s)";
+ String rCall = String.format(rInstruction, factors.size(), param_p,
+ param_r, param_resolution);
+
+ if (param_modifR) {
+ rCall = editRInstruction(rCall);
+ }
+
+ // Run function
+ engine.voidEval(rCall);
+
+ // Run function
+ engine.voidEval("call<-\"" + rCall + "\"");
+
+ // Creating the factors vector.
+ rInstruction = "factornames<-c(%s)";
+ rCall = String.format(rInstruction, factorNames);
+
+ engine.voidEval(rCall);
+
+
+ // Get back experiment plan
+ engine.eval("expPlan<-as.data.frame(x[[1]])");
+ dataFrame = (RDataFrame)engine.eval("expPlan");
+ dataFrame.setVariable("expPlan");
+
+ //Get back the simulation number
+ int simulationNumber = (Integer) engine.eval("length(x[[1]][,1])");
+
+ // Setting up the scenarios.
+ for (int j = 0; j < simulationNumber; j++) {
+ Scenario experimentScenario = new Scenario();
+ for (int i = 0; i < factors.size(); i++) {
+ Factor factor = plan.getFactors().get(i);
+ Domain domain = factor.getDomain();
+ Double dFValue = (Double)dataFrame.get(i,j);
+ if ((domain instanceof MatrixContinuousDomain)
+ || (domain instanceof EquationContinuousDomain)) {
+ factor.setValueForIdentifier(dFValue);
+ } else {
+ ContinuousDomain contDomain = (ContinuousDomain)domain;
+ Double max = contDomain.getCalculatorMaxBound();
+ Double min = contDomain.getCalculatorMinBound();
+ Double value = min + (max - min) * dFValue / (param_p - 1);
+ factor.setValueForIdentifier(value);
+ }
+ experimentScenario.addFactor(factor);
+ }
+ thisExperimentScenarios.add(experimentScenario);
+ thisExperiment.setScenarios(thisExperimentScenarios);
+ }
+
+ String dataframe = "data<-data.frame(";
+
+ //Create the factors vectors and the dataframe instruction
+ for (int j = 0; j < factorNumber; j++) {
+ Factor factor = factors.get(j);
+ String factorName = factor.getName().replaceAll(" ", "");
+
+ String vector = factorName + "<-c(";
+ for (int i = 0; i < simulationNumber; i++) {
+ Scenario scenario = thisExperimentScenarios.get(i);
+ List<Factor> newFactors = scenario.getFactors();
+ Factor factor1 = newFactors.get(j);
+
+ if (i < (simulationNumber - 1)) {
+ vector += factor1.getDisplayedValue() + ",";
+ } else {
+ vector += factor1.getDisplayedValue();
+ }
+
+ }
+ vector = vector + ")";
+ engine.voidEval(vector);
+
+ if (j < factorNumber - 1) {
+ dataframe += factorName + "=factor(" + factorName + "),";
+ } else {
+ dataframe += factorName + "=factor(" + factorName + "))";
+ }
+
+ }
+ engine.voidEval(dataframe);
+
+ engine.voidEval("isis.factor.distribution<-c(0.0)");
+
+ engine.voidEval("isis.MethodExp<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"call\"=call)");
+
+ engine.voidEval("attr(isis.MethodExp," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ //Create isis.Simule
+ engine.voidEval("isis.simule<-data.frame(data)");
+
+ engine.voidEval("attr(isis.simule," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ engine.voidEval("names(isis.simule)<-isis.factors[[1]]");
+
+ // Save Isis R session
+ engine.saveRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ engine.terminate();
+
+ } catch (RException eee) {
+ throw new SensitivityException("Can't generate scenarios", eee);
+ }
+
+ return thisExperiment;
+
+ }
+
+ @Override
+ public void analyzeResult(List<SimulationStorage> simulationStorages,
+ File outputDirectory) throws SensitivityException {
+
+ SimulationStorage firstStorage = simulationStorages.get(0);
+ SimulationParameter param = firstStorage.getParameter();
+ List<SensitivityExport> exports = param.getSensitivityExport();
+ int sensitivityNumber = exports.size();
+ String simulationName = firstStorage.getName().replaceAll("-", "");
+
+ try {
+
+ REngine engine = new RProxy();
+
+ //Clear session
+ engine.clearSession();
+
+ //Get Isis R session
+ engine.loadRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ //Get back the factors number
+ int factorNumber = (Integer) engine.eval("dim(data)[2]");
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ SensitivityExport sensitivityExport =
+ param.getSensitivityExport().get(k);
+
+ String rInstruction = createImportInstruction(sensitivityExport,
+ simulationStorages);
+
+ // Send the simulation results
+ engine.voidEval(rInstruction);
+
+ //Put results in isis.simule
+ engine.voidEval("isis.simule<-data.frame(isis.simule," +
+ sensitivityExport.getExportFilename() + ")");
+ }
+
+ //adding attribute to isis.Simule
+ engine.voidEval("attr(isis.simule," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ for (SensitivityExport export : exports) {
+
+ String name = export.getExportFilename();
+
+ //Create the dataforaov data.frame
+ String dataFrame = "dataforaov<-data.frame(data," +
+ name + "=" + name + ")";
+ engine.voidEval(dataFrame);
+
+ //Call aov()
+ String aovCall = "aovresult<-aov(" + name + "~(";
+ for (int j = 0; j < factorNumber; j++) {
+
+ if (j < (factorNumber - 1)) {
+ aovCall = aovCall
+ + engine.eval("names(data)[" + (j + 1) + "]")
+ + "+";
+ } else {
+ aovCall = aovCall
+ + engine.eval("names(data)[" + (j + 1) + "]")
+ + ")";
+ if (param_resolution <= 4) {
+ aovCall += ",data=dataforaov)";
+ } else {
+ aovCall += "^2,data=dataforaov)";
+ }
+ }
+ }
+ engine.voidEval(aovCall);
+
+ /*Export the results
+ *Export format is csv, data separated by ','
+ *Results Export name is sensitivityExportName_Results.csv
+ *Sensitivity Indices export name is sensitivityExportName_SensitivityIndices.csv
+ */
+
+ //Compute Sum of Squares and Sensitivity indices
+ engine.voidEval("SoS<-summary(aovresult)[[1]][1:dim(summary(aovresult)[[1]])[1],2]");
+ engine.voidEval("names(SoS)<-dimnames(summary(aovresult)[[1]])[[1]][1:dim(summary(aovresult)[[1]])[1]]");
+ engine.voidEval("IndSensibilite<-SoS/sum(SoS)");
+
+ //Create a data.frame to export sensitivity important results in one file.
+ engine.voidEval("exportsensitivity<-data.frame(" +
+ "SoS[1:dim(summary(aovresult)[[1]])[1]]," +
+ "IndSensibilite[1:dim(summary(aovresult)[[1]])[1]])");
+ engine.voidEval("names(exportsensitivity)<-c(" +
+ "\"Sum Of Squares\"," +
+ "\"Sensitivity indices\")");
+ engine.voidEval("row.names(exportsensitivity)<-dimnames(summary(aovresult)[[1]])[1][[1]][1:dim(summary(aovresult)[[1]])[1]]");
+
+ //Set dataforaov names
+ engine.voidEval("resultsnames<-c(factornames,\"Result\")");
+ engine.voidEval("names(dataforaov)<-resultsnames");
+
+ /*Set the export directory
+ *Export directory is the first simulation export directory.
+ */
+ engine.setwd(outputDirectory);
+
+ //Save the results with the scenarios.
+ engine.voidEval("write.csv(dataforaov,\"" + name +
+ "_Results.csv\")");
+
+ //Save the sensitivity indices
+ engine.voidEval("write.csv(exportsensitivity,\"" + name +
+ "_SensitivityIndices.csv\")");
+ //FIXME export through java to enable export when using Rserve (when distant Rserve).
+
+ //creating isis.methodAnalyse
+ engine.voidEval("isis.methodAnalyse<-list(" +
+ "\"isis.factors\"=isis.factors," +
+ "\"isis.factor.distribution\"=isis.factor.distribution," +
+ "\"isis.simule\"=isis.simule," +
+ "\"call_method\"=\"" + aovCall + "\"," +
+ "\"analysis_result\"=list(aovresult,IndSensibilite))");
+
+ engine.voidEval("attr(isis.methodAnalyse," +
+ "\"nomModel\")<-\"isis-fish-externe-R\"");
+
+ String renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-isis.methodAnalyse";
+ engine.voidEval(String.format(renameIsisMethodAnalyse,
+ simulationName + "." + name));
+
+ }
+
+ //Rename R objects for saving purpose
+ renameObjects(engine,simulationName);
+
+ // Save Isis R session
+ engine.saveRData(outputDirectory.getParentFile(),
+ outputDirectory.getName());
+
+ engine.terminate();
+
+ } catch (Exception eee) {
+ throw new SensitivityException("Can't evaluate results", eee);
+ }
+
+ }
+
+ @Override
+ public String getDescription() {
+ return "Implementation of Regular fractions method using R";
+ }
+
+}
Modified: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityBiomassReferenceY9.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityBiomassReferenceY9.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityBiomassReferenceY9.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -26,19 +23,20 @@
import static org.nuiton.i18n.I18n._;
+import java.io.File;
import java.io.Writer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.math.matrix.MatrixND;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.util.ReverseFileReader;
import scripts.ResultName;
import fr.ifremer.isisfish.datastore.ResultStorage;
import fr.ifremer.isisfish.datastore.SimulationStorage;
import fr.ifremer.isisfish.entities.Population;
import fr.ifremer.isisfish.export.SensitivityExport;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.util.Doc;
public class SensitivityBiomassReferenceY9 implements SensitivityExport {
@@ -52,53 +50,65 @@
@Doc("Population")
public Population param_pop;
- @Doc("Name of the reference simulation")
- public String param_referenceSimulation = "";
+ @Doc("URL of the Biomasses.csv reference export file")
+ public String param_referenceBiomassCSV ="";
@Override
public void export(SimulationStorage simulation, Writer out)
throws Exception {
- SimulationStorage referenceSimulation = SimulationStorage
- .getSimulation(param_referenceSimulation);
- ResultStorage referenceResultStorage = referenceSimulation
- .getResultStorage();
ResultStorage resultStorage = simulation.getResultStorage();
- Date lastDate = resultStorage.getLastDate();
+ TimeStep lastStep = resultStorage.getLastStep();
Double biomass = 0.0;
Double referenceBiomass = 0.0;
- System.out.println("reference simul : " + param_referenceSimulation);
+ File referenceFile = new File(param_referenceBiomassCSV);
+ //instantiate a reader that starts reading from the file end.
+ ReverseFileReader reader = new ReverseFileReader(referenceFile);
+
+ //read the last line of the file (should be empty)
+ String line = reader.readLine();
+
+ //read the next line (the last written line)
+ line = reader.readLine();
+
+
+ String lastMonth="";
+
+ while (line!=null ){
+
+ String[] items = line.split(";");
+
+ //If we did not initiate the last date (we are on the last line of
+ // the file), we do it now with the value of the date.
+ if ("".equals(lastMonth)) {
+ lastMonth = items[3];
+ }
+
+ if ((items[0].equals(param_pop.getName())) && (items[3].equals(lastMonth))){
+ referenceBiomass += Double.parseDouble(items[4]);
+ }
+ line = reader.readLine();
+ }
+
+
+ //Calculate the biomass for the simulation
for (Population pop : simulation.getParameter().getPopulations()) {
if (pop.getName().equals(param_pop.getName())) {
//Get the biomass of the last time step
- MatrixND matlastdate = resultStorage.getMatrix(lastDate, pop,
+ MatrixND matrixLastDate = resultStorage.getMatrix(lastStep, pop,
ResultName.MATRIX_BIOMASS);
- biomass = matlastdate.sumAll();
- System.out.println("matlastdate:" + (Object) matlastdate);
-
- TopiaContext tx = referenceSimulation.getStorage()
- .beginTransaction();
-
- MatrixND matreferencelastdate = referenceResultStorage
- .getMatrix(lastDate, ResultName.MATRIX_BIOMASS + " "
- + pop, tx);
- referenceBiomass = matreferencelastdate.sumAll();
-
- tx.commitTransaction();
- tx.closeContext();
+ //sum all
+ biomass = matrixLastDate.sumAll();
}
}
- System.out.println("simulationStorage:" + simulation);
- System.out.println("referenece simulation:" + referenceSimulation);
- System.out.println("resultStorage:" + resultStorage);
- System.out.println("referenceStroagr:" + referenceResultStorage);
- System.out.println("biomass:" + biomass);
- System.out.println("referenceBiomass:" + referenceBiomass);
- out.write(Double.toString(biomass / referenceBiomass));
+ log.info("Biomass : " + biomass);
+ log.info("Reference biomass : " + referenceBiomass);
+ out.write(Double.toString(biomass/referenceBiomass));
+
}
@Override
Modified: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityBiomassRelativeReferenceY12.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityBiomassRelativeReferenceY12.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityBiomassRelativeReferenceY12.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -26,19 +23,20 @@
import static org.nuiton.i18n.I18n._;
+import java.io.File;
import java.io.Writer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.math.matrix.MatrixND;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.util.ReverseFileReader;
import scripts.ResultName;
import fr.ifremer.isisfish.datastore.ResultStorage;
import fr.ifremer.isisfish.datastore.SimulationStorage;
import fr.ifremer.isisfish.entities.Population;
import fr.ifremer.isisfish.export.SensitivityExport;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.util.Doc;
public class SensitivityBiomassRelativeReferenceY12 implements
@@ -53,61 +51,71 @@
@Doc("Population")
public Population param_pop;
- @Doc("Name of the reference simulation")
- public String param_referenceSimulation = "";
+ @Doc("URL of the Biomasses.csv reference export file")
+ public String param_referenceBiomassCSV ="";
@Override
public void export(SimulationStorage simulation, Writer out)
throws Exception {
- SimulationStorage referenceSimulation = SimulationStorage
- .getSimulation(param_referenceSimulation);
ResultStorage resultStorage = simulation.getResultStorage();
- ResultStorage referenceResultStorage = referenceSimulation
- .getResultStorage();
- Date lastDate = resultStorage.getLastDate();
- Date firstDate = new Date(11);
+ TimeStep lastStep = resultStorage.getLastStep();
+ TimeStep firstStep = new TimeStep(11);
double biomass = 0.0;
- double firstbiomass = 0.0;
+ double firstBiomass = 0.0;
double biomassReference = 0.0;
- double firstbiomassReference = 0.0;
+ double firstBiomassReference = 0.0;
+ File referenceFile = new File(param_referenceBiomassCSV);
+
+ //instantiate a reader that starts reading from the file end.
+ ReverseFileReader reader = new ReverseFileReader(referenceFile);
+
+ //read the last line of the file (should be empty)
+ String line = reader.readLine();
+
+ //read the next line (the last written line)
+ line = reader.readLine();
+
+
+ String lastMonth="";
+
+ while (line!=null ){
+
+ String[] items = line.split(";");
+
+ //If we did not initiate the last date (we are on the last line of
+ // the file), we do it now with the value of the date.
+ if ("".equals(lastMonth)) {
+ lastMonth = items[3];
+ }
+
+ if ((items[0].equals(param_pop.getName())) && (items[3].equals(lastMonth))){
+ biomassReference += Double.parseDouble(items[4]);
+ }
+
+ if ((items[0].equals(param_pop.getName())) && (items[3].equals("11"))){
+ firstBiomassReference += Double.parseDouble(items[4]);
+ }
+ line = reader.readLine();
+ }
+
for (Population pop : simulation.getParameter().getPopulations()) {
if (pop.getName().equals(param_pop.getName())) {
//Get the biomass on december of the first year
- MatrixND matfirstdate = resultStorage.getMatrix(firstDate, pop,
+ MatrixND matfirstdate = resultStorage.getMatrix(firstStep, pop,
ResultName.MATRIX_BIOMASS);
- firstbiomass = matfirstdate.sumAll();
+ firstBiomass = matfirstdate.sumAll();
//Get the biomass of the last time step
- MatrixND matlastdate = resultStorage.getMatrix(lastDate, pop,
+ MatrixND matlastdate = resultStorage.getMatrix(lastStep, pop,
ResultName.MATRIX_BIOMASS);
biomass = matlastdate.sumAll();
-
- //Get the biomass on december of the first year
- TopiaContext tx = referenceSimulation.getStorage()
- .beginTransaction();
- MatrixND matfirstdatereference = referenceResultStorage
- .getMatrix(firstDate, ResultName.MATRIX_BIOMASS + " "
- + pop, tx);
- firstbiomassReference = matfirstdatereference.sumAll();
- tx.commitTransaction();
- tx.closeContext();
-
- //Get the biomass of the last time step
- tx = referenceSimulation.getStorage().beginTransaction();
- MatrixND matlastdatereference = referenceResultStorage
- .getMatrix(lastDate, ResultName.MATRIX_BIOMASS + " "
- + pop, tx);
- biomassReference = matlastdatereference.sumAll();
- tx.commitTransaction();
- tx.closeContext();
-
}
}
- out.write(Double.toString((biomass / firstbiomass)
- / (biomassReference / firstbiomassReference)));
+ out.write(Double.toString((biomass / firstBiomass)
+ / (biomassReference / firstBiomassReference)));
}
@@ -131,4 +139,4 @@
return this.necessaryResult;
}
-}
\ No newline at end of file
+}
Modified: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityBiomassRelativeY6.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityBiomassRelativeY6.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityBiomassRelativeY6.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -37,7 +34,7 @@
import fr.ifremer.isisfish.datastore.SimulationStorage;
import fr.ifremer.isisfish.entities.Population;
import fr.ifremer.isisfish.export.SensitivityExport;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.util.Doc;
public class SensitivityBiomassRelativeY6 implements SensitivityExport {
@@ -55,8 +52,8 @@
public void export(SimulationStorage simulation, Writer out)
throws Exception {
ResultStorage resultStorage = simulation.getResultStorage();
- Date lastDate = resultStorage.getLastDate();
- Date firstDate = new Date(11);
+ TimeStep lastStep = resultStorage.getLastStep();
+ TimeStep firstStep = new TimeStep(11);
double biomass = 0.0;
double firstbiomass = 0.0;
@@ -64,12 +61,12 @@
if (pop.getName().equals(param_pop.getName())) {
//Get the biomass on december of the first year
- MatrixND matfirstdate = resultStorage.getMatrix(firstDate, pop,
+ MatrixND matfirstdate = resultStorage.getMatrix(firstStep, pop,
ResultName.MATRIX_BIOMASS);
firstbiomass = matfirstdate.sumAll();
//Get the biomass of the last time step
- MatrixND matlastdate = resultStorage.getMatrix(lastDate, pop,
+ MatrixND matlastdate = resultStorage.getMatrix(lastStep, pop,
ResultName.MATRIX_BIOMASS);
biomass = matlastdate.sumAll();
@@ -98,4 +95,4 @@
return this.necessaryResult;
}
-}
\ No newline at end of file
+}
Modified: isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityBiomassY3.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityBiomassY3.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/sensitivityexports/SensitivityBiomassY3.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2009 - 2011 Ifremer, Code Lutin, Jean Couteau
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -37,7 +34,7 @@
import fr.ifremer.isisfish.datastore.SimulationStorage;
import fr.ifremer.isisfish.entities.Population;
import fr.ifremer.isisfish.export.SensitivityExport;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.util.Doc;
public class SensitivityBiomassY3 implements SensitivityExport {
@@ -54,13 +51,13 @@
public void export(SimulationStorage simulation, Writer out)
throws Exception {
ResultStorage resultStorage = simulation.getResultStorage();
- Date lastDate = resultStorage.getLastDate();
+ TimeStep lastStep = resultStorage.getLastStep();
double biomass = 0.0;
for (Population pop : simulation.getParameter().getPopulations()) {
if (pop.getName().equals(param_pop.getName())) {
//Get the biomass of the last time step
- MatrixND matlastdate = resultStorage.getMatrix(lastDate, pop,
+ MatrixND matlastdate = resultStorage.getMatrix(lastStep, pop,
ResultName.MATRIX_BIOMASS);
biomass = matlastdate.sumAll();
}
Deleted: isis-fish/trunk/src/test/resources/test-database/simulationplans/CalibrationSimplexePasVariable2Capturabilite.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/analyseplans/CalibrationSimplexePasVariable2Capturabilite.java 2011-06-14 13:21:14 UTC (rev 3392)
+++ isis-fish/trunk/src/test/resources/test-database/simulationplans/CalibrationSimplexePasVariable2Capturabilite.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,505 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-package analyseplans;
-
-import static org.codelutin.i18n.I18n._;
-
-import java.io.File;
-import java.io.FileReader;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-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.util.FileUtil;
-import org.codelutin.util.StringUtil;
-
-import scripts.ResultName;
-import fr.ifremer.isisfish.datastore.ResultStorage;
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.entities.Population;
-import fr.ifremer.isisfish.entities.PopulationGroup;
-import fr.ifremer.isisfish.entities.PopulationSeasonInfo;
-import fr.ifremer.isisfish.simulator.AnalysePlan;
-import fr.ifremer.isisfish.simulator.AnalysePlanContext;
-import fr.ifremer.isisfish.util.Doc;
-
-/**
- * CalibrationSimplexePasVariable2Capturabilite.
- *
- * Created: 17 septembre 2007
- *
- * @author <>
- * @version $Revision$
- *
- * Last update: $Date$
- * by : $Author: bpoussin $
- */
-/////***You can modify class name if you want
-/////***BUT attention : file name and class name must be the same (without the extention ".java"), ie here : "CalibrationSimplexePasVariable2Capturabilite"
-public class CalibrationSimplexePasVariable2Capturabilite implements
- AnalysePlan {
-
- /** to use log facility, just put in your code: log.info("..."); */
- static private Log log = LogFactory
- .getLog(CalibrationSimplexePasVariable2Capturabilite.class);
-
- enum State {
- STATE_INIT, STATE_0, STATE_1, STATE_2, STATE_3, STATE_4
- };
-
- /////***here must appear the path to export the historic file ("Historic.csv")
- //where q1, q2 and criteria computed at each simulation are written
- /////***Attention : before beginning a new calibration rename your eventual
- //old file Historic.csv otherwise it will be lost
- protected File exportHistoric = new File("Historic.csv");
- protected String exportHisto = "";
-
- @Doc("Population which parameters are calibrated")
- public Population param_Population = null;
- @Doc("First initial point of the simplex: de la forme(\"xx;yy\")")
- public String param_M1 = "2.42e-5;2.11e-6";// devient un parametre du plan d analyse
- @Doc("Second initial point of the simplex")
- public String param_M2 = "2.34e-5;2.59e-6";// devient un parametre du plan d analyse
- @Doc("Third initial point of the simplex")
- public String param_M3 = "2.59e-5;2.41e-6";// devient un parametre du plan d analyse
-
- ///// ***put here the path and name of the file containing the data on which you calibrate your fichery ( here observed catches)
- @Doc(value = "file name and path of observed landings")
- public String param_nomfichier_debarquements = "Observedlandings2001-2003.csv";//in row : time ; in columns : age or length group
- protected File debarquementsObserves;
- protected MatrixND matrixDebarquement;
-
- protected State state = State.STATE_INIT;
- public Experiences experiences = new Experiences();
- public String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP };
-
- 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 _("Calibration using variable step Simplex method (Walters): user gives a file of observations (here catches) by time step and group (.csv), output will try to approach oservations by changing the values of catchability");
- }
-
- /**
- * Appele au demarrage de la simulation, cette methode permet d'initialiser
- * des valeurs
- * @param context 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());
-
- /////*** specify dimention of the matrix containning observations (observed landings for instance)
- /////*** numbers of group/columns : could be equal to your number of classes in ISIS but may also be different if your had only aggregated data
- int nbGroup = 4;
- /////*** enter number of observation per year (if you have observation by quarter put 4) / lines of the observations file
- int nbTrim = nbYear * 4;
- int[] dimMatrix = { nbTrim, nbGroup };
- matrixDebarquement = MatrixFactory.getInstance().create(dimMatrix);
- //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, 0 });
- log.info("MatrixDebarquement : " + matrixDebarquement);
- //db.closeContext();
- }
-
- double g1;
- double g2;
- double worst1;
- double worst2;
-
- /**
- * 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;
- boolean doBoucle = true;
- log.info("before simulation");
-
- int number = context.getNumber();
-
- if (number < 3) {
- log.info("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 = 1000;
- double q2 = 1000;
- double lastCritere = experiences.getExperience(number - 1).criteria;
- while (doBoucle) {
- doBoucle = false;
- if (state == State.STATE_INIT) {
- doBoucle = false;
- log.info("state init");
-
- //ordonne les 3 premieres experiences selon leur critere
- Collections.sort(experiences.current);
- //log.info("SIMPLEXE : current 0 = " + experiences.current.get(0).criteria + "current 1 = " + experiences.current.get(1).criteria + "current 2 = " + experiences.current.get(2).criteria );
- log.info("SIMPLEXE : current 0 = "
- + experiences.current.get(0).criteria
- + "current 1 = "
- + experiences.current.get(1).criteria
- + "current 2 = "
- + experiences.current.get(2).criteria);
- log.info("SIMPLEXE : Best q1 = "
- + experiences.current.get(0).q1 + " q2 = "
- + experiences.current.get(0).q2);
- log.info("SIMPLEXE : NextBest q1 = "
- + experiences.current.get(1).q1 + " q2 = "
- + experiences.current.get(1).q2);
- log.info("SIMPLEXE : Worst q1 = "
- + experiences.current.get(2).q1 + " q2 = "
- + experiences.current.get(2).q2);
-
- //Calcul et evaluation de R
- double g1 = (experiences.current.get(0).q1 + experiences.current
- .get(1).q1) / 2.0;
- double g2 = (experiences.current.get(0).q2 + experiences.current
- .get(1).q2) / 2.0;
- double worst1 = experiences.current.get(2).q1;
- double worst2 = experiences.current.get(2).q2;
-
- state = State.STATE_0;
-
- q1 = 2 * g1 - worst1;
- q2 = 2 * g2 - worst2;
-
- log.info("R : q1 = " + q1 + " q2 = " + q2);
-
- } else if (state == State.STATE_0) {
- doBoucle = false;
- log.info("state 0");
-
- // on fait la 5eme avec des q qui dependent de la 4eme dans le dernier cas
- //log.info("g1 = " + g1 + " " + "g2 = " + g2);
- //log.info("worst1 = " + worst1 + " " + "worst2 = " + worst2);
-
- if (lastCritere > experiences.current.get(2).criteria) {
- log.info("State 0 : R : lastCtritere > current2 : R pire de W");
- state = State.STATE_1;
- //calcul de Cw
- q1 = ((experiences.current.get(0).q1 + experiences.current
- .get(1).q1) / 2.0)
- - (((experiences.current.get(0).q1 + experiences.current
- .get(1).q1) / 2.0) - experiences.current
- .get(2).q1) / 2.0;
- q2 = ((experiences.current.get(0).q2 + experiences.current
- .get(1).q2) / 2.0)
- - (((experiences.current.get(0).q2 + experiences.current
- .get(1).q2) / 2.0) - experiences.current
- .get(2).q2) / 2.0;
- log.info("Cw : q1 = " + q1 + " q2 = " + q2);
-
- } else if (lastCritere > experiences.current.get(1).criteria) {
- log.info("State 0 :R : lastCritere > current 1 : R meilleur que W et moins bon que N");
- state = State.STATE_2;
- // calcul de Cr
- q1 = ((experiences.current.get(0).q1 + experiences.current
- .get(1).q1) / 2.0)
- + (((experiences.current.get(0).q1 + experiences.current
- .get(1).q1) / 2.0) - experiences.current
- .get(2).q1) / 2.0;
- q2 = ((experiences.current.get(0).q2 + experiences.current
- .get(1).q2) / 2.0)
- + (((experiences.current.get(0).q2 + experiences.current
- .get(1).q2) / 2.0) - experiences.current
- .get(2).q2) / 2.0;
- log.info("Cr : q1 = " + q1 + " q2 = " + q2);
-
- } else if (lastCritere > experiences.current.get(0).criteria) {
- log.info("State 0 :R : lastCritere > current0 : R meilleur que N et moins bon que B");
- state = State.STATE_INIT;
- experiences.current.remove(2);//remove(3)avant
- doBoucle = true;
- log.info("remove W, simplex BNR");
-
- } else { // dernier cas possible: if (lastCritere < experiences.current.get(0).critere) {
- log.info("State 0 :R : lastCritere < current 0 : R meilleur que B, calcul de E");
- state = State.STATE_4;
-
- q1 = experiences.getExperience(number - 1).q1
- + (experiences.current.get(0).q1 + experiences.current
- .get(1).q1) / 2.0
- - experiences.current.get(2).q1;
- q2 = experiences.getExperience(number - 1).q2
- + (experiences.current.get(0).q2 + experiences.current
- .get(1).q2) / 2.0
- - experiences.current.get(2).q2;
- //q1 = experiences.current.get(3).q1 + (experiences.current.get(0).q1 + experiences.current.get(1).q1) / 2.0 - experiences.current.get(2).q1;
- //q2 = experiences.current.get(3).q2 + (experiences.current.get(0).q2 + experiences.current.get(1).q2) / 2.0 - experiences.current.get(2).q2;
- log.info("E : q1 = " + q1 + " q2 = " + q2);
- }
-
- } else if (state == State.STATE_1) {
- log.info("state 1, simplex BNCw");
- experiences.current.remove(3);
- experiences.current.remove(2);
- state = State.STATE_INIT;
- doBoucle = true;
-
- } else if (state == State.STATE_2) {
- log.info("state 2, simplex BNCr");
- experiences.current.remove(3);
- experiences.current.remove(2);
- state = State.STATE_INIT;
- doBoucle = true;
-
- } else if (state == State.STATE_4) {
- log.info("state 4 :comparaison de E a B");
- doBoucle = true;
- if (lastCritere < experiences.current.get(0).criteria) {
- log.info("E meilleur que B, remove 2 et 3 : simplex BNE");
- experiences.current.remove(3);
- experiences.current.remove(2);
- } else {
- log.info("E moins bon que B, remove 2 et 4, simplex BNR");
- experiences.current.remove(4);
- experiences.current.remove(2);
- }
-
- state = State.STATE_INIT;
- }
-
- }//fin du while
- //on remplit la table experiences
- experiences.getExperience(number).q1 = q1;
- experiences.getExperience(number).q2 = q2;
-
- log.info("on change Q dans la DB avec : q1 = " + q1 + " " + "q2 = " + q2);
-
- // on change la valeur de q dans la DB
- changeDB(experiences.getExperience(number), nextSimulation);
- }// fin du else (number > 3)
- return doNext;
- }// fin du before simulation
-
- /**
-
- * Call after each simulation, compute criteria for last simulation
- * @param context plan context
- * @param lastSimulation 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;
- log.info("after simulation");
- int number = context.getNumber();
- ResultStorage result = lastSimulation.getResultStorage();
-
- /////*** Simulated catches are cumulated over strategies, areas and metiers
-
- MatrixND L2 = result.getMatrix(param_Population,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
- // log.info("dim de L2" + " " + Arrays.toString(L2.getDim()));
- /////*** If some strategies, metiers or areas must not be included in the cumulated catches see below else put "//" at the beginning of line 297 and replace "L2" by "L" at line 289
- /////*** the strategies or so to exclude must be at the begining or end of the list you enter in the parameters interface
- /////*** fill the line MatrixND L = L2.getSubMatrix(a,b,c).copy(); as follow :
- /////*** a = 1 if you want to exclude strategies, 2 if metiers and 4 if areas
- /////*** b = indice of the first object considered
- /////*** c = number of object to keep after b, b included
- MatrixND L = L2.getSubMatrix(1, 2, 4).copy(); // for instance : keep strategies 2,3,4,5
- //log.info("sous matrice extraite");
- L = L.sumOverDim(1);// sum over strategies
- L = L.sumOverDim(2);// sum over metiers
- L = L.sumOverDim(4);// sum over zones
- log.info("sommes sur les strategies, metiers et zones faites");
-
- /////*** if observations are cumulated by groups else put "//" at the beginning of the following line
- L = L.sumOverDim(3);
- /////*** else if number of groups in your database differs from number of groups in observations ... write me an e-mail
-
- ////*** if observations are cumulated over quarter put 3, over year 12, else put "//" at the beginning of the following line
- L = L.sumOverDim(0, 3);
-
- L = L.reduce();
-
- ///////////////////Calcul du critere//////////////////
- log.info("calcul du critere");
- log.info("dim de L" + " " + Arrays.toString(L.getDim()));
- log.info("dim de obs" + " "
- + Arrays.toString(matrixDebarquement.getDim()));
- double crit = 0;
- for (MatrixIterator g = L.iterator(); g.hasNext();) {
- g.next();
- //boucle sur les trimestres et les classes d age
-
- int[] dim = g.getCoordinates();
-
- double obs = matrixDebarquement.getValue(dim);
- double simules = g.getValue();
-
- crit += Math.pow(obs - simules, 2); // crit = crit + (obs-simules)^2
- }// fin du for
- log.info("critere " + number + " = " + crit);
-
- //ajoute le critere dans la table experiences
- experiences.getExperience(number).criteria = crit;
-
- //ecriture de la table historic
- exportHisto += experiences.getExperience(number).q1 + ";"
- + experiences.getExperience(number).q2 + ";"
- + experiences.getExperience(number).criteria + "\n";
- org.codelutin.util.FileUtil.writeString(exportHistoric, exportHisto);
-
- return doNext;
-
- }// fin du after simulation
-
- /**
- * Modify nextSimulation database with q1 and q2 in exp.
- *
- * @param exp
- * @param nextSimulation
- * @throws Exception
- */
- protected void changeDB(Experience exp, SimulationStorage nextSimulation)
- throws Exception {
- //methode appelee dans before simualtion
- TopiaContext db = nextSimulation.getStorage().beginTransaction();//ouvrir un context pour modifier les donnees
- Population pop = (Population) db.findByTopiaId(param_Population.getTopiaId()); //reccupere la pop ciblee
- MatrixND c = pop.getCapturability(); // reccupere la matrice de capturabilité
-
- //log.info("Pour cette simulation : q1 = " + exp.q1 + ";" + "q2 = " + exp.q2 );
-
- /////*** that is where you explain how to fill the catchability matrix with q1 and q2
- for (MatrixIterator i = c.iterator(); i.hasNext();) {
- i.next();
- Object[] sem = i.getSemanticsCoordinates();
- PopulationGroup group = (PopulationGroup) sem[0];
- //PopulationSeasonInfo season = (PopulationSeasonInfo) sem[1];
-
- ////*** exemple when q2 corresponds to the 12 first groups (groups 0 to 11)
- if (group.getId() < 12) {
- i.setValue(exp.q2);
- } else {
- i.setValue(exp.q1);
- }
-
- /////*** exemple when it depends on seasons and groups
- /* if (season.getFirstMonth().after(Month.JULY) && group.getId() >=18){ //month >= aout && groupID >= 18
- i.setValue(exp.q2);
- }else {
- i.setValue(exp.q1);
- }
- */
-
- }//fin du for
-
- db.commitTransaction(); // effectue la modification
- db.closeContext(); // ferme le context
- }
-
- static public class Experiences {
- // cree la liste experiences ou sont stoqués q1,q2 et critere pour chaque simulation
-
- /** contains last simplex and potentialy 2 more simulation */
- public List<Experience> current = new ArrayList<Experience>();
-
- /** contains all experience done */
- public List<Experience> history = new ArrayList<Experience>();
-
- /**
- * 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;
- }//fin de la definition de getExperience
-
- /**
- * @return the history
- */
- public List<Experience> getHistory() {
- return this.history;
- }
- }// fin de la creation des listes experiences
-
- static public class Experience implements Comparable<Experience> {
- 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(Experience other) {
- int result = Double.compare(this.criteria, other.criteria);
- return result;
- }
- }
-
-}
\ No newline at end of file
Copied: isis-fish/trunk/src/test/resources/test-database/simulationplans/CalibrationSimplexePasVariable2Capturabilite.java (from rev 3393, isis-fish/trunk/src/test/resources/test-database/analyseplans/CalibrationSimplexePasVariable2Capturabilite.java)
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/simulationplans/CalibrationSimplexePasVariable2Capturabilite.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/simulationplans/CalibrationSimplexePasVariable2Capturabilite.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -0,0 +1,485 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2007 - 2011 Ifremer, CodeLutin, Sigrid Lehuta
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+package simulationplans;
+
+import static org.nuiton.i18n.I18n._;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.math.matrix.MatrixIterator;
+import org.nuiton.math.matrix.MatrixND;
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.util.FileUtil;
+import org.nuiton.util.StringUtil;
+
+import fr.ifremer.isisfish.datastore.ResultStorage;
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.entities.Population;
+import fr.ifremer.isisfish.entities.PopulationGroup;
+import fr.ifremer.isisfish.simulator.SimulationPlanContext;
+import fr.ifremer.isisfish.simulator.SimulationPlan;
+import fr.ifremer.isisfish.util.Doc;
+
+import scripts.ResultName;
+
+/**
+ * CalibrationSimplexePasVariable2Capturabilite.
+ *
+ * Created: 17 septembre 2007
+ *
+ * @author sigrid lehuta
+ * @version $Revision$
+ *
+ * Last update: $Date$
+ * by : $Author: bpoussin $
+ */
+
+// ////////////////////////////////////////////////////////////////////////
+// USER GUIDE
+//-------------------------------------------------------------------------
+// Script must be adapted to the case study (calibration data, catchability assumptions)
+// Script won't compile as it stands
+// Comments preceeded by /////*** explain where and how to adapt the script
+// Access to the APIs is free
+// ////////////////////////////////////////////////////////////////////////
+
+// ***You can modify class name if you want
+// ***BUT attention : file name and class name must be the same (without the extention ".java"),
+// ie here : "CalibrationSimplexePasVariable2Capturabilite"
+public class CalibrationSimplexePasVariable2Capturabilite implements SimulationPlan {
+
+ /** to use log facility, just put in your code: log.info("..."); */
+ static private Log log = LogFactory
+ .getLog(CalibrationSimplexePasVariable2Capturabilite.class);
+
+ enum State {
+ STATE_INIT, STATE_0, STATE_1, STATE_2, STATE_3, STATE_4
+ };
+
+ /////***here must appear the path to export the historic file ("Historic.csv")
+ //in which q1, q2 and objective function computed at each simulation are stored
+ /////***Attention : before beginning a new calibration rename any potential
+ //old Historic.csv files or they will be lost
+ protected File exportHistoric = new File("Historic.csv");
+
+ protected String exportHisto = "";
+
+ @Doc("Population which parameters are calibrated")
+ public Population param_Population = null;
+ @Doc("First initial point of the simplex: de la forme(\"xx;yy\")")
+ public String param_M1 = "2.42e-5;2.11e-6";// devient un parametre du plan d analyse
+ @Doc("Second initial point of the simplex")
+ public String param_M2 = "2.34e-5;2.59e-6";// devient un parametre du plan d analyse
+ @Doc("Third initial point of the simplex")
+ public String param_M3 = "2.59e-5;2.41e-6";// devient un parametre du plan d analyse
+
+ // ***put here the path and name of the file containing the data used to calibrate
+ // your fishery ( here observed landings per season and age groups)
+ @Doc(value = "file name and path of observed landings")
+ public String param_nomfichier_debarquements = "Observedlandings2001-2003.csv";
+ protected File debarquementsObserves;
+ protected MatrixND matrixDebarquement;
+
+ protected State state = State.STATE_INIT;
+ public Experiences experiences = new Experiences();
+
+ //*** write the name of the simulated matrix that contains the data corresponding
+ // to your observations (here MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP)
+ public String[] necessaryResult = {
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP
+ };
+
+ 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 _("Calibration using variable step Simplex method (Walters): user" +
+ "gives a file of observations (here catches)(.csv), simulated output" +
+ "will try to approach oservations by changing the values of catchability");
+ }
+
+ /**
+ * Appele au demarrage de la simulation, cette methode permet d'initialiser
+ * des valeurs
+ * @param context La simulation pour lequel on utilise cette regle
+ */
+ public void init(SimulationPlanContext 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);
+ }
+
+ // ***Create the matrix named matrixDebarquement that will contain your observed landings
+ // method: MatrixFactory.getInstance().create()
+ // ***Then import your file in it
+ // method : matrixDebarquement.importCSV();
+ log.info("MatrixDebarquement : " + matrixDebarquement);
+ }
+
+ double g1;
+ double g2;
+ double worst1;
+ double worst2;
+
+ /**
+ * 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(SimulationPlanContext context,
+ SimulationStorage nextSimulation) throws Exception {
+ // the whole beforeSimulation part codes for the variable step simplex
+ // algorithm (Walters et al.1999), no change to bring
+ boolean doNext = true;
+ boolean doBoucle = true;
+ log.info("before simulation");
+
+ int number = nextSimulation.getParameter().getAnalysePlanNumber();
+
+ if (number < 3) {
+ log.info("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 = 1000;
+ double q2 = 1000;
+ double lastCritere = experiences.getExperience(number - 1).criteria;
+ while (doBoucle) {
+ doBoucle = false;
+ if (state == State.STATE_INIT) {
+ doBoucle = false;
+ log.info("state init");
+
+ //ordonne les 3 premieres experiences selon leur critere
+ Collections.sort(experiences.current);
+ //log.info("SIMPLEXE : current 0 = " + experiences.current.get(0).criteria +
+ // "current 1 = " + experiences.current.get(1).criteria + "current 2 = " +
+ // experiences.current.get(2).criteria);
+ log.info("SIMPLEXE : current 0 = "
+ + experiences.current.get(0).criteria
+ + "current 1 = "
+ + experiences.current.get(1).criteria
+ + "current 2 = "
+ + experiences.current.get(2).criteria);
+ log.info("SIMPLEXE : Best q1 = "
+ + experiences.current.get(0).q1 + " q2 = "
+ + experiences.current.get(0).q2);
+ log.info("SIMPLEXE : NextBest q1 = "
+ + experiences.current.get(1).q1 + " q2 = "
+ + experiences.current.get(1).q2);
+ log.info("SIMPLEXE : Worst q1 = "
+ + experiences.current.get(2).q1 + " q2 = "
+ + experiences.current.get(2).q2);
+
+ //Calcul et evaluation de R
+ double g1 = (experiences.current.get(0).q1 + experiences.current
+ .get(1).q1) / 2.0;
+ double g2 = (experiences.current.get(0).q2 + experiences.current
+ .get(1).q2) / 2.0;
+ double worst1 = experiences.current.get(2).q1;
+ double worst2 = experiences.current.get(2).q2;
+
+ state = State.STATE_0;
+
+ q1 = 2 * g1 - worst1;
+ q2 = 2 * g2 - worst2;
+
+ log.info("R : q1 = " + q1 + " q2 = " + q2);
+
+ } else if (state == State.STATE_0) {
+ doBoucle = false;
+ log.info("state 0");
+
+ // on fait la 5eme avec des q qui dependent de la 4eme dans le dernier cas
+ //log.info("g1 = " + g1 + " " + "g2 = " + g2);
+ //log.info("worst1 = " + worst1 + " " + "worst2 = " + worst2);
+
+ if (lastCritere > experiences.current.get(2).criteria) {
+ log.info("State 0 : R : lastCtritere > current2 : R pire de W");
+ state = State.STATE_1;
+ //calcul de Cw
+ q1 = ((experiences.current.get(0).q1 + experiences.current
+ .get(1).q1) / 2.0)
+ - (((experiences.current.get(0).q1 + experiences.current
+ .get(1).q1) / 2.0) - experiences.current
+ .get(2).q1) / 2.0;
+ q2 = ((experiences.current.get(0).q2 + experiences.current
+ .get(1).q2) / 2.0)
+ - (((experiences.current.get(0).q2 + experiences.current
+ .get(1).q2) / 2.0) - experiences.current
+ .get(2).q2) / 2.0;
+ log.info("Cw : q1 = " + q1 + " q2 = " + q2);
+
+ } else if (lastCritere > experiences.current.get(1).criteria) {
+ log.info("State 0 :R : lastCritere > current 1 : R meilleur que W et moins bon que N");
+ state = State.STATE_2;
+ // calcul de Cr
+ q1 = ((experiences.current.get(0).q1 + experiences.current
+ .get(1).q1) / 2.0)
+ + (((experiences.current.get(0).q1 + experiences.current
+ .get(1).q1) / 2.0) - experiences.current
+ .get(2).q1) / 2.0;
+ q2 = ((experiences.current.get(0).q2 + experiences.current
+ .get(1).q2) / 2.0)
+ + (((experiences.current.get(0).q2 + experiences.current
+ .get(1).q2) / 2.0) - experiences.current
+ .get(2).q2) / 2.0;
+ log.info("Cr : q1 = " + q1 + " q2 = " + q2);
+
+ } else if (lastCritere > experiences.current.get(0).criteria) {
+ log.info("State 0 :R : lastCritere > current0 : R meilleur que N et moins bon que B");
+ state = State.STATE_INIT;
+ experiences.current.remove(2);//remove(3)avant
+ doBoucle = true;
+ log.info("remove W, simplex BNR");
+
+ } else { // dernier cas possible: if (lastCritere < experiences.current.get(0).critere) {
+ log.info("State 0 :R : lastCritere < current 0 : R meilleur que B, calcul de E");
+ state = State.STATE_4;
+
+ q1 = experiences.getExperience(number - 1).q1
+ + (experiences.current.get(0).q1 + experiences.current
+ .get(1).q1) / 2.0
+ - experiences.current.get(2).q1;
+ q2 = experiences.getExperience(number - 1).q2
+ + (experiences.current.get(0).q2 + experiences.current
+ .get(1).q2) / 2.0
+ - experiences.current.get(2).q2;
+ //q1 = experiences.current.get(3).q1 + (experiences.current.get(0).q1 + experiences.current.get(1).q1) / 2.0 - experiences.current.get(2).q1;
+ //q2 = experiences.current.get(3).q2 + (experiences.current.get(0).q2 + experiences.current.get(1).q2) / 2.0 - experiences.current.get(2).q2;
+ log.info("E : q1 = " + q1 + " q2 = " + q2);
+ }
+
+ } else if (state == State.STATE_1) {
+ log.info("state 1, simplex BNCw");
+ experiences.current.remove(3);
+ experiences.current.remove(2);
+ state = State.STATE_INIT;
+ doBoucle = true;
+
+ } else if (state == State.STATE_2) {
+ log.info("state 2, simplex BNCr");
+ experiences.current.remove(3);
+ experiences.current.remove(2);
+ state = State.STATE_INIT;
+ doBoucle = true;
+
+ } else if (state == State.STATE_4) {
+ log.info("state 4 :comparaison de E a B");
+ doBoucle = true;
+ if (lastCritere < experiences.current.get(0).criteria) {
+ log.info("E meilleur que B, remove 2 et 3 : simplex BNE");
+ experiences.current.remove(3);
+ experiences.current.remove(2);
+ } else {
+ log.info("E moins bon que B, remove 2 et 4, simplex BNR");
+ experiences.current.remove(4);
+ experiences.current.remove(2);
+ }
+
+ state = State.STATE_INIT;
+ }
+
+ }//fin du while
+ //on remplit la table experiences
+ experiences.getExperience(number).q1 = q1;
+ experiences.getExperience(number).q2 = q2;
+
+ log.info("on change Q dans la DB avec : q1 = " + q1 + " " + "q2 = " + q2);
+
+ // on change la valeur de q dans la DB
+ changeDB(experiences.getExperience(number), nextSimulation);
+ }// fin du else (number > 3)
+ return doNext;
+ }// fin du before simulation
+
+ /**
+ * Call after each simulation, compute criteria for last simulation.
+ *
+ * @param context plan context
+ * @param lastSimulation storage used for next simulation
+ * @return true if we must do next simulation, false to stop plan
+ * @throws Exception
+ */
+ public boolean afterSimulation(SimulationPlanContext context,
+ SimulationStorage lastSimulation) throws Exception {
+ boolean doNext = true;
+ log.info("after simulation");
+ int number = lastSimulation.getParameter().getAnalysePlanNumber();
+ ResultStorage result = lastSimulation.getResultStorage();
+
+ /////***import the matrix of simulated data (here landings) from the simulation result
+ MatrixND L = result.getMatrix(param_Population,
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ /////*** extract, sum, etc to obtain the same format/data as your observation matrix
+ // useful methods to work on matrix : sumOverDim(), getSubMatrix(), reduce()
+
+ ///////////////////Calcul du critere//////////////////
+ log.info("calcul de la fonction objectif");
+ log.info("dim de L" + " " + Arrays.toString(L.getDim()));
+ log.info("dim de obs" + " "
+ + Arrays.toString(matrixDebarquement.getDim()));
+
+ double obj = 0;
+ // *** using the matrixIterator assumes that the observation and simulated
+ // matrix are organised in the exact same way ( columns and rows corresponding in each of them)
+ for (MatrixIterator g = L.iterator(); g.hasNext();) {
+ g.next();
+ int[] dim = g.getCoordinates();
+ double obs = matrixDebarquement.getValue(dim);
+ double simules = g.getValue();
+ obj += Math.pow(obs - simules, 2);
+ }
+
+ //ajoute le critere dans la table experiences
+ experiences.getExperience(number).criteria = obj;
+
+ //ecriture de la table historic
+ exportHisto += experiences.getExperience(number).q1 + ";"
+ + experiences.getExperience(number).q2 + ";"
+ + experiences.getExperience(number).criteria + "\n";
+ org.nuiton.util.FileUtil.writeString(exportHistoric, exportHisto);
+
+ return doNext;
+ }// fin du after simulation
+
+ /**
+ * Modify nextSimulation database with q1 and q2 in exp.
+ *
+ * @param exp
+ * @param nextSimulation
+ * @throws Exception
+ */
+ protected void changeDB(Experience exp, SimulationStorage nextSimulation)
+ throws Exception {
+ // methode appelee dans before simualtion
+ TopiaContext db = nextSimulation.getStorage().beginTransaction();//ouvrir un context pour modifier les donnees
+ Population pop = (Population) db.findByTopiaId(param_Population.getTopiaId()); //reccupere la pop ciblee
+ MatrixND c = pop.getCapturability(); // reccupere la matrice de capturabilité
+
+ // *** that is where you explain how to fill the catchability matrix with q1 and q2
+ for (MatrixIterator i = c.iterator(); i.hasNext();) {
+ i.next();
+ Object[] sem = i.getSemanticsCoordinates();
+ PopulationGroup group = (PopulationGroup) sem[0];
+
+ // *** exemple when q2 corresponds to the 12 first groups (groups 0 to 11)
+ if (group.getId() < 12) {
+ i.setValue(exp.q2);
+ } else {
+ i.setValue(exp.q1);
+ }
+
+ // *** exemple when it depends on seasons and groups
+ /*PopulationSeasonInfo season = (PopulationSeasonInfo) sem[1];
+ if (season.getFirstMonth().after(Month.JULY) && group.getId() >=18){ //month >= aout && groupID >= 18
+ i.setValue(exp.q2);
+ } else {
+ i.setValue(exp.q1);
+ } */
+ }//fin du for
+
+ db.commitTransaction(); // effectue la modification
+ db.closeContext(); // ferme le context
+ }
+
+ static public class Experiences {
+ // cree la liste experiences ou sont stoqués q1,q2 et critere pour chaque simulation
+
+ /** contains last simplex and potentialy 2 more simulation */
+ public List<Experience> current = new ArrayList<Experience>();
+
+ /** contains all experience done */
+ public List<Experience> history = new ArrayList<Experience>();
+
+ /**
+ * 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;
+ }//fin de la definition de getExperience
+
+ /**
+ * @return the history
+ */
+ public List<Experience> getHistory() {
+ return this.history;
+ }
+ }// fin de la creation des listes experiences
+
+ static public class Experience implements Comparable<Experience> {
+ 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(Experience other) {
+ int result = Double.compare(this.criteria, other.criteria);
+ return result;
+ }
+ }
+
+}
\ No newline at end of file
Deleted: isis-fish/trunk/src/test/resources/test-database/simulationplans/SimulationNumberRestriction.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/analyseplans/SimulationNumberRestriction.java 2011-06-14 13:21:14 UTC (rev 3392)
+++ isis-fish/trunk/src/test/resources/test-database/simulationplans/SimulationNumberRestriction.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,120 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2009 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-package analyseplans;
-
-import static org.codelutin.i18n.I18n._;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.simulator.AnalysePlanContext;
-import fr.ifremer.isisfish.simulator.AnalysePlanIndependent;
-import fr.ifremer.isisfish.util.Doc;
-
-/**
- * ExempleSimulationsIndependantes.java
- *
- * Created: 2 mars 2007
- *
- * @author bpoussin <bpoussin at labs.libre-entreprise.org>
- * @version $Revision$
- *
- * Last update: $Date$ by : $Author: bpoussin $
- */
-public class SimulationNumberRestriction implements AnalysePlanIndependent {
-
- /** to use log facility, just put in your code: log.info("..."); */
- static private Log log = LogFactory.getLog(SimulationNumberRestriction.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,
- };
-
- @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 {
- return _("Permit to specify maximum simulation numbers");
- }
-
- /**
- * Appelé au démarrage de la simulation, cette méthode permet d'initialiser
- * des valeurs
- *
- * @param context La simulation pour lequel on utilise cette regle
- */
- @Override
- 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
- */
- @Override
- 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 lastSimulation storage used for last 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;
- }
-
-}
Copied: isis-fish/trunk/src/test/resources/test-database/simulationplans/SimulationNumberRestriction.java (from rev 3393, isis-fish/trunk/src/test/resources/test-database/analyseplans/SimulationNumberRestriction.java)
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/simulationplans/SimulationNumberRestriction.java (rev 0)
+++ isis-fish/trunk/src/test/resources/test-database/simulationplans/SimulationNumberRestriction.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -0,0 +1,117 @@
+/*
+ * #%L
+ * IsisFish data
+ * %%
+ * Copyright (C) 2006 - 2011 Ifremer, CodeLutin
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+package simulationplans;
+
+import static org.nuiton.i18n.I18n._;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import fr.ifremer.isisfish.datastore.SimulationStorage;
+import fr.ifremer.isisfish.simulator.SimulationPlanContext;
+import fr.ifremer.isisfish.simulator.SimulationPlanIndependent;
+import fr.ifremer.isisfish.util.Doc;
+
+/**
+ * ExempleSimulationsIndependantes.java
+ *
+ * Created: 2 mars 2007
+ *
+ * @author bpoussin <bpoussin at labs.libre-entreprise.org>
+ * @version $Revision$
+ *
+ * Last update: $Date$ by : $Author: bpoussin $
+ */
+public class SimulationNumberRestriction implements SimulationPlanIndependent {
+
+ /** to use log facility, just put in your code: log.info("..."); */
+ static private Log log = LogFactory.getLog(SimulationNumberRestriction.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,
+ };
+
+ @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 {
+ return _("Permit to specify maximum simulation numbers");
+ }
+
+ /**
+ * Appelé au démarrage de la simulation, cette méthode permet d'initialiser
+ * des valeurs
+ *
+ * @param context La simulation pour lequel on utilise cette regle
+ */
+ @Override
+ public void init(SimulationPlanContext 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
+ */
+ @Override
+ public boolean beforeSimulation(SimulationPlanContext context,
+ SimulationStorage nextSimulation) throws Exception {
+ boolean result = nextSimulation.getParameter().getAnalysePlanNumber() < param_max;
+ return result;
+ }
+
+ /**
+ * Call after each simulation
+ *
+ * @param context
+ * plan context
+ * @param lastSimulation storage used for last simulation
+ * @return true if we must do next simulation, false to stop plan
+ * @throws Exception
+ */
+ @Override
+ public boolean afterSimulation(SimulationPlanContext context,
+ SimulationStorage lastSimulation) throws Exception {
+ return true;
+ }
+
+}
Modified: isis-fish/trunk/src/test/resources/test-database/simulators/DefaultSimulator.java
===================================================================
--- isis-fish/trunk/src/test/resources/test-database/simulators/DefaultSimulator.java 2011-07-08 14:21:12 UTC (rev 3440)
+++ isis-fish/trunk/src/test/resources/test-database/simulators/DefaultSimulator.java 2011-07-08 14:22:36 UTC (rev 3441)
@@ -1,11 +1,8 @@
/*
* #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
+ * IsisFish data
* %%
- * Copyright (C) 2009 - 2010 Ifremer, Code Lutin
+ * Copyright (C) 2006 - 2011 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
@@ -23,18 +20,6 @@
* #L%
*/
-/* *
- * DefaultSimulator.java
- *
- * Created: 21 ao?t 2006 10:57:46
- *
- * @author poussin
- * @version $Revision: 1 $
- *
- * Last update: $Date: 2009-10-19 14:25:49 +0200 (lun., 19 oct. 2009) $
- * by : $Author: bpoussin $
- */
-
package simulators;
import static org.nuiton.i18n.I18n._;
@@ -66,18 +51,24 @@
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.TimeStep;
import fr.ifremer.isisfish.types.Month;
/**
+ * 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 $
*/
-
public class DefaultSimulator implements Simulator {
/** to use log facility, just put in your code: log.info("..."); */
- private Log log = LogFactory.getLog(DefaultSimulator.class);
+ static private Log log = LogFactory.getLog(DefaultSimulator.class);
/**
* Called by isis don't modify signature
@@ -88,8 +79,8 @@
.getParameter();
SimulationControl control = context.getSimulationControl();
int lastYear = param.getNumberOfYear();
- int lastDate = lastYear * Month.NUMBER_OF_MONTH;
- Date date = control.getDate();
+ int lastStep = lastYear * Month.NUMBER_OF_MONTH;
+ TimeStep step = control.getTimeStep();
ResultManager resManager = context.getResultManager();
TopiaContext db = context.getDB();
@@ -101,7 +92,7 @@
MetierMonitor metierMonitor = context.getMetierMonitor();
RuleMonitor ruleMonitor = context.getRuleMonitor();
- List<Population> allpops = siMatrix.getPopulations(date);
+ List<Population> allpops = siMatrix.getPopulations(step);
populationMonitor.init(allpops);
for (Population pop : allpops) {
@@ -132,7 +123,7 @@
//
// Simulation loop
//
- while (date.getDate() < lastDate) {
+ while (step.getStep() < lastStep) {
//
// if user stop simulation before last year
@@ -141,9 +132,9 @@
break;
}
- control.setDate(date);
- control.setProgress(date.getDate());
- control.setText(_("begin step " + date));
+ control.setTimeStep(step);
+ control.setProgress(step.getStep());
+ control.setText(_("begin step " + step));
//
// Reload parameters for current step
@@ -156,18 +147,18 @@
// raz des metiers interdits et des licences
metierMonitor.clear();
- if (date.getMonth().equals(Month.JANUARY)) {
+ if (step.getMonth().equals(Month.JANUARY)) {
populationMonitor.clearCatch();
}
// only if there are one or more strategy
- if (siMatrix.getStrategies(date).size() > 0) {
+ if (siMatrix.getStrategies(step).size() > 0) {
if (resManager.isEnabled(ResultName.MATRIX_NO_ACTIVITY)) {
- MatrixND mat = metierMonitor.getOrCreateNoActivity(date,
+ MatrixND mat = metierMonitor.getOrCreateNoActivity(step,
ResultName.MATRIX_NO_ACTIVITY, siMatrix
- .getStrategies(date), siMatrix
- .getMetiers(date));
- resManager.addResult(date, mat);
+ .getStrategies(step), siMatrix
+ .getMetiers(step));
+ resManager.addResult(step, mat);
}
}
@@ -177,22 +168,22 @@
control.setText("Evaluate rules conditions (" + rules.size()
+ " rules)");
for (Rule rule : rules) {
- for (Metier metier : siMatrix.getMetiers(date)) {
+ for (Metier metier : siMatrix.getMetiers(step)) {
boolean active = false;
try {
- active = rule.condition(context, date, metier);
+ active = rule.condition(context, step, metier);
} catch (Exception eee) {
if (log.isWarnEnabled()) {
log.warn("Can't evaluate rule condition for: "
+ rule, eee);
}
}
- ruleMonitor.setEvaluationCondition(date, rule, metier,
+ ruleMonitor.setEvaluationCondition(step, rule, metier,
active);
if (active) {
log.info("Activate rule: "
+ rule.getClass().getSimpleName());
- resManager.addActiveRule(date, rule);
+ resManager.addActiveRule(step, rule);
}
}
}
@@ -202,11 +193,11 @@
//
control.setText("Do pre action Rules");
for (Rule rule : rules) {
- for (Metier metier : siMatrix.getMetiers(date)) {
- boolean condition = ruleMonitor.getEvalutionCondition(date,
+ for (Metier metier : siMatrix.getMetiers(step)) {
+ boolean condition = ruleMonitor.getEvalutionCondition(step,
rule, metier);
if (condition) {
- rule.preAction(context, date, metier);
+ rule.preAction(context, step, metier);
}
}
}
@@ -215,16 +206,16 @@
// Keep modification's information done in rule
//
if (resManager.isEnabled(ResultName.MATRIX_METIER_ZONE)) {
- MatrixND metierZone = siMatrix.getMetierZone(date);
- resManager.addResult(date, metierZone);
+ MatrixND metierZone = siMatrix.getMetierZone(step);
+ resManager.addResult(step, metierZone);
}
//
// Simulate one step for all pop
//
control.setText("Simulate one month");
- for (Population pop : siMatrix.getPopulations(date)) {
- computeMonth(context, siMatrix, date, pop);
+ for (Population pop : siMatrix.getPopulations(step)) {
+ computeMonth(context, siMatrix, step, pop);
}
//
@@ -232,19 +223,19 @@
//
// only if there are one or more strategy
- if (siMatrix.getStrategies(date).size() > 0) {
+ if (siMatrix.getStrategies(step).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);
+ .matrixEffortPerStrategyMet(step);
+ resManager.addResult(step, effortPerStrategyMet);
}
if (resManager.isEnabled(ResultName.MATRIX_EFFORT_NOMINAL_PER_STRATEGY_MET)) {
- MatrixND effortNominalPerStrategyMet = siMatrix.matrixEffortNominalPerStrategyMet(date);
- resManager.addResult(date, effortNominalPerStrategyMet);
+ MatrixND effortNominalPerStrategyMet = siMatrix.matrixEffortNominalPerStrategyMet(step);
+ resManager.addResult(step, effortNominalPerStrategyMet);
}
//
@@ -253,7 +244,7 @@
if (!"false".equalsIgnoreCase(param.getTagValue().get(
"ecoResult"))) {
control.setText("Add economics results");
- saveGravityModel(date, resManager, gravityModel);
+ saveGravityModel(step, resManager, gravityModel);
}
}
@@ -261,9 +252,9 @@
// 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);
+ for (Population pop : siMatrix.getPopulations(step)) {
+ MatrixND matPrice = siMatrix.matrixPrice(step, pop);
+ resManager.addResult(step, pop, matPrice);
}
}
@@ -272,43 +263,43 @@
//
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);
+ for (Metier metier : siMatrix.getMetiers(step)) {
+ if (ruleMonitor.getEvalutionCondition(step, rule, metier)) {
+ rule.postAction(context, step, 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) {
+ if (siMatrix.getStrategies(step).size() > 0) {
control.setText("Compute discard and landing");
- for (Population pop : siMatrix.getPopulations(date)) {
+ for (Population pop : siMatrix.getPopulations(step)) {
//
// 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
+ MatrixND discard = populationMonitor.getDiscard(step, pop);
+ if (discard != null || step.getStep() == 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),
+ new List[] { siMatrix.getStrategies(step),
+ siMatrix.getMetiers(step),
pop.getPopulationGroup(),
pop.getPopulationZone() },
new String[] { n_("Strategies"),
n_("Metiers"), n_("Groups"),
n_("Zones") });
}
- resManager.addResult(date, pop, discard);
+ resManager.addResult(step, 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,
+ pop, step, discard);
+ resManager.addResult(step, pop,
discardWeightPerStrategyMet);
}
@@ -324,7 +315,7 @@
landing = landing.minus(discard);
}
landing.setName(ResultName.MATRIX_LANDING_PER_MET);
- resManager.addResult(date, pop, landing);
+ resManager.addResult(step, pop, landing);
}
}
}
@@ -345,7 +336,7 @@
//
// Go next step
//
- date = date.next();
+ step = step.next();
}
}
@@ -356,7 +347,7 @@
}
protected void computeMonth(SimulationContext context, SiMatrix siMatrix,
- Date date, Population pop) throws IsisFishException, TopiaException {
+ TimeStep step, Population pop) throws IsisFishException, TopiaException {
// to add result
ResultStorage resManager = context.getSimulationStorage()
.getResultStorage();
@@ -365,7 +356,7 @@
MatrixND N = popMon.getN(pop);
if (log.isInfoEnabled()) {
- log.info("====================== begin " + date + " - " + pop
+ log.info("====================== begin " + step + " - " + pop
+ " =========================== "
+ System.currentTimeMillis());
log.info("N: " + N);
@@ -373,19 +364,19 @@
// add N and biomass result now, before computation
// N is reassigned during computation
- resManager.addResult(date, pop, N);
+ resManager.addResult(step, pop, N);
if (resManager.isEnabled(ResultName.MATRIX_BIOMASS)) {
- MatrixND biomass = siMatrix.matrixBiomass(N, pop, date);
- resManager.addResult(date, pop, biomass);
+ MatrixND biomass = siMatrix.matrixBiomass(N, pop, step);
+ resManager.addResult(step, pop, biomass);
}
- Month month = date.getMonth();
+ Month month = step.getMonth();
PopulationSeasonInfo info = pop.getPopulationSeasonInfo(month);
// group change
MatrixND CA = null;
- if (date.getDate() == 0) {
+ if (step.getStep() == 0) {
CA = MatrixFactory.getInstance().matrixId(
pop.sizePopulationGroup() * pop.sizePopulationZone());
} else {
@@ -426,10 +417,10 @@
// ajout de la matrice R dans le suivi de la pop comme etant
// la reproduction pour le mois courant.
- popMon.setReproduction(date, pop, R);
+ popMon.setReproduction(step, pop, R);
// recrutement
- MatrixND recruitment = popMon.getRecruitment(date, pop);
+ MatrixND recruitment = popMon.getRecruitment(step, pop);
log.debug("recruitment: " + recruitment);
// mortalite de la reproduction
@@ -438,84 +429,84 @@
N = N.add(recruitment);
log.debug("N after recru: " + N);
- if (resManager.isEnabled(ResultName.MATRIX_ABUNDANCE)) {
+ if (resManager.isEnabled(ResultName.MATRIX_ABUNDANCE_BEGIN_MONTH)) {
MatrixND abondanceBM = siMatrix.matrixAbondanceBeginMonth(N, pop,
- date);
- resManager.addResult(date, pop, abondanceBM);
+ step);
+ resManager.addResult(step, pop, abondanceBM);
}
- if (resManager.isEnabled(ResultName.MATRIX_BIOMASS)) {
- MatrixND biomassBM = siMatrix.matrixBiomassBeginMonth(N, pop, date);
- resManager.addResult(date, pop, biomassBM);
+ if (resManager.isEnabled(ResultName.MATRIX_BIOMASS_BEGIN_MONTH)) {
+ MatrixND biomassBM = siMatrix.matrixBiomassBeginMonth(N, pop, step);
+ resManager.addResult(step, pop, biomassBM);
}
MatrixND abundance = N;
// compute fishing matrix only if there are one or more strategy
- if (siMatrix.getStrategies(date).size() > 0) {
+ if (siMatrix.getStrategies(step).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);
+ abundance = siMatrix.matrixAbundance(N, pop, step);
catchPerStrategyMetPerZonePop = siMatrix
- .matrixCatchPerStrategyMetPerZonePop(N, pop, date);
+ .matrixCatchPerStrategyMetPerZonePop(N, pop, step);
} else { // en zone
MatrixND matrixFishingMortality = siMatrix
- .matrixFishingMortality(date, pop);
- resManager.addResult(date, pop, matrixFishingMortality);
+ .matrixFishingMortality(step, pop);
+ resManager.addResult(step, pop, matrixFishingMortality);
- abundance = siMatrix.matrixAbundance(N, pop, date,
+ abundance = siMatrix.matrixAbundance(N, pop, step,
matrixFishingMortality);
// this matrix is necessary for matrixCatchPerStrategyMet
MatrixND catchRatePerStrategyMet = siMatrix
- .matrixCatchRatePerStrategyMetPerZone(pop, date,
+ .matrixCatchRatePerStrategyMetPerZone(pop, step,
matrixFishingMortality);
- resManager.addResult(date, pop, catchRatePerStrategyMet);
+ resManager.addResult(step, pop, catchRatePerStrategyMet);
catchPerStrategyMetPerZonePop = siMatrix
- .matrixCatchPerStrategyMetPerZone(N, pop, date,
+ .matrixCatchPerStrategyMetPerZone(N, pop, step,
catchRatePerStrategyMet);
}
popMon.holdCatch(pop, catchPerStrategyMetPerZonePop);
- resManager.addResult(date, pop, catchPerStrategyMetPerZonePop);
+ resManager.addResult(step, pop, catchPerStrategyMetPerZonePop);
if (resManager
.isEnabled(ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP)) {
MatrixND catchWeightPerStrategyMet = siMatrix
- .matrixCatchWeightPerStrategyMetPerZonePop(date, pop,
+ .matrixCatchWeightPerStrategyMetPerZonePop(step, pop,
catchPerStrategyMetPerZonePop);
- resManager.addResult(date, pop, catchWeightPerStrategyMet);
+ resManager.addResult(step, pop, catchWeightPerStrategyMet);
}
if (isEffortByCell(context)) {
MatrixND catchPerStrategyMetPerZoneMet = siMatrix
- .matrixCatchPerStrategyMetPerZoneMet(N, pop, date);
- resManager.addResult(date, pop, catchPerStrategyMetPerZoneMet);
+ .matrixCatchPerStrategyMetPerZoneMet(N, pop, step);
+ resManager.addResult(step, pop, catchPerStrategyMetPerZoneMet);
if (resManager
.isEnabled(ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_MET)) {
MatrixND catchWeightPerStrategyMet = siMatrix
- .matrixCatchWeightPerStrategyMetPerZoneMet(date,
+ .matrixCatchWeightPerStrategyMetPerZoneMet(step,
pop, catchPerStrategyMetPerZoneMet);
- resManager.addResult(date, pop, catchWeightPerStrategyMet);
+ resManager.addResult(step, pop, catchWeightPerStrategyMet);
}
}
} else { // no strategies
// compute only if fishing mortality =0 to apply Natural Mortality
- abundance = siMatrix.matrixAbundanceSsF(N, pop, date);
+ abundance = siMatrix.matrixAbundanceSsF(N, pop, step);
}
log.debug("abundance: " + abundance);
// Keep new N
popMon.setN(pop, abundance);
- log.debug("====================== end " + date + " - " + pop
+ log.debug("====================== end " + step + " - " + pop
+ " ===========================");
}
@@ -526,43 +517,43 @@
* @throws IsisFishException
* @throws TopiaException
*/
- private void saveGravityModel(Date date, ResultManager resManager,
+ private void saveGravityModel(TimeStep step, 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);
+ .matrixFishingTimePerMonthPerVessel(step);
+ resManager.addResult(step, mat);
}
if (resManager
.isEnabled(ResultName.MATRIX_FUEL_COSTS_OF_TRAVEL_PER_VESSEL)) {
- MatrixND mat = gravityModel.matrixFuelCostsOfTravelPerVessel(date);
- resManager.addResult(date, mat);
+ MatrixND mat = gravityModel.matrixFuelCostsOfTravelPerVessel(step);
+ resManager.addResult(step, mat);
}
if (resManager.isEnabled(ResultName.MATRIX_COSTS_OF_FISHING_PER_VESSEL)) {
- MatrixND mat = gravityModel.matrixCostsOfFishingPerVessel(date);
- resManager.addResult(date, mat);
+ MatrixND mat = gravityModel.matrixCostsOfFishingPerVessel(step);
+ resManager.addResult(step, mat);
}
if (resManager.isEnabled(ResultName.MATRIX_FUEL_COSTS_PER_VESSEL)) {
- MatrixND mat = gravityModel.matrixFuelCostsOfTravelPerVessel(date);
- resManager.addResult(date, mat);
+ MatrixND mat = gravityModel.matrixFuelCostsOfTravelPerVessel(step);
+ resManager.addResult(step, mat);
}
if (resManager
.isEnabled(ResultName.MATRIX_REPAIR_AND_MAINTENANCE_GEAR_COSTS_PER_VESSEL)) {
MatrixND mat = gravityModel
- .matrixRepairAndMaintenanceGearCostsPerVessel(date);
- resManager.addResult(date, mat);
+ .matrixRepairAndMaintenanceGearCostsPerVessel(step);
+ resManager.addResult(step, mat);
}
if (resManager
.isEnabled(ResultName.MATRIX_OTHER_RUNNING_COSTS_PER_VESSEL)) {
- MatrixND mat = gravityModel.matrixOtherRunningCostsPerVessel(date);
- resManager.addResult(date, mat);
+ MatrixND mat = gravityModel.matrixOtherRunningCostsPerVessel(step);
+ resManager.addResult(step, mat);
}
if (resManager
.isEnabled(ResultName.MATRIX_SHARED_NOT_FIXED_COSTS_PER_VESSEL)) {
MatrixND mat = gravityModel
- .matrixSharedNotFixedCostsPerVessel(date);
- resManager.addResult(date, mat);
+ .matrixSharedNotFixedCostsPerVessel(step);
+ resManager.addResult(step, mat);
}
// if (resManager.isEnabled(ResultName.MATRIX_SHARED_FIXED_COSTS_PER_VESSEL_PER_MET)) {
// MatrixND mat = gravityModel.matrixSharedFixedCostsPerVesselPerMet(date);
@@ -571,80 +562,80 @@
if (resManager
.isEnabled(ResultName.MATRIX_GROSS_VALUE_OF_LANDINGS_PER_SPECIES_PER_STRATEGY_MET)) {
MatrixND mat = gravityModel
- .matrixGrossValueOfLandingsPerSpeciesPerStrategyMet(date);
- resManager.addResult(date, mat);
+ .matrixGrossValueOfLandingsPerSpeciesPerStrategyMet(step);
+ resManager.addResult(step, mat);
}
if (resManager
.isEnabled(ResultName.MATRIX_GROSS_VALUE_OF_LANDINGS_PER_STRATEGY_MET)) {
MatrixND mat = gravityModel
- .matrixGrossValueOfLandingsPerStrategyMet(date);
- resManager.addResult(date, mat);
+ .matrixGrossValueOfLandingsPerStrategyMet(step);
+ resManager.addResult(step, mat);
}
if (resManager
.isEnabled(ResultName.MATRIX_GROSS_VALUE_OF_LANDINGS_PER_STRATEGY_MET_PER_VESSEL)) {
MatrixND mat = gravityModel
- .matrixGrossValueOfLandingsPerStrategyMetPerVessel(date);
- resManager.addResult(date, mat);
+ .matrixGrossValueOfLandingsPerStrategyMetPerVessel(step);
+ resManager.addResult(step, mat);
}
if (resManager
.isEnabled(ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET)) {
MatrixND mat = gravityModel
- .matrixNetValueOfLandingsPerStrategyMet(date);
- resManager.addResult(date, mat);
+ .matrixNetValueOfLandingsPerStrategyMet(step);
+ resManager.addResult(step, mat);
}
if (resManager
.isEnabled(ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET_PER_VESSEL)) {
MatrixND mat = gravityModel
- .matrixNetValueOfLandingsPerStrategyMetPerVessel(date);
- resManager.addResult(date, mat);
+ .matrixNetValueOfLandingsPerStrategyMetPerVessel(step);
+ resManager.addResult(step, mat);
}
if (resManager
.isEnabled(ResultName.MATRIX_NET_RENEVUE_TO_SHARE_PER_STRATEGY_MET_PER_VESSEL)) {
MatrixND mat = gravityModel
- .matrixNetRenevueToSharePerStrategyMetPerVessel(date);
- resManager.addResult(date, mat);
+ .matrixNetRenevueToSharePerStrategyMetPerVessel(step);
+ resManager.addResult(step, mat);
}
if (resManager
.isEnabled(ResultName.MATRIX_CREW_SHARE_PER_STRATEGY_MET_PER_VESSEL)) {
MatrixND mat = gravityModel
- .matrixCrewSharePerStrategyMetPerVessel(date);
- resManager.addResult(date, mat);
+ .matrixCrewSharePerStrategyMetPerVessel(step);
+ resManager.addResult(step, 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);
+ .matrixOwnerMarginOverVariableCostsPerStrategyMetPerVessel(step);
+ resManager.addResult(step, 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);
+ .matrixVesselMarginOverVariableCostsPerStrategyMetPerVessel(step);
+ resManager.addResult(step, mat);
}
if (resManager
.isEnabled(ResultName.MATRIX_OWNER_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_PER_VESSEL)) {
MatrixND mat = gravityModel
- .matrixOwnerMarginOverVariableCostsPerStrategyPerVessel(date);
- resManager.addResult(date, mat);
+ .matrixOwnerMarginOverVariableCostsPerStrategyPerVessel(step);
+ resManager.addResult(step, mat);
}
if (resManager
.isEnabled(ResultName.MATRIX_OWNER_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY)) {
MatrixND mat = gravityModel
- .matrixOwnerMarginOverVariableCostsPerStrategy(date);
- resManager.addResult(date, mat);
+ .matrixOwnerMarginOverVariableCostsPerStrategy(step);
+ resManager.addResult(step, mat);
}
if (resManager
.isEnabled(ResultName.MATRIX_VESSEL_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY_PER_VESSEL)) {
MatrixND mat = gravityModel
- .matrixVesselMarginOverVariableCostsPerStrategyPerVessel(date);
- resManager.addResult(date, mat);
+ .matrixVesselMarginOverVariableCostsPerStrategyPerVessel(step);
+ resManager.addResult(step, mat);
}
if (resManager
.isEnabled(ResultName.MATRIX_VESSEL_MARGIN_OVER_VARIABLE_COSTS_PER_STRATEGY)) {
MatrixND mat = gravityModel
- .matrixVesselMarginOverVariableCostsPerStrategy(date);
- resManager.addResult(date, mat);
+ .matrixVesselMarginOverVariableCostsPerStrategy(step);
+ resManager.addResult(step, mat);
}
}
1
0
r3440 - isis-fish/trunk/src/test/java/fr/ifremer/isisfish/util
by chatellier@users.labs.libre-entreprise.org 08 Jul '11
by chatellier@users.labs.libre-entreprise.org 08 Jul '11
08 Jul '11
Author: chatellier
Date: 2011-07-08 14:21:12 +0000 (Fri, 08 Jul 2011)
New Revision: 3440
Log:
Fix tests
Modified:
isis-fish/trunk/src/test/java/fr/ifremer/isisfish/util/JavadocHelperTest.java
Modified: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/util/JavadocHelperTest.java
===================================================================
--- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/util/JavadocHelperTest.java 2011-07-08 14:08:32 UTC (rev 3439)
+++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/util/JavadocHelperTest.java 2011-07-08 14:21:12 UTC (rev 3440)
@@ -35,6 +35,7 @@
import org.junit.Test;
import fr.ifremer.isisfish.AbstractIsisFishTest;
+import fr.ifremer.isisfish.datastore.SimulationPlanStorage;
/**
* CompileHelperTest.
@@ -65,7 +66,8 @@
File currentDirectory = getCurrentDatabaseDirectory();
File destinationDirectory = new File(getTestDirectory(), "isis-docs");
- File testJavaFile = new File(currentDirectory, "analyseplans" + File.separatorChar + "CalibrationSimplexePasVariable2Capturabilite.java");
+ File testJavaFile = new File(currentDirectory, SimulationPlanStorage.SIMULATION_PLAN_PATH
+ + File.separatorChar + "CalibrationSimplexePasVariable2Capturabilite.java");
PrintWriter out = new PrintWriter(System.out);
int result = JavadocHelper.generateJavadoc(currentDirectory, testJavaFile,
1
0
r3439 - isis-fish/trunk/src/main/resources/templates/script
by chatellier@users.labs.libre-entreprise.org 08 Jul '11
by chatellier@users.labs.libre-entreprise.org 08 Jul '11
08 Jul '11
Author: chatellier
Date: 2011-07-08 14:08:32 +0000 (Fri, 08 Jul 2011)
New Revision: 3439
Log:
Refactoring :
- Date > TimeStep
Modified:
isis-fish/trunk/src/main/resources/templates/script/simulationplan.ftl
Modified: isis-fish/trunk/src/main/resources/templates/script/simulationplan.ftl
===================================================================
--- isis-fish/trunk/src/main/resources/templates/script/simulationplan.ftl 2011-07-08 13:04:30 UTC (rev 3438)
+++ isis-fish/trunk/src/main/resources/templates/script/simulationplan.ftl 2011-07-08 14:08:32 UTC (rev 3439)
@@ -33,7 +33,7 @@
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.types.TimeStep;
import fr.ifremer.isisfish.entities.*;
import fr.ifremer.isisfish.simulator.SimulationPlan;
import fr.ifremer.isisfish.simulator.SimulationPlanContext;
1
0
r3438 - isis-fish/trunk/src/main/resources/templates/script
by chatellier@users.labs.libre-entreprise.org 08 Jul '11
by chatellier@users.labs.libre-entreprise.org 08 Jul '11
08 Jul '11
Author: chatellier
Date: 2011-07-08 13:04:30 +0000 (Fri, 08 Jul 2011)
New Revision: 3438
Log:
Fix javadoc
Modified:
isis-fish/trunk/src/main/resources/templates/script/rule.ftl
Modified: isis-fish/trunk/src/main/resources/templates/script/rule.ftl
===================================================================
--- isis-fish/trunk/src/main/resources/templates/script/rule.ftl 2011-07-08 11:26:05 UTC (rev 3437)
+++ isis-fish/trunk/src/main/resources/templates/script/rule.ftl 2011-07-08 13:04:30 UTC (rev 3438)
@@ -31,7 +31,7 @@
import fr.ifremer.isisfish.util.Doc;
import fr.ifremer.isisfish.simulator.SimulationContext;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.entities.*;
import fr.ifremer.isisfish.rule.AbstractRule;
import fr.ifremer.isisfish.datastore.SimulationStorage;
@@ -86,24 +86,24 @@
* La condition qui doit etre vrai pour faire les actions.
*
* @param context la simulation pour lequel on utilise cette regle
- * @param date la date courante
- * @param metier le metier
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
* @return vrai si on souhaite que les actions soit faites
*/
- public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception {
+ public boolean condition(SimulationContext context, TimeStep step, Metier metier) throws Exception {
// TODO
return false;
}
/**
- * Si la condition est vrai alors cette action est executée avant le pas
+ * Si la condition est vrai alors cette action est executee avant le pas
* de temps de la simulation.
*
* @param context la simulation pour lequel on utilise cette regle
- * @param date la date courant
- * @param metier le metier
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void preAction(SimulationContext context, Date date, Metier metier) throws Exception {
+ public void preAction(SimulationContext context, TimeStep step, Metier metier) throws Exception {
// TODO
}
@@ -111,11 +111,11 @@
* Si la condition est vrai alors cette action est executée apres le pas
* de temps de la simulation.
*
- * @param context la simulation pour lequel on utilise cette regle
- * @param date la date courant
- * @param metier le metier
+ * @param context La simulation pour lequel on utilise cette regle
+ * @param step le pas de temps courant
+ * @param metier le metier concerné
*/
- public void postAction(SimulationContext context, Date date, Metier metier) throws Exception {
+ public void postAction(SimulationContext context, TimeStep step, Metier metier) throws Exception {
// TODO
}
}
\ No newline at end of file
1
0
r3437 - in isis-fish/trunk/src: main/java/fr/ifremer/isisfish/aspect main/java/fr/ifremer/isisfish/datastore main/java/fr/ifremer/isisfish/datastore/migration main/java/fr/ifremer/isisfish/entities main/java/fr/ifremer/isisfish/rule main/java/fr/ifremer/isisfish/simulator main/java/fr/ifremer/isisfish/simulator/launcher main/java/fr/ifremer/isisfish/types main/java/fr/ifremer/isisfish/types/hibernate main/java/fr/ifremer/isisfish/ui/result main/java/fr/ifremer/isisfish/ui/widget/editor m
by chatellier@users.labs.libre-entreprise.org 08 Jul '11
by chatellier@users.labs.libre-entreprise.org 08 Jul '11
08 Jul '11
Author: chatellier
Date: 2011-07-08 11:26:05 +0000 (Fri, 08 Jul 2011)
New Revision: 3437
Log:
Refactoring :
- Date > TimeStep
Added:
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/TimeStep.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/TimeStepType.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/TimeStepConverter.java
Removed:
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/DateType.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/DateConverter.java
Modified:
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/aspect/RuleAspect.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/ResultStorage.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/migration/MigrationV33V40.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/entities/SetOfVesselsImpl.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/rule/AbstractRule.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/rule/Rule.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/MetierMonitor.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/PopulationMonitor.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/ResultManager.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/RuleMonitor.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationControl.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationResultGetter.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationResultListener.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationResultXML.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/InProcessSimulatorLauncher.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceTableModel.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/Date.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/MatrixSummaryRenderer.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/ResultMatrixFilter.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/YearSumDimensionAction.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/widget/editor/ParameterTableCellEditor.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/ConverterUtil.java
isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/StringConverter.java
isis-fish/trunk/src/main/xmi/isis-fish.zargo
isis-fish/trunk/src/test/java/fr/ifremer/isisfish/rule/RuleMock.java
isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceIT.java
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/aspect/RuleAspect.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/aspect/RuleAspect.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/aspect/RuleAspect.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -36,12 +36,12 @@
import fr.ifremer.isisfish.entities.Metier;
import fr.ifremer.isisfish.rule.Rule;
import fr.ifremer.isisfish.simulator.SimulationContext;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* Aspect utiliser pour intersepecter les appels a
- * {@link Rule#init(SimulationContext)}, {@link Rule#preAction(SimulationContext, Date, Metier)},
- * {@link Rule#postAction(SimulationContext, Date, Metier)} et memoriser
+ * {@link Rule#init(SimulationContext)}, {@link Rule#preAction(SimulationContext, TimeStep, Metier)},
+ * {@link Rule#postAction(SimulationContext, TimeStep, Metier)} et memoriser
* le temps mit.
*
* @author chatellier
@@ -79,7 +79,7 @@
}
/**
- * Aspect around {@link Rule#preAction(SimulationContext, Date, Metier)} in packages "rules".
+ * Aspect around {@link Rule#preAction(SimulationContext, TimeStep, Metier)} in packages "rules".
*
* @param jp join point
* @return preAction result
@@ -93,7 +93,7 @@
}
/**
- * Aspect around {@link Rule#postAction(SimulationContext, Date, Metier)} in packages "rules".
+ * Aspect around {@link Rule#postAction(SimulationContext, TimeStep, Metier)} in packages "rules".
*
* @param jp join point
* @return preAction result
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/ResultStorage.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/ResultStorage.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/ResultStorage.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -60,7 +60,7 @@
import fr.ifremer.isisfish.simulator.SimulationPlan;
import fr.ifremer.isisfish.simulator.SimulationResultGetter;
import fr.ifremer.isisfish.simulator.SimulationResultListener;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.types.Month;
/**
@@ -75,13 +75,14 @@
* Mise a jour: $Date$
* par : $Author$
*/
-public class ResultStorage implements SimulationResultListener, SimulationResultGetter{ // ResultStorage
+public class ResultStorage implements SimulationResultListener,
+ SimulationResultGetter { // ResultStorage
/** to use log facility, just put in your code: log.info(\"...\"); */
static private Log log = LogFactory.getLog(ResultStorage.class);
protected SimulationStorage simulation = null;
-// transient protected HashMap<String, MatrixND> globalMatrix = new HashMap<String, MatrixND>();
+ // transient protected HashMap<String, MatrixND> globalMatrix = new HashMap<String, MatrixND>();
transient protected ReferenceMap cacheContext = new ReferenceMap(ReferenceMap.HARD, ReferenceMap.WEAK);
/** cache to maintains some result. key: String(date + ':' + name), value: matrix
@@ -103,10 +104,11 @@
this.simulation = simulation;
}
- protected void putInCache(Date date, String name, MatrixND mat, TopiaContext context) {
- String key = date + ":" + name;
+ protected void putInCache(TimeStep step, String name, MatrixND mat, TopiaContext context) {
+ String key = step + ":" + name;
putInCache(key, mat, context);
}
+
protected void putInCache(String name, MatrixND mat, TopiaContext context) {
if (mat != null) {
cache.put(name, mat);
@@ -114,18 +116,19 @@
}
}
- protected MatrixND getInCache(Date date, String name) {
- String key = date + ":" + name;
+ protected MatrixND getInCache(TimeStep step, String name) {
+ String key = step + ":" + name;
MatrixND result = getInCache(key);
return result;
}
+
protected MatrixND getInCache(String name) {
MatrixND result = null;
- TopiaContext context = (TopiaContext)cacheContext.get(name);
+ TopiaContext context = (TopiaContext) cacheContext.get(name);
if (context != null && !context.isClosed()) {
// on verifie que le context existe encore car on peut vouloir
// naviguer dans les semantics
- result = (MatrixND)cache.get(name);
+ result = (MatrixND) cache.get(name);
}
return result;
}
@@ -152,9 +155,8 @@
tx = simulation.getStorage().beginTransaction();
mustClose = true;
}
- @SuppressWarnings("unchecked")
- List<String> result = (List<String>)tx.find(
- "Select resultDate||':'||name from fr.ifremer.isisfish.entities.Result");
+
+ List<String> result = (List<String>) tx.find("Select resultDate||':'||name from fr.ifremer.isisfish.entities.Result");
if (mustClose) {
tx.closeContext();
}
@@ -164,19 +166,19 @@
log.warn("Can't get result available", eee);
}
}
-
}
return availableResult;
}
/**
- * Verifie si un resultat est disponible pour une date donnée
- * @param date
+ * Verifie si un resultat est disponible pour une date donnée.
+ *
+ * @param step
* @param name
* @return {@code true} if result is available
*/
- protected boolean isAvailableResult(Date date, String name) {
- String key = date.getDate() + ":" + name;
+ protected boolean isAvailableResult(TimeStep step, String name) {
+ String key = step.getStep() + ":" + name;
boolean result = getAvailableResult().contains(key);
return result;
}
@@ -184,11 +186,11 @@
/**
* Ajoute un resultat comme etant disponible pour une date donnée.
*
- * @param date
+ * @param step
* @param name
*/
- protected void addAvailableResult(Date date, String name) {
- String key = date.getDate() + ":" + name;
+ protected void addAvailableResult(TimeStep step, String name) {
+ String key = step.getStep() + ":" + name;
getAvailableResult().add(key);
}
@@ -207,12 +209,13 @@
* @param name result name
* @return {@code true} if result is enabled
*/
- public boolean isEnabled(String name){
+ public boolean isEnabled(String name) {
name = name.trim();
if (enabledResult == null) {
enabledResult = new HashSet<String>();
- Collection<String> resultEnabled = simulation.getParameter().getResultEnabled();
+ Collection<String> resultEnabled = simulation.getParameter()
+ .getResultEnabled();
enabledResult.addAll(resultEnabled);
// test on export
@@ -227,14 +230,16 @@
}
} catch (IsisFishException eee) {
if (log.isWarnEnabled()) {
- log.warn(_("isisfish.error.instanciate.export", exportName), eee);
+ log.warn(_("isisfish.error.instanciate.export",
+ exportName), eee);
}
}
}
}
// test on sensitivity export
- List<SensitivityExport> sensitivityExports = simulation.getParameter().getSensitivityExport();
+ List<SensitivityExport> sensitivityExports = simulation
+ .getParameter().getSensitivityExport();
if (sensitivityExports != null) {
for (SensitivityExport sensitivityExport : sensitivityExports) {
for (String resultName : sensitivityExport.getNecessaryResult()) {
@@ -268,43 +273,43 @@
return result;
}
- public void addResult(Date date, MatrixND mat) throws IsisFishException{
- addResult(false, date, mat.getName(), mat);
+ public void addResult(TimeStep step, MatrixND mat) throws IsisFishException {
+ addResult(false, step, mat.getName(), mat);
}
- public void addResult(Date date, Population pop, MatrixND mat) throws IsisFishException{
- addResult(false, date, mat.getName(), pop, mat);
+ public void addResult(TimeStep step, Population pop, MatrixND mat) throws IsisFishException {
+ addResult(false, step, mat.getName(), pop, mat);
}
- public void addResult(boolean force, Date date, MatrixND mat) throws IsisFishException{
- addResult(force, date, mat.getName(), mat);
+ public void addResult(boolean force, TimeStep step, MatrixND mat) throws IsisFishException {
+ addResult(force, step, mat.getName(), mat);
}
- public void addResult(boolean force, Date date, Population pop, MatrixND mat) throws IsisFishException{
- addResult(force, date, mat.getName(), pop, mat);
+ public void addResult(boolean force, TimeStep step, Population pop, MatrixND mat) throws IsisFishException {
+ addResult(force, step, mat.getName(), pop, mat);
}
- public void addResult(Date date, String name, Population pop, MatrixND mat) throws IsisFishException{
- addResult(false, date, name, pop, mat);
+ public void addResult(TimeStep step, String name, Population pop, MatrixND mat) throws IsisFishException {
+ addResult(false, step, name, pop, mat);
}
- public void addResult(Date date, String name, MatrixND mat) throws IsisFishException{
- addResult(false, date, name, mat);
+ public void addResult(TimeStep step, String name, MatrixND mat) throws IsisFishException {
+ addResult(false, step, name, mat);
}
- public void addResult(boolean force, Date date, String name, Population pop, MatrixND mat) throws IsisFishException{
+ public void addResult(boolean force, TimeStep step, String name, Population pop, MatrixND mat) throws IsisFishException {
if (force || isEnabled(name)) {
- doAddResult(date, name + " " + pop, mat);
+ doAddResult(step, name + " " + pop, mat);
}
}
- public void addResult(boolean force, Date date, String name, MatrixND mat) throws IsisFishException{
+ public void addResult(boolean force, TimeStep step, String name, MatrixND mat) throws IsisFishException {
if (force || isEnabled(name)) {
- doAddResult(date, name, mat);
+ doAddResult(step, name, mat);
}
}
- protected void doAddResult(Date date, String name, MatrixND mat) throws IsisFishException{
+ protected void doAddResult(TimeStep step, String name, MatrixND mat) throws IsisFishException {
try {
TopiaContext tx = null;
boolean mustClose = false;
@@ -317,22 +322,25 @@
tx = simulation.getStorage().beginTransaction();
mustClose = true;
}
- doAddResult(date, name, mat, tx);
+ doAddResult(step, name, mat, tx);
if (mustClose) {
tx.commitTransaction();
tx.closeContext();
}
} catch (TopiaException eee) {
- log.warn("Can't add result '" + name + "' at date " + date , eee);
+ log.warn("Can't add result '" + name + "' at step " + step, eee);
}
}
- protected void doAddResult(Date date, String name, MatrixND mat, TopiaContext tx) throws IsisFishException{
+ protected void doAddResult(TimeStep step, String name, MatrixND mat,
+ TopiaContext tx) throws IsisFishException {
// si la matrice n'a pas de semantique on refuse
- for (int i=0; i<mat.getDimCount(); i++) {
+ for (int i = 0; i < mat.getDimCount(); i++) {
// la semantique n'est pas bonne des qu'il y a un null dedans
if (mat.getSemantic(i).contains(null)) {
- throw new SimulationException("Erreur le résultat que vous souhaitez enregistrer n'a pas d'information convenable pour la dimension: " + i + " " + mat.getDimensionName(i) );
+ throw new SimulationException(
+ "Erreur le résultat que vous souhaitez enregistrer n'a pas d'information convenable pour la dimension: "
+ + i + " " + mat.getDimensionName(i));
}
}
@@ -341,19 +349,19 @@
try {
ResultDAO resultPS = IsisFishDAOHelper.getResultDAO(tx);
Result result = resultPS.create();
- result.setResultDate(date);
+ result.setResultStep(step);
result.setName(name);
result.setMatrix(newMat);
resultPS.update(result);
- addAvailableResult(date, name);
- putInCache(date, name, newMat, tx);
+ addAvailableResult(step, name);
+ putInCache(step, name, newMat, tx);
} catch (TopiaException eee) {
- log.warn("Can't add result '" + name + "' at date " + date , eee);
+ log.warn("Can't add result '" + name + "' at step " + step, eee);
}
}
- public void addActiveRule(Date date, Rule rule) throws IsisFishException {
+ public void addActiveRule(TimeStep step, Rule rule) throws IsisFishException {
try {
TopiaContext tx = null;
boolean mustClose = false;
@@ -368,7 +376,7 @@
}
ActiveRuleDAO ps = IsisFishDAOHelper.getActiveRuleDAO(tx);
ActiveRule result = ps.create();
- result.setActiveRuleDate(date);
+ result.setActiveRuleStep(step);
result.setName(RuleStorage.getName(rule));
result.setParam(RuleStorage.getParamAsString(rule));
ps.update(result);
@@ -403,9 +411,8 @@
}
ResultDAO resultPS = IsisFishDAOHelper.getResultDAO(tx);
-
- result = (List<String>)resultPS.getContext().find(
- "Select distinct name from fr.ifremer.isisfish.entities.Result order by name");
+ result = (List<String>) resultPS.getContext()
+ .find("Select distinct name from fr.ifremer.isisfish.entities.Result order by name");
if (mustClose) {
tx.closeContext();
}
@@ -422,20 +429,20 @@
/**
* Retourne la matrice stocke pour un pas de temps
- * @param date le pas de temps que l'on souhaite
+ * @param step le pas de temps que l'on souhaite
* @param pop la population pour lequelle on souhaite le resultat
* @param name le nom des resultats dont on veut la matrice
* @return La matrice demandée ou null si aucune matrice ne correspond a
* la demande.
*/
- public MatrixND getMatrix(Date date, Population pop, String name) {
+ public MatrixND getMatrix(TimeStep step, Population pop, String name) {
String newName = name + " " + pop;
- return getMatrix(date, newName);
+ return getMatrix(step, newName);
}
- public MatrixND getMatrix(Date date, String name) {
- MatrixND mat = getInCache(date, name);
- if (mat == null && isAvailableResult(date, name)) {
+ public MatrixND getMatrix(TimeStep step, String name) {
+ MatrixND mat = getInCache(step, name);
+ if (mat == null && isAvailableResult(step, name)) {
try {
TopiaContext tx = null;
boolean mustClose = false;
@@ -448,7 +455,7 @@
tx = simulation.getStorage().beginTransaction();
mustClose = true;
}
- mat = getMatrix(date, name, tx);
+ mat = getMatrix(step, name, tx);
if (mustClose) {
// FIXME transaction never closed
// quand peut on fermer la transaction ?
@@ -459,7 +466,8 @@
}
} catch (Exception eee) {
if (log.isWarnEnabled()) {
- log.warn("Can't return matrix '" + name + "' for date " + date, eee);
+ log.warn("Can't return matrix '" + name + "' for step "
+ + step, eee);
}
}
}
@@ -469,25 +477,28 @@
/**
* Retourne la matrice stocke pour un pas de temps.
*
- * @param date le pas de temps que l'on souhaite
+ * @param step le pas de temps que l'on souhaite
* @param name le nom des resultats dont on veut la matrice
* @param tx TopiaContext a utiliser pour recuperer les resultats et donc les semantiques
* @return La matrice demandée ou {@code null} si aucune matrice ne correspond a
* la demande.
*/
- public MatrixND getMatrix(Date date, String name, TopiaContext tx) {
- MatrixND mat = getInCache(date, name);
- if (mat == null && isAvailableResult(date, name)) {
+ public MatrixND getMatrix(TimeStep step, String name, TopiaContext tx) {
+ MatrixND mat = getInCache(step, name);
+ if (mat == null && isAvailableResult(step, name)) {
try {
ResultDAO resultPS = IsisFishDAOHelper.getResultDAO(tx);
- Result result = resultPS.findByProperties("resultDate", date, "name", name);
+ Result result = resultPS.findByProperties(
+ Result.PROPERTY_RESULT_STEP, step,
+ Result.PROPERTY_NAME, name);
if (result != null) {
mat = result.getMatrix();
- putInCache(date, name, mat, tx);
+ putInCache(step, name, mat, tx);
}
} catch (Exception eee) {
if (log.isWarnEnabled()) {
- log.warn("Can't return matrix '" + name + "' for date " + date, eee);
+ log.warn("Can't return matrix '" + name + "' for step "
+ + step, eee);
}
}
}
@@ -548,7 +559,7 @@
log.debug("Get result: " + name);
MatrixND resultMat = getInCache(name);
- if(resultMat != null){
+ if (resultMat != null) {
return resultMat;
}
@@ -571,71 +582,70 @@
// Creation des listes pour chaque dimension
// creation de la liste de date
- Date lastDate = getLastDate();
- List<Date> dates = new ArrayList<Date>();
- Date date = new Date(0);
- dates.add(date);
- while (date.before(lastDate)) {
- date = date.next();
- dates.add(date);
+ TimeStep lastStep = getLastStep();
+ List<TimeStep> steps = new ArrayList<TimeStep>();
+ TimeStep step = new TimeStep(0);
+ steps.add(step);
+ while (step.before(lastStep)) {
+ step = step.next();
+ steps.add(step);
}
if (log.isTraceEnabled()) {
- log.trace("List des dates: "+ dates);
+ log.trace("Steps list : " + steps);
}
// recuperation des dimensions des matrices
- MatrixND mat = (MatrixND)results.get(0).getMatrix();
+ MatrixND mat = (MatrixND) results.get(0).getMatrix();
// recuperation des noms des dimensions
- String [] dimNames = new String[1 + mat.getDimCount()];
+ String[] dimNames = new String[1 + mat.getDimCount()];
dimNames[0] = _("isisfish.common.date");
- for (int i=1; i<dimNames.length; i++) {
- dimNames[i] = mat.getDimensionName(i-1);
+ for (int i = 1; i < dimNames.length; i++) {
+ dimNames[i] = mat.getDimensionName(i - 1);
}
-
// creation de la semantique pour la matrice resultat. +1 pour les dates
List[] sem = new List[1 + mat.getDimCount()];
- sem[0] = dates;
+ sem[0] = steps;
- for (int i=1; i<sem.length; i++) {
+ for (int i = 1; i < sem.length; i++) {
sem[i] = new HashList();
}
- for (Result result: results) {
+ for (Result result : results) {
MatrixND mattmp = result.getMatrix();
if (log.isTraceEnabled()) {
- log.trace("Ajout de la semantics: "+ Arrays.asList(mattmp.getSemantics()));
+ log.trace("Ajout de la semantics: "
+ + Arrays.asList(mattmp.getSemantics()));
}
- for (int s=0; s<mattmp.getDimCount(); s++) {
- sem[s+1].addAll(mattmp.getSemantic(s));
+ for (int s = 0; s < mattmp.getDimCount(); s++) {
+ sem[s + 1].addAll(mattmp.getSemantic(s));
}
}
if (log.isTraceEnabled()) {
- log.trace("La semantique final est: "+ Arrays.asList(sem));
+ log.trace("La semantique final est: " + Arrays.asList(sem));
}
// creation de la matrice resultat
resultMat = MatrixFactory.getInstance().create(name, sem, dimNames);
// recuperation du resultat pour chaque date de la simulation, de Date(0) à lastDate
- for(Result result: results){
- Date d = result.getResultDate();
+ for (Result result : results) {
+ TimeStep d = result.getResultStep();
mat = result.getMatrix();
// on met ce resultat dans la matrice result si besoin
- if(mat != null){
+ if (mat != null) {
// on recupere dans la matrice resultat l'endroit on il faut
// mettre la matrice
MatrixND submat = resultMat.getSubMatrix(0, d, 1);
// on met les valeur de mat dans la sous matrice extraite
- for(MatrixIterator mi=mat.iterator(); mi.next();){
+ for (MatrixIterator mi = mat.iterator(); mi.next();) {
submat.setValue(
- ArrayUtil.concat(new Object[]{d},
- mi.getSemanticsCoordinates()),
- mi.getValue());
+ ArrayUtil.concat(new Object[] { d },
+ mi.getSemanticsCoordinates()), mi.getValue());
}
}
}
@@ -649,38 +659,40 @@
*
* @return last simulation date
*/
- public Date getLastDate() {
- int monthNumber = simulation.getParameter().getNumberOfYear() * Month.NUMBER_OF_MONTH;
- Date result = new Date(monthNumber - 1); // -1 because date begin at 0
+ public TimeStep getLastStep() {
+ int monthNumber = simulation.getParameter().getNumberOfYear()
+ * Month.NUMBER_OF_MONTH;
+ TimeStep result = new TimeStep(monthNumber - 1); // -1 because date begin at 0
return result;
}
/*
- * @see fr.ifremer.isisfish.simulator.SimulationResultListener#addResult(fr.ifremer.isisfish.simulator.SimulationContext, fr.ifremer.isisfish.types.Date, java.lang.String, org.nuiton.math.matrix.MatrixND)
+ * @see fr.ifremer.isisfish.simulator.SimulationResultListener#addResult(fr.ifremer.isisfish.simulator.SimulationContext, fr.ifremer.isisfish.types.TimeStep, java.lang.String, org.nuiton.math.matrix.MatrixND)
*/
@Override
- public void addResult(SimulationContext context, Date date, String name, MatrixND mat) throws IsisFishException {
+ public void addResult(SimulationContext context, TimeStep step, String name,
+ MatrixND mat) throws IsisFishException {
try {
- doAddResult(date, name, mat, context.getDbResult());
+ doAddResult(step, name, mat, context.getDbResult());
} catch (TopiaException eee) {
- log.warn(_("Can't add result '%1$s' at date %2$s", name, date) , eee);
+ log.warn(_("Can't add result '%1$s' at date %2$s", name, step), eee);
}
- }
+ }
/*
- * @see fr.ifremer.isisfish.simulator.SimulationResultGetter#getMatrix(fr.ifremer.isisfish.simulator.SimulationContext, fr.ifremer.isisfish.types.Date, java.lang.String)
+ * @see fr.ifremer.isisfish.simulator.SimulationResultGetter#getMatrix(fr.ifremer.isisfish.simulator.SimulationContext, fr.ifremer.isisfish.types.TimeStep, java.lang.String)
*/
@Override
- public MatrixND getMatrix(SimulationContext context, Date date, String name) {
+ public MatrixND getMatrix(SimulationContext context, TimeStep step, String name) {
MatrixND result = null;
try {
- result = getMatrix(date, name, context.getDbResult());
+ result = getMatrix(step, name, context.getDbResult());
} catch (TopiaException eee) {
if (log.isWarnEnabled()) {
log.warn(_("Can't get result: %1$s", name), eee);
}
}
- return result;
+ return result;
}
/*
@@ -696,7 +708,7 @@
log.warn(_("Can't get result: %1$s", name), eee);
}
}
- return result;
+ return result;
}
/*
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/migration/MigrationV33V40.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/migration/MigrationV33V40.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/datastore/migration/MigrationV33V40.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -65,5 +65,8 @@
queries.add("alter table POPULATION drop column MATURITYGROUP;");
queries.add("alter table POPULATION add column MATURITYOGIVEEQUATION VARCHAR(255);");
queries.add("alter table POPULATION add column REPRODUCTIONRATEEQUATION VARCHAR(255);");
+
+ queries.add("alter table Result ALTER COLUMN resultdate RENAME TO resultstep;");
+ queries.add("alter table ActiveRule ALTER COLUMN activeruledate RENAME TO activerulestep;");
}
}
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/entities/SetOfVesselsImpl.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/entities/SetOfVesselsImpl.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/entities/SetOfVesselsImpl.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -84,20 +84,19 @@
/**
* Evaluate {@link SetOfVesselsAbstract#technicalEfficiencyEquation} with
- * {@link Date} and {@link Metier}.
+ * {@link Gear} and {@link Metier}.
*
* By default return {@code 1} if equation can't be evaluated.
*/
@Override
- public double getTechnicalEfficiency(Date date, Metier metier) {
+ public double getTechnicalEfficiency(Metier metier) {
double result = 1;
try {
Equation eq = getTechnicalEfficiencyEquation();
if (eq != null) {
Gear gear = metier.getGear();
- result = eq.evaluate("date", date, "metier", metier, "gear",
- gear);
+ result = eq.evaluate("metier", metier, "gear", gear);
}
} catch (Exception eee) {
if (log.isWarnEnabled()) {
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/rule/AbstractRule.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/rule/AbstractRule.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/rule/AbstractRule.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2006 - 2010 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin
+ * Copyright (C) 2006 - 2011 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/rule/Rule.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/rule/Rule.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/rule/Rule.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -27,7 +27,7 @@
import fr.ifremer.isisfish.entities.Metier;
import fr.ifremer.isisfish.simulator.SimulationContext;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* Interface d'une regle. setValue et getValue permet de stocker des
@@ -40,7 +40,7 @@
* <li> un nombre (int, long, float, double, ...)
* <li> un boolean
* <li> une chaine String
- * <li> un objet Date ({@link fr.ifremer.isisfish.types.Date})
+ * <li> un objet Date ({@link fr.ifremer.isisfish.types.TimeStep})
* <li> un objet Month ({@link fr.ifremer.isisfish.types.Month})
* <li> Le type d'une entité (@see fr.ifremer.isisfish.entities)
*
@@ -85,16 +85,16 @@
* La condition qui doit etre vrai pour faire les actions.
*
* Si la confition return vrai alors les methodes
- * {@link #preAction(SimulationContext, Date, Metier)} et
- * {@link #postAction(SimulationContext, Date, Metier)} seront appelée.
+ * {@link #preAction(SimulationContext, TimeStep, Metier)} et
+ * {@link #postAction(SimulationContext, TimeStep, Metier)} seront appelée.
*
* @param context la simulation pour lequel on utilise cette regle
- * @param date la date courante
+ * @param step le pas de temps courant
* @param metier le metier
* @return vrai si on souhaite que les actions soit faites
* @throws Exception s'il y a une erreur, met fin a la simulation
*/
- public boolean condition(SimulationContext context, Date date, Metier metier)
+ public boolean condition(SimulationContext context, TimeStep step, Metier metier)
throws Exception;
/**
@@ -102,11 +102,11 @@
* de temps de la simulation.
*
* @param context la simulation pour lequel on utilise cette regle
- * @param date la date courant
+ * @param step le pas de temps courant
* @param metier le metier
* @throws Exception s'il y a une erreur, met fin a la simulation
*/
- public void preAction(SimulationContext context, Date date, Metier metier)
+ public void preAction(SimulationContext context, TimeStep step, Metier metier)
throws Exception;
/**
@@ -114,11 +114,11 @@
* de temps de la simulation.
*
* @param context la simulation pour lequel on utilise cette regle
- * @param date la date courante
+ * @param step le pas de temps courant
* @param metier le metier
* @throws Exception s'il y a une erreur, met fin a la simulation
*/
- public void postAction(SimulationContext context, Date date, Metier metier)
+ public void postAction(SimulationContext context, TimeStep step, Metier metier)
throws Exception;
/**
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/MetierMonitor.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/MetierMonitor.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/MetierMonitor.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2006 - 2010 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin
+ * Copyright (C) 2006 - 2011 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -50,7 +50,7 @@
import fr.ifremer.isisfish.entities.SetOfVessels;
import fr.ifremer.isisfish.entities.Strategy;
import fr.ifremer.isisfish.entities.StrategyMonthInfo;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.types.Month;
/**
@@ -74,7 +74,7 @@
protected Set<Metier> forbiddenMetier = new HashSet<Metier>();
protected Set<MultiKey> forbiddenMetierMonth = new HashSet<MultiKey>();
- protected Map<Date, MatrixND> noActivity = new HashMap<Date, MatrixND>();
+ protected Map<TimeStep, MatrixND> noActivity = new HashMap<TimeStep, MatrixND>();
/**
* clear all data
@@ -140,12 +140,12 @@
/**
* @return Returns the nonActivity.
*/
- public MatrixND getNoActivity(Date date) {
- return this.noActivity.get(date);
+ public MatrixND getNoActivity(TimeStep step) {
+ return this.noActivity.get(step);
}
- public MatrixND getOrCreateNoActivity(Date date, String name, List<Strategy> strategies, List<Metier> metiers) {
- MatrixND result = getNoActivity(date);
+ public MatrixND getOrCreateNoActivity(TimeStep step, String name, List<Strategy> strategies, List<Metier> metiers) {
+ MatrixND result = getNoActivity(step);
if (result == null){
if (strategies.size() == 0) {
strategies = new ArrayList<Strategy>();
@@ -161,7 +161,7 @@
name,
new List[] {strategies, metiers},
new String[] {n_("isisfish.metierMonitor.strategies"), n_("isisfish.metierMonitor.metiers")});
- setNoActivity(date, result);
+ setNoActivity(step, result);
}
return result;
}
@@ -169,8 +169,8 @@
/**
* @param nonActivity The nonActivity to set.
*/
- public void setNoActivity(Date date, MatrixND nonActivity) {
- this.noActivity.put(date, nonActivity);
+ public void setNoActivity(TimeStep step, MatrixND nonActivity) {
+ this.noActivity.put(step, nonActivity);
}
//////////////////////////////////////////////////////////////////////////
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/PopulationMonitor.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/PopulationMonitor.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/PopulationMonitor.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -41,7 +41,7 @@
import fr.ifremer.isisfish.entities.PopulationSeasonInfo;
import fr.ifremer.isisfish.entities.Species;
import fr.ifremer.isisfish.entities.Zone;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.types.Month;
import java.util.Collections;
@@ -71,9 +71,9 @@
/** current number of fish by Pop */
protected Map<Population, MatrixND> Ns = new HashMap<Population, MatrixND>();
/** reproduction key: <date, pop> value:<MatrixND> */
- protected Map<Population, Map<Date, MatrixND>> reproductions = new HashMap<Population, Map<Date, MatrixND>>();
+ protected Map<Population, Map<TimeStep, MatrixND>> reproductions = new HashMap<Population, Map<TimeStep, MatrixND>>();
/** discard key: <date, pop> value:<MatrixND> */
- protected Map<Population, Map<Date, MatrixND>> discards = new HashMap<Population, Map<Date, MatrixND>>();
+ protected Map<Population, Map<TimeStep, MatrixND>> discards = new HashMap<Population, Map<TimeStep, MatrixND>>();
/** catch per population, only last catch is remaining */
protected Map<Population, MatrixND> catchs = new HashMap<Population, MatrixND>();
/** catch per population, only last catch is remaining */
@@ -96,8 +96,8 @@
this.pops = Collections
.unmodifiableList(new ArrayList<Population>(pops));
for (Population pop : this.pops) {
- reproductions.put(pop, new HashMap<Date, MatrixND>());
- discards.put(pop, new HashMap<Date, MatrixND>());
+ reproductions.put(pop, new HashMap<TimeStep, MatrixND>());
+ discards.put(pop, new HashMap<TimeStep, MatrixND>());
}
}
@@ -173,23 +173,23 @@
/**
* Return reproduction.
*
- * @param date date
+ * @param step step
* @param pop population
* @return the reproduction
*/
- public MatrixND getReproduction(Date date, Population pop) {
- return this.reproductions.get(pop).get(date);
+ public MatrixND getReproduction(TimeStep step, Population pop) {
+ return this.reproductions.get(pop).get(step);
}
/**
* Set new reproduction.
*
- * @param date date
+ * @param step step
* @param pop population
* @param repro reproduction to set
*/
- public void setReproduction(Date date, Population pop, MatrixND repro) {
- reproductions.get(pop).put(date, repro);
+ public void setReproduction(TimeStep step, Population pop, MatrixND repro) {
+ reproductions.get(pop).put(step, repro);
}
/**
@@ -226,11 +226,11 @@
* Une autre facon de faire est de supprimer les repro == 0 car normalement
* toute la repro doit etre utilisé au bout d'un certain temps
*
- * @param date
+ * @param step
* @param pop
* @return population recruitment
*/
- public MatrixND getRecruitment(Date date, Population pop) {
+ public MatrixND getRecruitment(TimeStep step, Population pop) {
MatrixND matEtalement = pop.getRecruitmentDistribution();
int etalement = matEtalement.getDim(0);
@@ -242,9 +242,9 @@
// pour chaque
for (int e = 0; e < etalement; e++) {
// recuperation de la reproduction stucture en zone repro
- Date d = new Date(date.getDate() - e
+ TimeStep t = new TimeStep(step.getStep() - e
- pop.getMonthGapBetweenReproRecrutement());
- MatrixND repro = (MatrixND) reproductions.get(pop).get(d);
+ MatrixND repro = (MatrixND) reproductions.get(pop).get(t);
if (repro != null) { // si une repro existe pour le mois
@@ -290,20 +290,20 @@
MatrixND N = pop.N2DToN1D(result);
// on applique les migrations et le changement d'age sur le resultat
// on suppose que la reproduction est toujours dans une seul saison
- Date dateRepro = new Date(date.getDate()
+ TimeStep stepRepro = new TimeStep(step.getStep()
- pop.getMonthGapBetweenReproRecrutement());
// recherche les saisons des differents mois entre les deux dates
List<PopulationSeasonInfo> infos = pop.getPopulationSeasonInfo();
List<PopulationSeasonInfo> usedSeasons = new ArrayList<PopulationSeasonInfo>();
- while (date.after(dateRepro)) {
- dateRepro = dateRepro.next();
- Month month = dateRepro.getMonth();
+ while (step.after(stepRepro)) {
+ stepRepro = stepRepro.next();
+ Month month = stepRepro.getMonth();
for (PopulationSeasonInfo info : infos) {
if (month.equals(info.getFirstMonth())) {
usedSeasons.add(info);
- dateRepro = new Date(dateRepro.getDate()
+ stepRepro = new TimeStep(stepRepro.getStep()
+ info.getMonths().size() - 1); // -1 because, for have next()
break;
}
@@ -390,12 +390,12 @@
/**
* Get discard.
*
- * @param date date to get discard
+ * @param step step to get discard
* @param pop population to get discard
* @return le discard
*/
- public MatrixND getDiscard(Date date, Population pop) {
- MatrixND result = discards.get(pop).get(date);
+ public MatrixND getDiscard(TimeStep step, Population pop) {
+ MatrixND result = discards.get(pop).get(step);
return result;
}
@@ -404,17 +404,17 @@
*
* Force discard at date for population.
*
- * @param date date to set discard
+ * @param step step to set discard
* @param pop population to set discard
* @param discard le discard
*/
- public void setDiscard(Date date, Population pop, MatrixND discard) {
- Map<Date, MatrixND> oneDiscard = discards.get(pop);
+ public void setDiscard(TimeStep step, Population pop, MatrixND discard) {
+ Map<TimeStep, MatrixND> oneDiscard = discards.get(pop);
synchronized (oneDiscard) {
// meme si discards.get(pop) != null
// replace toujours le précédent
MatrixND tmp = discard.copy();
- discards.get(pop).put(date, tmp);
+ discards.get(pop).put(step, tmp);
}
}
@@ -422,17 +422,17 @@
* FIXME: discards n'est jamais vider, on le conserve pour toutes les annees
* il serait bon de faire un peu le menage de temps en temps.
*
- * @param date
+ * @param step
* @param pop
* @param discard
*/
- public void addDiscard(Date date, Population pop, MatrixND discard) {
- Map<Date, MatrixND> oneDiscard = discards.get(pop);
+ public void addDiscard(TimeStep step, Population pop, MatrixND discard) {
+ Map<TimeStep, MatrixND> oneDiscard = discards.get(pop);
synchronized (oneDiscard) {
- MatrixND tmp = oneDiscard.get(date);
+ MatrixND tmp = oneDiscard.get(step);
if (tmp == null) {
tmp = discard.copy();
- discards.get(pop).put(date, tmp);
+ discards.get(pop).put(step, tmp);
} else {
tmp.add(discard);
}
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/ResultManager.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/ResultManager.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/ResultManager.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -42,7 +42,7 @@
import fr.ifremer.isisfish.entities.Population;
import fr.ifremer.isisfish.export.Export;
import fr.ifremer.isisfish.rule.Rule;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* Used to store and retrieve result during simulation. This class manage
@@ -155,48 +155,48 @@
boolean result = enabledResult.contains(name);
return result;
}
- public void addActiveRule(Date date, Rule rule) throws IsisFishException {
+ public void addActiveRule(TimeStep step, Rule rule) throws IsisFishException {
log.warn("addActiveRule not implemented");
// FIXME: addActiveRule not implemented
}
- public void addResult(Date date, MatrixND mat) throws IsisFishException{
- addResult(false, date, mat.getName(), mat);
+ public void addResult(TimeStep step, MatrixND mat) throws IsisFishException{
+ addResult(false, step, mat.getName(), mat);
}
- public void addResult(Date date, Population pop, MatrixND mat) throws IsisFishException{
- addResult(false, date, mat.getName(), pop, mat);
+ public void addResult(TimeStep step, Population pop, MatrixND mat) throws IsisFishException{
+ addResult(false, step, mat.getName(), pop, mat);
}
- public void addResult(boolean force, Date date, MatrixND mat) throws IsisFishException{
- addResult(force, date, mat.getName(), mat);
+ public void addResult(boolean force, TimeStep step, MatrixND mat) throws IsisFishException{
+ addResult(force, step, mat.getName(), mat);
}
- public void addResult(boolean force, Date date, Population pop, MatrixND mat) throws IsisFishException{
- addResult(force, date, mat.getName(), pop, mat);
+ public void addResult(boolean force, TimeStep step, Population pop, MatrixND mat) throws IsisFishException{
+ addResult(force, step, mat.getName(), pop, mat);
}
- public void addResult(Date date, String name, Population pop, MatrixND mat) throws IsisFishException{
- addResult(false, date, name, pop, mat);
+ public void addResult(TimeStep step, String name, Population pop, MatrixND mat) throws IsisFishException{
+ addResult(false, step, name, pop, mat);
}
- public void addResult(Date date, String name, MatrixND mat) throws IsisFishException{
- addResult(false, date, name, mat);
+ public void addResult(TimeStep step, String name, MatrixND mat) throws IsisFishException{
+ addResult(false, step, name, mat);
}
- public void addResult(boolean force, Date date, String name, Population pop, MatrixND mat) throws IsisFishException{
+ public void addResult(boolean force, TimeStep step, String name, Population pop, MatrixND mat) throws IsisFishException{
// don't call generic addResult, because pop name is added
if (force || isEnabled(name)) {
for (SimulationResultListener l : listeners) {
- l.addResult(context, date, name + " " + pop, mat);
+ l.addResult(context, step, name + " " + pop, mat);
}
}
}
- public void addResult(boolean force, Date date, String name, MatrixND mat) throws IsisFishException{
+ public void addResult(boolean force, TimeStep step, String name, MatrixND mat) throws IsisFishException{
if (force || isEnabled(name)) {
for (SimulationResultListener l : listeners) {
- l.addResult(context, date, name, mat);
+ l.addResult(context, step, name, mat);
}
}
}
@@ -209,15 +209,15 @@
* @return La matrice demandée ou null si aucune matrice ne correspond a
* la demande.
*/
- public MatrixND getMatrix(Date date, Population pop, String name){
+ public MatrixND getMatrix(TimeStep step, Population pop, String name){
name += " " + pop;
- return getMatrix(date, name);
+ return getMatrix(step, name);
}
- public MatrixND getMatrix(Date date, String name){
+ public MatrixND getMatrix(TimeStep step, String name){
MatrixND result = null;
if (getter != null) {
- result = getter.getMatrix(context, date, name);
+ result = getter.getMatrix(context, step, name);
}
return result;
}
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/RuleMonitor.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/RuleMonitor.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/RuleMonitor.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2006 - 2010 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin
+ * Copyright (C) 2006 - 2011 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -29,7 +29,7 @@
import fr.ifremer.isisfish.entities.Metier;
import fr.ifremer.isisfish.rule.Rule;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* This class keep trace of rule evalution condition for all step and all metier.
@@ -46,13 +46,13 @@
protected MultiKeyMap evalutionCondition = new MultiKeyMap();
- public boolean getEvalutionCondition(Date date, Rule rule, Metier metier) {
- return (Boolean) this.evalutionCondition.get(date, rule, metier);
+ public boolean getEvalutionCondition(TimeStep step, Rule rule, Metier metier) {
+ return (Boolean) this.evalutionCondition.get(step, rule, metier);
}
- public void setEvaluationCondition(Date date, Rule rule, Metier metier,
+ public void setEvaluationCondition(TimeStep step, Rule rule, Metier metier,
boolean evalutionCondition) {
- this.evalutionCondition.put(date, rule, metier, evalutionCondition);
+ this.evalutionCondition.put(step, rule, metier, evalutionCondition);
}
}
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationControl.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationControl.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationControl.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -34,7 +34,7 @@
import org.apache.commons.logging.LogFactory;
import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* Permit to communicate with user interface from simulation thread.
@@ -60,7 +60,7 @@
protected boolean started = false;
protected boolean running = true;
protected boolean stop = false;
- protected Date date;
+ protected TimeStep step;
protected long progressMax = 0;
protected long progress = 0;
protected String text = "";
@@ -105,7 +105,7 @@
started = false;
running = true;
stop = false;
- date = null;
+ step = null;
progressMax = 0;
progress = 0;
}
@@ -281,22 +281,22 @@
*
* @return donne la date utiliser par la simulation
*/
- public Date getDate() {
- return date;
+ public TimeStep getTimeStep() {
+ return step;
}
/**
* Modifie la date de la simulation.
*
- * @param d la nouvelle date
+ * @param t la nouvelle etape
*/
- public void setDate(Date d) {
+ public void setTimeStep(TimeStep t) {
int oldValue = 0;
- if (this.date != null) {
- oldValue = this.date.getDate();
+ if (this.step != null) {
+ oldValue = this.step.getStep();
}
- this.date = d;
- listeners.firePropertyChange("date", oldValue, this.date.getDate());
+ this.step = t;
+ listeners.firePropertyChange("date", oldValue, this.step.getStep());
}
/**
@@ -309,8 +309,8 @@
result.setProperty("started", String.valueOf(started));
result.setProperty("running", String.valueOf(running));
result.setProperty("stop", String.valueOf(stop));
- if (date != null) {
- result.setProperty("date", String.valueOf(date.getDate()));
+ if (step != null) {
+ result.setProperty("date", String.valueOf(step.getStep()));
}
result.setProperty("progressMax", String.valueOf(progressMax));
result.setProperty("progress", String.valueOf(progress));
@@ -350,10 +350,10 @@
.getProperty("stop"));
setStopSimulationRequest(stop);
}
- if (props.containsKey("date")) {
- Date date = new Date(Integer
- .parseInt(props.getProperty("date")));
- setDate(date);
+ if (props.containsKey("step")) {
+ TimeStep step = new TimeStep(Integer
+ .parseInt(props.getProperty("step")));
+ setTimeStep(step);
}
if (props.containsKey("progressMax")) {
long progressMax = Long.parseLong(props
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationResultGetter.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationResultGetter.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationResultGetter.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2007 - 2010 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin
+ * Copyright (C) 2007 - 2011 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -27,9 +27,8 @@
import org.nuiton.math.matrix.MatrixND;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
-
/**
* Some SimulationResultListener can implement this interface to show that can
* be used to retrieve result
@@ -39,16 +38,18 @@
public interface SimulationResultGetter {
/**
- * Retourne la matrice stocke pour un pas de temps
- * @param date le pas de temps que l'on souhaite
+ * Retourne la matrice stocke pour un pas de temps.
+ *
+ * @param step le pas de temps que l'on souhaite
* @param name le nom des resultats dont on veut la matrice
* @return La matrice demandée ou null si aucune matrice ne correspond a
* la demande.
*/
- public MatrixND getMatrix(SimulationContext context, Date date, String name);
+ public MatrixND getMatrix(SimulationContext context, TimeStep step, String name);
/**
* Retourne une matrice contenant tous les pas de temps.
+ *
* @param name le nom des resultats dont on veut une matrice globale.
*/
public MatrixND getMatrix(SimulationContext context, String name);
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationResultListener.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationResultListener.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationResultListener.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2007 - 2010 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin
+ * Copyright (C) 2007 - 2011 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -28,7 +28,7 @@
import org.nuiton.math.matrix.MatrixND;
import fr.ifremer.isisfish.IsisFishException;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* SimulationResultListener.java
@@ -42,10 +42,10 @@
* by : $Author$
*/
public interface SimulationResultListener extends SimulationListener {
-
+
public void addResult(SimulationContext context,
- Date date, String name, MatrixND mat) throws IsisFishException;
-
+ TimeStep step, String name, MatrixND mat) throws IsisFishException;
+
}
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationResultXML.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationResultXML.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationResultXML.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2007 - 2010 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin
+ * Copyright (C) 2007 - 2011 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -39,7 +39,7 @@
import fr.ifremer.isisfish.IsisFishException;
import fr.ifremer.isisfish.datastore.SimulationStorage;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
@@ -139,15 +139,15 @@
}
/* (non-Javadoc)
- * @see fr.ifremer.isisfish.simulator.SimulationResultListener#addResult(fr.ifremer.isisfish.simulator.SimulationContext, fr.ifremer.isisfish.types.Date, java.lang.String, org.nuiton.math.matrix.MatrixND)
+ * @see fr.ifremer.isisfish.simulator.SimulationResultListener#addResult(fr.ifremer.isisfish.simulator.SimulationContext, fr.ifremer.isisfish.types.TimeStep, java.lang.String, org.nuiton.math.matrix.MatrixND)
*/
- public void addResult(SimulationContext context, Date date, String name,
+ public void addResult(SimulationContext context, TimeStep step, String name,
MatrixND mat) throws IsisFishException {
try {
- out.write(" <m name='" + name + "' date='" + date + "'>\n");
- for (int dim=0; dim<mat.getNbDim(); dim++) {
+ out.write(" <m name='" + name + "' step='" + step + "'>\n");
+ for (int dim=0; dim<mat.getDimCount(); dim++) {
out.write(" <dimension name='" + mat.getDimensionName(dim) + "' size='" + mat.getDim(dim) + "'>");
- for (Object sem : mat.getSemantics(dim)) {
+ for (Object sem : mat.getSemantic(dim)) {
out.write(" <label>" + sem + "</label>");
}
out.write(" </dimension>");
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/InProcessSimulatorLauncher.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/InProcessSimulatorLauncher.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/InProcessSimulatorLauncher.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -66,7 +66,7 @@
import fr.ifremer.isisfish.simulator.SimulationParameter;
import fr.ifremer.isisfish.simulator.SimulationPreScript;
import fr.ifremer.isisfish.simulator.Simulator;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.types.Month;
/**
@@ -129,7 +129,7 @@
// WARNING: make sure to not open Region before being in simulation context
// add missing control informations
SimulationParameter param = simulation.getParameter();
- control.setDate(new Date());
+ control.setTimeStep(new TimeStep());
control.setProgress(0);
control.setStarted(true);
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceTableModel.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceTableModel.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceTableModel.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -42,7 +42,7 @@
import fr.ifremer.isisfish.simulator.SimulationControl;
import fr.ifremer.isisfish.simulator.SimulationParameter;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* Model de table pour suivre l'evolution des differentes simulations en cours.
@@ -227,7 +227,7 @@
+ ", " + "control.getProgress() = " + control.getProgress()
+ ", " + "control.getProgressMax() = "
+ control.getProgressMax() + ", " + "control.getDate() = "
- + control.getDate());
+ + control.getTimeStep());
}
switch (columnIndex) {
@@ -266,9 +266,9 @@
pb.setValue((int) control.getProgress());
// progress can be used for other things
- Date date = control.getDate();
- if (date != null) {
- pb.setString(date.getMonth() + "/" + date.getYear());
+ TimeStep step = control.getTimeStep();
+ if (step != null) {
+ pb.setString(step.getMonth() + "/" + step.getYear());
}
else {
pb.setString("");
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/Date.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/Date.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/Date.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2005 - 2010 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin
+ * Copyright (C) 2005 - 2011 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
@@ -25,163 +25,30 @@
package fr.ifremer.isisfish.types;
-import java.io.Serializable;
-import static org.nuiton.i18n.I18n._;
-
/**
- * This object can't be modified. If this beaviour is modified pay attention
+ * This object can't be modified. If this behavior is modified pay attention
* if you used date as key in Map, in this case you will have error
*
* @author poussin
+ *
+ * @deprecated since 4.0.0.0, use {@link TimeStep} instead
*/
-public class Date implements Cloneable, Serializable, Comparable<Date> { // Date
+ at Deprecated
+public class Date extends TimeStep { // Date
- /** serialVersionUID. */
- private static final long serialVersionUID = 1L;
-
- protected int date = 0;
-
- public Date() {
- }
-
- public Date(int date) {
- this.date = date;
- }
-
- public int compareTo(Date d) {
- if (this.before(d))
- return -1;
- else if (this.after(d))
- return 1;
- else
- return 0;
- }
-
- public int getYear() {
- return date / 12;
- }
-
- public Month getMonth() {
- int tmp = date;
- while (tmp < 0) {
- tmp += 12;
- }
- Month result = Month.MONTH[tmp % 12];
- return result;
- }
-
- // public Date inc() {
- // date++;
- // return this;
- // }
-
- public int getDate() {
- return date;
- }
-
/**
- * Method next retourne une nouvelle date qui est la date suivante de la
- * date courante. la date courante n'est pas modifier.
*
- * @return Date
*/
- public Date next() {
- return new Date(this.date + 1);
+ public Date() {
+ super();
}
/**
- * Method preview retourne une nouvelle date qui est la date precedente de
- * la date courante la date courante n'est pas modifier.
- *
- * @return Date
+ * @param step
*/
- public Date previous() {
- return new Date(this.date - 1);
- }
+ public Date(int step) {
+ super(step);
+ }
- /**
- * Method next retourne une nouvelle date qui est le meme mois de l'annee
- * suivante de la date courante. la date courante n'est pas modifier.
- *
- * @return Date
- */
- public Date nextYear() {
- return new Date(this.date + 12);
- }
-
- /**
- * Method preview retourne une nouvelle date qui est le meme mois de l'annee
- * precedente de la date courante la date courante n'est pas modifier.
- *
- * @return Date
- */
- public Date previousYear() {
- return new Date(this.date - 12);
- }
-
-
- /**
- * compare 2 dates.
- *
- * @return retourne vrai si d est strictement superieur
- */
- public boolean before(Date d) {
- return this.date < d.date;
- }
-
- public boolean beforeOrEquals(Date d) {
- return this.date <= d.date;
- }
-
- /**
- * compare 2 dates.
- *
- * @return retourne vrai si d est strictement inferieur
- */
- public boolean after(Date d) {
- return this.date > d.date;
- }
-
- public boolean afterOrEquals(Date d) {
- return this.date >= d.date;
- }
-
- public boolean equals(Object o) {
- if (o instanceof Date)
- return date == ((Date) o).date;
- return false;
- }
-
- public int hashCode() {
- return date;
- }
-
- /**
- * @param date2
- * @return month array
- */
- public Month[] getMonthBetweenDate(Date date2) {
- if(date2.getDate() - getDate() <0) {
- return new Month[0];
- }
-
- Month[] result = new Month[date2.getDate() - getDate()];
- Month month = getMonth();
- for (int i=0; i<result.length; i++) {
- month = month.next();
- result[i] = month;
- }
- return result;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- String result = _("isisfish.date.toString", getMonth(), getYear());
- return result;
- }
-
} // Date
Added: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/TimeStep.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/TimeStep.java (rev 0)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/TimeStep.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -0,0 +1,192 @@
+/*
+ * #%L
+ * IsisFish
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2005 - 2011 Ifremer, Code Lutin, Cédric Pineau, Benjamin Poussin, Chatellier Eric
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+
+package fr.ifremer.isisfish.types;
+
+import java.io.Serializable;
+import static org.nuiton.i18n.I18n._;
+
+/**
+ * This object can't be modified. If this beaviour is modified pay attention
+ * if you used date as key in Map, in this case you will have error
+ *
+ * @author poussin
+ */
+public class TimeStep implements Cloneable, Serializable, Comparable<TimeStep> { // Date
+
+ /** serialVersionUID. */
+ private static final long serialVersionUID = 1L;
+
+ protected int step = 0;
+
+ public TimeStep() {
+ }
+
+ public TimeStep(int step) {
+ this.step = step;
+ }
+
+ public int compareTo(TimeStep t) {
+ if (this.before(t)) {
+ return -1;
+ } else if (this.after(t)) {
+ return 1;
+ } else {
+ return 0;
+ }
+ }
+
+ public int getYear() {
+ return step / 12;
+ }
+
+ public Month getMonth() {
+ int tmp = step;
+ while (tmp < 0) {
+ tmp += 12;
+ }
+ Month result = Month.MONTH[tmp % 12];
+ return result;
+ }
+
+ /**
+ * @deprecated since 4.0.0.0, use {@link #getStep()} instead
+ * @return date
+ */
+ @Deprecated
+ public int getDate() {
+ return step;
+ }
+
+ public int getStep() {
+ return step;
+ }
+
+ /**
+ * Method next retourne une nouvelle date qui est la date suivante de la
+ * date courante. la date courante n'est pas modifier.
+ *
+ * @return Date
+ */
+ public TimeStep next() {
+ return new TimeStep(this.step + 1);
+ }
+
+ /**
+ * Method preview retourne une nouvelle date qui est la date precedente de
+ * la date courante la date courante n'est pas modifier.
+ *
+ * @return Date
+ */
+ public TimeStep previous() {
+ return new TimeStep(this.step - 1);
+ }
+
+ /**
+ * Method next retourne une nouvelle date qui est le meme mois de l'annee
+ * suivante de la date courante. la date courante n'est pas modifier.
+ *
+ * @return Date
+ */
+ public TimeStep nextYear() {
+ return new TimeStep(this.step + 12);
+ }
+
+ /**
+ * Method preview retourne une nouvelle date qui est le meme mois de l'annee
+ * precedente de la date courante la date courante n'est pas modifier.
+ *
+ * @return Date
+ */
+ public TimeStep previousYear() {
+ return new TimeStep(this.step - 12);
+ }
+
+ /**
+ * compare 2 dates.
+ *
+ * @return retourne vrai si t est strictement superieur
+ */
+ public boolean before(TimeStep t) {
+ return this.step < t.step;
+ }
+
+ public boolean beforeOrEquals(TimeStep t) {
+ return this.step <= t.step;
+ }
+
+ /**
+ * compare 2 dates.
+ *
+ * @return retourne vrai si t est strictement inferieur
+ */
+ public boolean after(TimeStep t) {
+ return this.step > t.step;
+ }
+
+ public boolean afterOrEquals(TimeStep d) {
+ return this.step >= d.step;
+ }
+
+ public boolean equals(Object o) {
+ if (o instanceof TimeStep) {
+ return step == ((TimeStep) o).step;
+ }
+ return false;
+ }
+
+ public int hashCode() {
+ return step;
+ }
+
+ /**
+ * @param timeStep2
+ * @return month array
+ */
+ public Month[] getMonthBetweenDate(TimeStep timeStep2) {
+ if (timeStep2.getStep() - getStep() < 0) {
+ return new Month[0];
+ }
+
+ Month[] result = new Month[timeStep2.getStep() - getStep()];
+ Month month = getMonth();
+ for (int i = 0; i < result.length; i++) {
+ month = month.next();
+ result[i] = month;
+ }
+ return result;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ String result = _("isisfish.date.toString", getMonth(), getYear());
+ return result;
+ }
+
+} // Date
+
Property changes on: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/TimeStep.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Deleted: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/DateType.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/DateType.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/DateType.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -1,111 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2002 - 2010 Ifremer, 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-
-package fr.ifremer.isisfish.types.hibernate;
-
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Types;
-
-import org.hibernate.HibernateException;
-import org.hibernate.type.ImmutableType;
-
-import fr.ifremer.isisfish.types.Date;
-
-/**
- * DateType.java
- *
- * Created: 19 janv. 2006
- *
- * @author Arnaud Thimel <thimel at codelutin.com>
- * Copyright Code Lutin
- * @version $Revision$
- *
- * Mise a jour: $Date$
- * par : $Author$
- */
-public class DateType extends ImmutableType {
-
- /** */
- private static final long serialVersionUID = -5295147041590169149L;
-
- /* (non-Javadoc)
- * @see org.hibernate.type.NullableType#get(java.sql.ResultSet, java.lang.String)
- */
- @Override
- public Object get(ResultSet rs, String name) throws HibernateException,
- SQLException {
- return new Date(rs.getInt(name));
- }
-
- /* (non-Javadoc)
- * @see org.hibernate.type.NullableType#set(java.sql.PreparedStatement, java.lang.Object, int)
- */
- @Override
- public void set(PreparedStatement st, Object value, int index)
- throws HibernateException, SQLException {
- st.setInt(index, ((Date) value).getDate());
- }
-
- /* (non-Javadoc)
- * @see org.hibernate.type.NullableType#sqlType()
- */
- @Override
- public int sqlType() {
- return Types.INTEGER;
- }
-
- /* (non-Javadoc)
- * @see org.hibernate.type.NullableType#toString(java.lang.Object)
- */
- @Override
- public String toString(Object value) throws HibernateException {
- return ((Date)value).toString();
- }
-
- /* (non-Javadoc)
- * @see org.hibernate.type.NullableType#fromStringValue(java.lang.String)
- */
- @Override
- public Object fromStringValue(String xml) throws HibernateException {
- return new Date(Integer.parseInt(xml));
- }
-
- /* (non-Javadoc)
- * @see org.hibernate.type.Type#getReturnedClass()
- */
- public Class getReturnedClass() {
- return Date.class;
- }
-
- /* (non-Javadoc)
- * @see org.hibernate.type.Type#getName()
- */
- public String getName() {
- return DateType.class.getName();
- }
-
-}
Copied: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/TimeStepType.java (from rev 3392, isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/DateType.java)
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/TimeStepType.java (rev 0)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/types/hibernate/TimeStepType.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -0,0 +1,111 @@
+/*
+ * #%L
+ * IsisFish
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2002 - 2011 Ifremer, Code Lutin, Chatellier Eric
+ * %%
+ * 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+
+package fr.ifremer.isisfish.types.hibernate;
+
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+
+import org.hibernate.HibernateException;
+import org.hibernate.type.ImmutableType;
+
+import fr.ifremer.isisfish.types.TimeStep;
+
+/**
+ * DateType.java
+ *
+ * Created: 19 janv. 2006
+ *
+ * @author Arnaud Thimel <thimel at codelutin.com>
+ * Copyright Code Lutin
+ * @version $Revision$
+ *
+ * Mise a jour: $Date$
+ * par : $Author$
+ */
+public class TimeStepType extends ImmutableType {
+
+ /** serialVersionUID. */
+ private static final long serialVersionUID = -5295147041590169149L;
+
+ /*
+ * @see org.hibernate.type.NullableType#get(java.sql.ResultSet, java.lang.String)
+ */
+ @Override
+ public Object get(ResultSet rs, String name) throws HibernateException,
+ SQLException {
+ return new TimeStep(rs.getInt(name));
+ }
+
+ /*
+ * @see org.hibernate.type.NullableType#set(java.sql.PreparedStatement, java.lang.Object, int)
+ */
+ @Override
+ public void set(PreparedStatement st, Object value, int index)
+ throws HibernateException, SQLException {
+ st.setInt(index, ((TimeStep) value).getStep());
+ }
+
+ /*
+ * @see org.hibernate.type.NullableType#sqlType()
+ */
+ @Override
+ public int sqlType() {
+ return Types.INTEGER;
+ }
+
+ /*
+ * @see org.hibernate.type.NullableType#toString(java.lang.Object)
+ */
+ @Override
+ public String toString(Object value) throws HibernateException {
+ return ((TimeStep)value).toString();
+ }
+
+ /*
+ * @see org.hibernate.type.NullableType#fromStringValue(java.lang.String)
+ */
+ @Override
+ public Object fromStringValue(String xml) throws HibernateException {
+ return new TimeStep(Integer.parseInt(xml));
+ }
+
+ /*
+ * @see org.hibernate.type.Type#getReturnedClass()
+ */
+ public Class getReturnedClass() {
+ return TimeStep.class;
+ }
+
+ /*
+ * @see org.hibernate.type.Type#getName()
+ */
+ public String getName() {
+ return TimeStepType.class.getName();
+ }
+
+}
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/MatrixSummaryRenderer.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/MatrixSummaryRenderer.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/MatrixSummaryRenderer.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -40,7 +40,7 @@
import fr.ifremer.isisfish.datastore.ResultStorage;
import fr.ifremer.isisfish.datastore.SimulationStorage;
import fr.ifremer.isisfish.simulator.SimulationParameter;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* Simulation summary renderer.
@@ -88,13 +88,13 @@
// TODO EC20090717 ca marche plus ca
if (name.startsWith(ABONDANCE_STRING)){
- MatrixND mat1 = resultStorage.getMatrix(new Date(0), name, topiaContext);
+ MatrixND mat1 = resultStorage.getMatrix(new TimeStep(0), name, topiaContext);
mat1 = mat1.sumOverDim(0);
mat1 = mat1.sumOverDim(1);
mat1 = mat1.reduce();
resume.append(_("isisfish.result.begin.simulation")).append(mat1.getName()).append(": ").append(mat1.getValue(0)).append("\n");
- mat1 = resultStorage.getMatrix(resultStorage.getLastDate(), name, topiaContext);
+ mat1 = resultStorage.getMatrix(resultStorage.getLastStep(), name, topiaContext);
mat1 = mat1.sumOverDim(0);
mat1 = mat1.sumOverDim(1);
mat1 = mat1.reduce();
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/ResultMatrixFilter.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/ResultMatrixFilter.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/ResultMatrixFilter.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -32,7 +32,7 @@
import org.nuiton.math.matrix.viewer.MatrixFilter;
import fr.ifremer.isisfish.datastore.ResultStorage;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* Filtre qui ajoute les trou dans les données (valeur intermédiares absentes)
@@ -82,10 +82,10 @@
List<Object> newList = new ArrayList<Object>();
for (int index = 0 ; index < semList.size(); ++index) {
Object semObject = semList.get(index);
- if (semObject instanceof Date) {
- Date semDate = (Date)semObject;
- Date newDate = new Date(semDate.getDate() * sumStep);
- newList.add(newDate);
+ if (semObject instanceof TimeStep) {
+ TimeStep semStep = (TimeStep)semObject;
+ TimeStep newStep = new TimeStep(semStep.getStep() * sumStep);
+ newList.add(newStep);
}
else {
newList.add(semObject);
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/YearSumDimensionAction.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/YearSumDimensionAction.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/result/YearSumDimensionAction.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -28,7 +28,7 @@
import org.nuiton.math.matrix.viewer.MatrixDimensionAction;
import org.nuiton.util.Resource;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* Action de somme des elements par 12 (année) pour la dimension des pas de temps.
@@ -58,7 +58,7 @@
@Override
public Class<?> getDimensionType() {
- return Date.class;
+ return TimeStep.class;
}
@Override
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/widget/editor/ParameterTableCellEditor.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/widget/editor/ParameterTableCellEditor.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/ui/widget/editor/ParameterTableCellEditor.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -51,7 +51,7 @@
import org.nuiton.util.MonthEnum;
import fr.ifremer.isisfish.datastore.RegionStorage;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.types.Month;
import fr.ifremer.isisfish.util.ConverterUtil;
@@ -89,7 +89,7 @@
/** for a mounth. */
Mounth(Month.class),
/** for a simple date. */
- Date(Date.class),
+ TimeStep(TimeStep.class),
/** for a simple boolean. */
Double(double.class, Double.class),
/** for a simple boolean. */
@@ -181,10 +181,10 @@
c.setSelectedItem(value);
editor = c;
break;
- case Date:
- Date date = (Date) value;
+ case TimeStep:
+ TimeStep date = (TimeStep) value;
if (date == null) {
- date = new Date(0);
+ date = new TimeStep(0);
}
int month = date.getMonth().getMonthNumber();
int yea = date.getYear();
@@ -273,7 +273,7 @@
case Mounth:
result = getComboBoxIndex(editor) + "";
break;
- case Date:
+ case TimeStep:
result = ((DateComponent) editor).getSelectedValue() + "";
break;
case File:
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/ConverterUtil.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/ConverterUtil.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/ConverterUtil.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -32,7 +32,7 @@
import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.persistence.TopiaEntity;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.types.Month;
import fr.ifremer.isisfish.types.RangeOfValues;
import fr.ifremer.isisfish.types.TimeUnit;
@@ -56,7 +56,7 @@
// mise en place de converter de string vers des objet ...
cub.register(new TopiaEntityConverter(context), TopiaEntity.class);
- cub.register(new DateConverter(), Date.class);
+ cub.register(new TimeStepConverter(), TimeStep.class);
cub.register(new MonthConverter(), Month.class);
cub.register(new TimeUnitConverter(), TimeUnit.class);
cub.register(new RangeOfValuesConverter(), RangeOfValues.class);
Deleted: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/DateConverter.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/DateConverter.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/DateConverter.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -1,63 +0,0 @@
-/*
- * #%L
- * IsisFish
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2006 - 2010 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, see
- * <http://www.gnu.org/licenses/gpl-2.0.html>.
- * #L%
- */
-
-package fr.ifremer.isisfish.util;
-
-import org.apache.commons.beanutils.ConversionException;
-import org.apache.commons.beanutils.Converter;
-
-import fr.ifremer.isisfish.types.Date;
-
-
-/**
- * Classe utilise pour convertir une chaine en un objet Date.
- *
- * Utilisé pour la conversion et le stockage en propriete des parametres.
- *
- * @author poussin
- */
-public class DateConverter implements Converter {
-
- /* (non-Javadoc)
- * @see org.apache.commons.beanutils.Converter#convert(java.lang.Class, java.lang.Object)
- */
- public Object convert(Class type, Object value) {
- Object result;
- if (value instanceof Date) {
- result = value;
- } else if (value instanceof String) {
- int d = Integer.parseInt(value.toString());
- result = new Date(d);
- } else if (value == null) {
- result = new Date(0);
- } else {
- throw new ConversionException("Can't convert '" + value + "' to " + type.getName());
- }
- return result;
- }
-
-}
-
-
Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/StringConverter.java
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/StringConverter.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/StringConverter.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -30,7 +30,7 @@
import org.nuiton.math.matrix.MatrixND;
import org.nuiton.topia.persistence.TopiaEntity;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.types.Month;
import fr.ifremer.isisfish.types.TimeUnit;
@@ -59,8 +59,8 @@
if (o != null) {
if (o instanceof TopiaEntity) {
result = ((TopiaEntity) o).getTopiaId();
- } else if (o instanceof Date) {
- result = String.valueOf(((Date) o).getDate());
+ } else if (o instanceof TimeStep) {
+ result = String.valueOf(((TimeStep) o).getStep());
} else if (o instanceof Month) {
result = String.valueOf(((Month) o).getMonthNumber());
} else if (o instanceof TimeUnit) {
Copied: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/TimeStepConverter.java (from rev 3392, isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/DateConverter.java)
===================================================================
--- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/TimeStepConverter.java (rev 0)
+++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/util/TimeStepConverter.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -0,0 +1,63 @@
+/*
+ * #%L
+ * IsisFish
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2006 - 2010 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, see
+ * <http://www.gnu.org/licenses/gpl-2.0.html>.
+ * #L%
+ */
+
+package fr.ifremer.isisfish.util;
+
+import org.apache.commons.beanutils.ConversionException;
+import org.apache.commons.beanutils.Converter;
+
+import fr.ifremer.isisfish.types.TimeStep;
+
+
+/**
+ * Classe utilise pour convertir une chaine en un objet Date.
+ *
+ * Utilisé pour la conversion et le stockage en propriete des parametres.
+ *
+ * @author poussin
+ */
+public class TimeStepConverter implements Converter {
+
+ /* (non-Javadoc)
+ * @see org.apache.commons.beanutils.Converter#convert(java.lang.Class, java.lang.Object)
+ */
+ public Object convert(Class type, Object value) {
+ Object result;
+ if (value instanceof TimeStep) {
+ result = value;
+ } else if (value instanceof String) {
+ int d = Integer.parseInt(value.toString());
+ result = new TimeStep(d);
+ } else if (value == null) {
+ result = new TimeStep(0);
+ } else {
+ throw new ConversionException("Can't convert '" + value + "' to " + type.getName());
+ }
+ return result;
+ }
+
+}
+
+
Modified: isis-fish/trunk/src/main/xmi/isis-fish.zargo
===================================================================
(Binary files differ)
Modified: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/rule/RuleMock.java
===================================================================
--- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/rule/RuleMock.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/rule/RuleMock.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -27,7 +27,7 @@
import fr.ifremer.isisfish.entities.Metier;
import fr.ifremer.isisfish.simulator.SimulationContext;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* A basic rule implementation.
@@ -71,29 +71,29 @@
}
/*
- * @see fr.ifremer.isisfish.rule.Rule#condition(fr.ifremer.isisfish.simulator.SimulationContext, fr.ifremer.isisfish.types.Date, fr.ifremer.isisfish.entities.Metier)
+ * @see fr.ifremer.isisfish.rule.Rule#condition(fr.ifremer.isisfish.simulator.SimulationContext, fr.ifremer.isisfish.types.TimeStep, fr.ifremer.isisfish.entities.Metier)
*/
@Override
- public boolean condition(SimulationContext context, Date date, Metier metier)
+ public boolean condition(SimulationContext context, TimeStep step, Metier metier)
throws Exception {
return false;
}
/*
- * @see fr.ifremer.isisfish.rule.Rule#preAction(fr.ifremer.isisfish.simulator.SimulationContext, fr.ifremer.isisfish.types.Date, fr.ifremer.isisfish.entities.Metier)
+ * @see fr.ifremer.isisfish.rule.Rule#preAction(fr.ifremer.isisfish.simulator.SimulationContext, fr.ifremer.isisfish.types.TimeStep, fr.ifremer.isisfish.entities.Metier)
*/
@Override
- public void preAction(SimulationContext context, Date date, Metier metier)
+ public void preAction(SimulationContext context, TimeStep step, Metier metier)
throws Exception {
// TODO Auto-generated method stub
}
/*
- * @see fr.ifremer.isisfish.rule.Rule#postAction(fr.ifremer.isisfish.simulator.SimulationContext, fr.ifremer.isisfish.types.Date, fr.ifremer.isisfish.entities.Metier)
+ * @see fr.ifremer.isisfish.rule.Rule#postAction(fr.ifremer.isisfish.simulator.SimulationContext, fr.ifremer.isisfish.types.TimeStep, fr.ifremer.isisfish.entities.Metier)
*/
@Override
- public void postAction(SimulationContext context, Date date, Metier metier)
+ public void postAction(SimulationContext context, TimeStep step, Metier metier)
throws Exception {
}
Modified: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceIT.java
===================================================================
--- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceIT.java 2011-07-07 14:33:45 UTC (rev 3436)
+++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceIT.java 2011-07-08 11:26:05 UTC (rev 3437)
@@ -41,7 +41,7 @@
import fr.ifremer.isisfish.datastore.SimulationStorage;
import fr.ifremer.isisfish.entities.Result;
import fr.ifremer.isisfish.simulator.SimulationControl;
-import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.TimeStep;
/**
* Integration tests for {@link SimulationService}.
@@ -92,7 +92,7 @@
// lancement de la simulation
SimulationControl control = new SimulationControl(sim.getName());
- control.setDate(new Date());
+ control.setTimeStep(new TimeStep());
InProcessSimulatorLauncher launcher = new InProcessSimulatorLauncher();
sim = launcher.localSimulate(control, sim);
@@ -108,21 +108,21 @@
List<String> resultNames = resultRef.getResultName();
Assert.assertEquals(resultNames, result.getResultName());
- Date lastDate = resultRef.getLastDate();
+ TimeStep lastStep = resultRef.getLastStep();
if (log.isInfoEnabled()) {
log.info("Check result ...");
}
- for (Date date = new Date(0); date.beforeOrEquals(lastDate); date = date.next()) {
+ for (TimeStep step = new TimeStep(0); step.beforeOrEquals(lastStep); step = step.next()) {
for (String resultName : resultNames) {
if (log.isDebugEnabled()) {
- log.debug("Check result " + date + " " + resultName);
+ log.debug("Check result " + step + " " + resultName);
}
- Assert.assertEquals("Date " + date.getDate() + " result " + resultName,
- resultRef.getMatrix(date, resultName),
- result.getMatrix(date, resultName));
+ Assert.assertEquals("Date " + step.getStep() + " result " + resultName,
+ resultRef.getMatrix(step, resultName),
+ result.getMatrix(step, resultName));
resultChecked++;
}
1
0