Isis-fish-data-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
April 2009
- 2 participants
- 39 discussions
Author: jcouteau
Date: 2009-04-28 13:25:06 +0000 (Tue, 28 Apr 2009)
New Revision: 122
Modified:
trunk/scripts/SiMatrix.java
Log:
Adaptation aux scripts de St?\195?\169phanie
Modified: trunk/scripts/SiMatrix.java
===================================================================
--- trunk/scripts/SiMatrix.java 2009-04-28 13:19:55 UTC (rev 121)
+++ trunk/scripts/SiMatrix.java 2009-04-28 13:25:06 UTC (rev 122)
@@ -246,7 +246,7 @@
List<PopulationGroup> groups = pop.getPopulationGroup();
MatrixND result = matrixCatchPerStrategyMetPerZoneMet.copy();
- result.setName(ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_MET);
+ result.setName(ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET);
for (PopulationGroup group : groups) {
MatrixND sub = result.getSubMatrix(2, group, 1);
@@ -271,7 +271,7 @@
Set<Cell> cellPops = new HashSet(matrixCatchPerStrategyMetPerCell.getSemantics(4));
MatrixND result = MatrixFactory.getInstance().create(
- ResultName.MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_MET,
+ ResultName.MATRIX_CATCH_PER_STRATEGY_MET,
new List[]{strategies, metiers, groups, zones},
new String[]{n_("Strategies"), n_("Metiers"), n_("Groups"), n_("Zones")});
@@ -316,7 +316,7 @@
// on somme sur les cellules
MatrixND result = matrixCatchPerStrategyMetPerCell.sumOverDim(4);
result = result.reduceDims(4);
- result.setName(ResultName.MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_POP);
+ result.setName(ResultName.MATRIX_CATCH_PER_STRATEGY_MET);
return result;
}
@@ -326,7 +326,7 @@
List<PopulationGroup> groups = pop.getPopulationGroup();
MatrixND result = matrixCatchPerStrategyMetPerZonePop.copy();
- result.setName(ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ result.setName(ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET);
for (PopulationGroup group : groups) {
MatrixND sub = result.getSubMatrix(2, group, 1);
@@ -359,7 +359,7 @@
// on le passe en argument ce qui evite de le calculer 2 fois
// MatrixND matrixCatchRatePerStrategyMet = matrixCatchRatePerStrategyMet(pop, date);
MatrixND result = matrixCatchRatePerStrategyMet.copy();
- result.setName(ResultName.MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_POP);
+ result.setName(ResultName.MATRIX_CATCH_PER_STRATEGY_MET);
for(PopulationGroup group : groups) {
MatrixND sub = result.getSubMatrix(2, group, 1);
@@ -390,7 +390,7 @@
List<Zone> zones = pop.getPopulationZone();
MatrixND result = MatrixFactory.getInstance().create(
- ResultName.MATRIX_CATCH_RATE_PER_STRATEGY_MET_PER_ZONE_POP,
+ ResultName.MATRIX_CATCH_RATE_PER_STRATEGY_MET,
new List[]{strategies, metiers, groups, zones},
new String[]{n_("Strategies"), n_("Metiers"), n_("Groups"), n_("Zones")});
@@ -1624,7 +1624,7 @@
List<Zone> zones = N.getSemantics(1);
MatrixND result = MatrixFactory.getInstance().create(
- ResultName.MATRIX_BIOMASS_BEGIN_MONTH,
+ ResultName.MATRIX_BIOMASS,
new List[]{groups, zones},
new String[]{n_("Groups"), n_("Zones")});
@@ -1646,7 +1646,7 @@
List<Zone> zones = N.getSemantics(1);
MatrixND result = MatrixFactory.getInstance().create(
- ResultName.MATRIX_ABONDANCE_BEGIN_MONTH,
+ ResultName.MATRIX_ABUNDANCE,
new List[]{groups, zones},
new String[]{n_("Groups"), n_("Zones")});
@@ -1742,7 +1742,7 @@
List<PopulationGroup> groups = pop.getPopulationGroup();
MatrixND result = matrixDiscardPerStrategyMetPerZonePop.copy();
- result.setName(ResultName.MATRIX_DISCARDS_WEIGHT_PER_STR_MET_PER_ZONE_POP);
+ result.setName(ResultName.MATRIX_DISCARDS_WEIGHT_PER_STR_MET);
for(PopulationGroup group : groups){
MatrixND sub = result.getSubMatrix(2, group, 1);
1
0
28 Apr '09
Author: jcouteau
Date: 2009-04-28 13:19:55 +0000 (Tue, 28 Apr 2009)
New Revision: 121
Added:
trunk/rules/GraviteVPUE1LangEtGrossValueOtherSpeciesECOMOD.java
Modified:
trunk/exports/SensitivityCapturesWeightReferenceY7.java
trunk/exports/SensitivityCapturesWeightRelativeReferenceY10.java
trunk/exports/SensitivityCapturesWeightRelativeY4.java
trunk/exports/SensitivityCapturesWeightY1.java
trunk/rules/GraviteCPUE.java
trunk/rules/TACpoids.java
trunk/scripts/ResultName.java
Log:
Commit des scripts modifi?\195?\169s par St?\195?\169phanie
adaptation des scripts existants
Refactoring des scripts de st?\195?\169phanie (rajouts des @Doc sur les param?\195?\168tres, plus de system.out.println, organize imports et format du code)
Modified: trunk/exports/SensitivityCapturesWeightReferenceY7.java
===================================================================
--- trunk/exports/SensitivityCapturesWeightReferenceY7.java 2009-04-22 16:32:05 UTC (rev 120)
+++ trunk/exports/SensitivityCapturesWeightReferenceY7.java 2009-04-28 13:19:55 UTC (rev 121)
@@ -24,7 +24,7 @@
static private Log log = LogFactory
.getLog(SensitivityCapturesWeightReferenceY7.class);
- protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP };
+ protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET };
@Doc("Population")
public Population param_pop;
@@ -53,7 +53,7 @@
.getMatrix(
new Date(lastDate.getDate() - i),
pop,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET);
capturesWeight += matlastdate.sumAll();
//Get the reference captures Weight of each month of the last year
@@ -62,7 +62,7 @@
MatrixND matlastdatereference = referenceResultStorage
.getMatrix(
new Date(lastDate.getDate() - i),
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET
+ " " + pop, tx);
capturesWeightReference += matlastdatereference.sumAll();
tx.commitTransaction();
Modified: trunk/exports/SensitivityCapturesWeightRelativeReferenceY10.java
===================================================================
--- trunk/exports/SensitivityCapturesWeightRelativeReferenceY10.java 2009-04-22 16:32:05 UTC (rev 120)
+++ trunk/exports/SensitivityCapturesWeightRelativeReferenceY10.java 2009-04-28 13:19:55 UTC (rev 121)
@@ -25,7 +25,7 @@
static private Log log = LogFactory
.getLog(SensitivityCapturesWeightRelativeReferenceY10.class);
- protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP };
+ protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET };
@Doc("Population")
public Population param_pop;
@@ -56,7 +56,7 @@
.getMatrix(
new Date(lastDate.getDate() - i),
pop,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET);
capturesWeight += matlastdate.sumAll();
//Get the captures Weight of each month of the first year
@@ -64,7 +64,7 @@
.getMatrix(
new Date(i),
pop,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET);
capturesWeightfirst += matfirstdate.sumAll();
//Get the reference captures Weight of each month of the last year
@@ -75,7 +75,7 @@
MatrixND matlastdatereference = referenceResultStorage
.getMatrix(
new Date(lastDate.getDate() - i),
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET
+ " " + pop, tx);
capturesWeightreference += matlastdatereference.sumAll();
@@ -83,7 +83,7 @@
MatrixND matfirstdatereference = referenceResultStorage
.getMatrix(
new Date(i),
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET
+ " " + pop, tx);
capturesWeightfirstreference += matfirstdatereference
.sumAll();
Modified: trunk/exports/SensitivityCapturesWeightRelativeY4.java
===================================================================
--- trunk/exports/SensitivityCapturesWeightRelativeY4.java 2009-04-22 16:32:05 UTC (rev 120)
+++ trunk/exports/SensitivityCapturesWeightRelativeY4.java 2009-04-28 13:19:55 UTC (rev 121)
@@ -23,7 +23,7 @@
static private Log log = LogFactory
.getLog(SensitivityCapturesWeightRelativeY4.class);
- protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP };
+ protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET };
@Doc("Population")
public Population param_pop;
@@ -45,7 +45,7 @@
.getMatrix(
new Date(lastDate.getDate() - i),
pop,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET);
capturesWeight += matlastdate.sumAll();
//Get the captures Weight of each month of the first year
@@ -53,7 +53,7 @@
.getMatrix(
new Date(i),
pop,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET);
capturesWeightfirst += matfirstdate.sumAll();
}
Modified: trunk/exports/SensitivityCapturesWeightY1.java
===================================================================
--- trunk/exports/SensitivityCapturesWeightY1.java 2009-04-22 16:32:05 UTC (rev 120)
+++ trunk/exports/SensitivityCapturesWeightY1.java 2009-04-28 13:19:55 UTC (rev 121)
@@ -23,7 +23,7 @@
static private Log log = LogFactory
.getLog(SensitivityCapturesWeightY1.class);
- protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP };
+ protected String[] necessaryResult = { ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET };
@Doc("Population")
public Population param_pop;
@@ -44,7 +44,7 @@
.getMatrix(
new Date(lastDate.getDate() - i),
pop,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET);
capturesWeight += matlastdate.sumAll();
}
Modified: trunk/rules/GraviteCPUE.java
===================================================================
--- trunk/rules/GraviteCPUE.java 2009-04-22 16:32:05 UTC (rev 120)
+++ trunk/rules/GraviteCPUE.java 2009-04-28 13:19:55 UTC (rev 121)
@@ -57,7 +57,7 @@
// example:
// ResultName.MATRIX_BIOMASS,
// ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP,
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET,
ResultName.MATRIX_EFFORT_PER_STRATEGY_MET,
};
@@ -186,7 +186,7 @@
MatrixND temp = resultmanager.getMatrix(
date.previousYear(),
pop,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET);
// on somme sur les zones
temp=temp.sumOverDim(3);
// on somme sur les groupes
Added: trunk/rules/GraviteVPUE1LangEtGrossValueOtherSpeciesECOMOD.java
===================================================================
--- trunk/rules/GraviteVPUE1LangEtGrossValueOtherSpeciesECOMOD.java (rev 0)
+++ trunk/rules/GraviteVPUE1LangEtGrossValueOtherSpeciesECOMOD.java 2009-04-28 13:19:55 UTC (rev 121)
@@ -0,0 +1,542 @@
+package rules;
+
+import static org.codelutin.i18n.I18n._;
+import static org.codelutin.i18n.I18n.n_;
+
+import java.io.File;
+import java.io.FileReader;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.codelutin.math.matrix.MapFunction;
+import org.codelutin.math.matrix.MatrixFactory;
+import org.codelutin.math.matrix.MatrixND;
+import org.codelutin.util.FileUtil;
+
+import scripts.ResultName;
+import scripts.SiMatrix;
+import fr.ifremer.isisfish.datastore.ResultStorage;
+import fr.ifremer.isisfish.entities.EffortDescription;
+import fr.ifremer.isisfish.entities.Metier;
+import fr.ifremer.isisfish.entities.Population;
+import fr.ifremer.isisfish.entities.Strategy;
+import fr.ifremer.isisfish.entities.StrategyMonthInfo;
+import fr.ifremer.isisfish.rule.AbstractRule;
+import fr.ifremer.isisfish.simulator.SimulationContext;
+import fr.ifremer.isisfish.types.Date;
+import fr.ifremer.isisfish.types.Month;
+
+/**
+ * GraviteVPUE1Anchois.java
+ *
+ * Created: 26 aout 2008
+ *
+ * @author anonymous <anonymous(a)labs.libre-entreprise.org>
+ * @version $Revision: 1.2 $
+ *
+ * Last update: $Date: 2008-10-23 08:59:38 $ by : $Author: Stephanie $
+ */
+public class GraviteVPUE1LangEtGrossValueOtherSpeciesECOMOD extends
+ AbstractRule {
+ /** to use log facility, just put in your code: log.info("..."); */
+ static private Log log = LogFactory
+ .getLog(GraviteVPUE1LangEtGrossValueOtherSpeciesECOMOD.class);
+
+ public String param_nomfichier_coeffOthers0 = "Inputs_Langoustine/CoeffOthers_Intercept_Langoustine/CoeffOthersNephrops.csv";
+ public String param_nomfichier_coeffOthers1 = "Inputs_Langoustine/CoeffOthers_Intercept_Langoustine/CoeffOthersHake.csv";
+ public String param_nomfichier_coeffOthers2 = "Inputs_Langoustine/CoeffOthers_Intercept_Langoustine/CoeffOthersBenthic.csv";
+ public boolean param_gravite = false;
+ // doit �tre � vrai si gravite s'applique sinon la methode calcul uniquement les grossvalue otherspecies
+
+ static final protected String BETA_O = "BetaOthers";
+ static final protected String ALPHA_O = "AlphaOthers";
+
+ protected File CoeffOthers0;
+ protected File CoeffOthers1;
+ protected File CoeffOthers2;
+
+ protected MatrixND matrixCoeffOthers;
+
+ protected List<Metier> metiers;
+ // interdit de faire des set sur les strategies de la map, il faut recuperer les strategies de la date courante
+ protected Map<String, Strategy> mesStrategies;
+
+ /** stocke la somme des prop initiales [str x month] */
+ private MatrixND SommePropInitial = null;
+ /**
+ * stocke par strat*met, la derni�re attractivite pour chaque mois [str x
+ * met x month]
+ */
+
+ /** permet de stocker les CPUE nominales [str x met] */
+ private MatrixND valuePerUnitOfEffort = null;
+
+ public String[] necessaryResult = {
+ // put here all necessary result for this rule
+ // example:
+ // ResultName.MATRIX_BIOMASS,
+ // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET,
+ ResultName.MATRIX_GROSS_VALUE_OF_LANDINGS_PER_STRATEGY_MET,
+ //ResultName.MATRIX_EFFORT_PER_STRATEGY_MET,
+ ResultName.MATRIX_EFFORT_NOMINAL_PER_STRATEGY_MET, // garder la ,
+
+ };
+
+ public String[] getNecessaryResult() {
+ return this.necessaryResult;
+ }
+
+ /**
+ * Permet d'afficher a l'utilisateur une aide sur la regle.
+ *
+ * @return L'aide ou la description de la regle
+ */
+ public String getDescription() throws Exception {
+ return _("calcule les proportion par m�tier chaque mois en fonction de la VPUE du m�tier l'ann�e pr�c�dante et les gross Values otherSpecies");
+ /*"HYPOTHESES GRAVITE"
+ " attention cette r�gle doit toujours �tre mise avant les mesures de gestion"+
+ " si pour un metier Effort (m�tier annee-1,mois) = 0 et propinitiale (m�tier, mois) !=0 (ie m�tier potentiellement pratiqu�), alors "+
+ on remet propInitiale pour tous les m�tiers (premiere vue complete pour tous les metiers de la strategie - graviteVPUE1-, une alternative
+ pourrait �tre de chercher lapremiere ann�e avant ann�e -1 pour laquelle le m�tier, ayant une propInitiale non nulle , aurait une VPUE (metier,mois) non nulle
+ et recuperer la propStr (metier,mois) pour cette ann�e et on l'affecte ann�e courante - mois, les autres m�tiers se partageant la proportion d'effort restante
+ en fonction de leur VPUE - graviteVPUE2-, une alternative pourrait etre de chercher la premiere ann�e avant ann�e -1 pour laquelle tous les m�tiers,
+ ayant une propInitiale non nulle, auraient eu une propStr non nulle, (surement difficile � trouver) - - graviteVPUE3- d'autres hypoth�ses pourraient etre envisag�es)
+ "*/
+ /*Calcul des gross Value Other Species en fonction de l'effort par strategie et par m�tier � date
+ Avant ann�e 1 (premiere ann�e d'appliaction de Gravit�) - il faut deja faire les calculs des grossValues des autres esp�ces
+ A partir de l'ann�e 1 : Gravit� s'applique, il faut donc attendre de connaitre l'allocation de l'effort � date (dependant des gross values species et otherspecies � date - 1)
+ pour pouvoir calculer les grossValueOtherSpecies � date
+
+ */
+ }
+
+ /**
+ * function used to initialise MatrixND to NaN double
+ */
+ private MapFunction nanFunction = new MapFunction() {
+ public double apply(double value) {
+ return Double.NaN;
+ }
+ };
+
+ /**
+ * Appel� au d�marrage de la simulation, cette m�thode permet d'initialiser
+ * des valeurs
+ *
+ * @param simulation
+ * La simulation pour lequel on utilise cette regle
+ */
+ public void init(SimulationContext context) throws Exception {
+ Date date = new Date(0);
+
+ List<Strategy> strs = SiMatrix.getSiMatrix(context).getStrategies(date);
+ List<Metier> metiers = SiMatrix.getSiMatrix(context).getMetiers(date);
+ List<Month> months = Arrays.asList(Month.MONTH);
+
+ SommePropInitial = MatrixFactory.getInstance().create(
+ "SommePropInitial", new List[] { strs, months },
+ new String[] { "Strategies", "Months" });
+ SommePropInitial.map(nanFunction);
+
+ valuePerUnitOfEffort = MatrixFactory.getInstance().create(
+ "ValuePerUnitOfEffort", new List[] { strs, metiers },
+ new String[] { "Strategies", "Metiers" });
+ valuePerUnitOfEffort.map(nanFunction);
+
+ for (Strategy str : strs) {
+ List<Metier> strMetiers = SiMatrix.getSiMatrix(context).getMetiers(
+ str, date);
+ List<StrategyMonthInfo> infos = str.getStrategyMonthInfo();
+ for (StrategyMonthInfo info : infos) {
+ double somme = 0;
+ for (Metier strMetier : strMetiers) {
+ somme += info.getProportionMetier(strMetier);
+ }
+ // FIXME soit on somme pour toutes les str le meme metier; donc pas de notion de str.getName dans la cle
+ // soit pour une str on somme tous ces metiers (mais ce doit etre 1; donc pas de notion de metier.getName dans la cle
+ SommePropInitial.setValue(str, info.getMonth(), somme);
+ }
+ }
+
+ // load coefficients of relation others file in a matrix
+ if (param_nomfichier_coeffOthers0 == null
+ || "".equals(param_nomfichier_coeffOthers0)) {
+ CoeffOthers0 = FileUtil.getFile(".*.csv",
+ "fichier 0 csv s�parateur ';'");
+ CoeffOthers1 = FileUtil.getFile(".*.csv",
+ "fichier 1 csv s�parateur ';'");
+ CoeffOthers2 = FileUtil.getFile(".*.csv",
+ "fichier 2 csv s�parateur ';'");
+ } else {
+ CoeffOthers0 = new File(param_nomfichier_coeffOthers0);
+ CoeffOthers1 = new File(param_nomfichier_coeffOthers1);
+ CoeffOthers2 = new File(param_nomfichier_coeffOthers2);
+ }
+
+ // reccuperation des metiers et strategies
+ SiMatrix siMatrix = SiMatrix.getSiMatrix(context);
+ List<String> coeffs = Arrays.asList(new String[] { ALPHA_O, BETA_O });
+
+ // creation de mes strategies qui ne contient pas les espagnols
+ //mesStrategies = new HashMap<String, Strategy>();
+ //for(Strategy str : strs) {
+ // mesStrategies.put(str.getName(), str);
+ //}
+
+ MatrixND matCoeffOthers0 = MatrixFactory.getInstance().create(
+ "matCoeffOthers0", new List[] { metiers, coeffs },
+ new String[] { "Metiers", "Coeff" });
+ MatrixND matCoeffOthers1 = MatrixFactory.getInstance().create(
+ "matCoeffOthers1", new List[] { metiers, coeffs },
+ new String[] { "Metiers", "Coeff" });
+ MatrixND matCoeffOthers2 = MatrixFactory.getInstance().create(
+ "matCoeffOthers2", new List[] { metiers, coeffs },
+ new String[] { "Metiers", "Coeff" });
+
+ matCoeffOthers0.importCSV(new FileReader(CoeffOthers0), new int[] { 0,
+ 0 });
+ matCoeffOthers1.importCSV(new FileReader(CoeffOthers1), new int[] { 0,
+ 0 });
+ matCoeffOthers2.importCSV(new FileReader(CoeffOthers2), new int[] { 0,
+ 0 });
+
+ // captures non simulees
+ matrixCoeffOthers = MatrixFactory.getInstance().create(
+ "matrixCoeffOthers", new List[] { strs, metiers, coeffs },
+ new String[] { "Strategies", "Metiers", "Coeff" });
+
+ MatrixND matImport = MatrixFactory.getInstance().create(
+ new int[] { 14, 2 });
+ ;
+ for (Strategy str : strs) {
+ log.info("str =" + str.getName());
+ for (Metier met : metiers) {
+ for (String coeff : coeffs) {
+ if ("NephropsLargeLesSables".equals(str.getName())
+ || "NephropsLargeGuilvinec".equals(str.getName())
+ || "NephropsIntermediateLesSables".equals(str
+ .getName())
+ || "NephropsIntermediateGuilvinec".equals(str
+ .getName())) {
+ matImport = matCoeffOthers0;
+ } else if ("HakeLargeLesSables".equals(str.getName())
+ || "HakeLargeGuilvinec".equals(str.getName())
+ || "HakeIntermediateLesSables"
+ .equals(str.getName())
+ || "HakeIntermediateGuilvinec"
+ .equals(str.getName())) {
+ matImport = matCoeffOthers1;
+ } else if ("BenthicLargeLesSables".equals(str.getName())
+ || "BenthicLargeGuilvinec".equals(str.getName())
+ || "BenthicIntermediateLesSables".equals(str
+ .getName())
+ || "BenthicIntermediateGuilvinec".equals(str
+ .getName())) {
+ matImport = matCoeffOthers2;
+ }
+ matrixCoeffOthers.setValue(str, met, coeff, matImport
+ .getValue(met, coeff));
+ }// fin de for coeff
+ }// fin de for met
+ }// fin de for strategy
+ log.info("matrixCoeffOthers : " + matrixCoeffOthers);
+
+ }
+
+ /**
+ * La condition qui doit etre vrai pour faire les actions
+ *
+ * @param simulation
+ * La simulation pour lequel on utilise cette regle
+ * @return vrai si on souhaite que les actions soit faites
+ */
+ public boolean condition(SimulationContext context, Date date, Metier metier)
+ throws Exception {
+
+ return true; // on y passe a chaque pas de temps
+ }
+
+ /**
+ * Si la condition est vrai alors cette action est execut�e avant le pas de
+ * temps de la simulation.
+ *
+ * @param simulation
+ * La simulation pour lequel on utilise cette regle
+ */
+ // Booleen permettant que ne boucler que sur un seul metier dans la preaction :
+ boolean first = true;
+
+ public void preAction(SimulationContext context, Date date, Metier metier)
+ throws Exception {
+ if (log.isDebugEnabled()) {
+ log.debug("first = " + first + "date:" + date);
+ }
+ log.info("first = " + first + " ,on passe dans la preaction ?");
+ if (first) { // on passe dans preaction pour la premiere fois
+
+ log.info("Oui, preaction : ");
+
+ List<Strategy> strs = SiMatrix.getSiMatrix(context).getStrategies(
+ date);
+ List<Population> populations = SiMatrix.getSiMatrix(context)
+ .getPopulations(date);
+ List<Metier> metiers = SiMatrix.getSiMatrix(context).getMetiers(
+ date);
+ ResultStorage resultmanager = context.getSimulationStorage()
+ .getResultStorage();
+ //on commence par creer une instance de resultats de matrice GrossValuesOtherSpecies
+ MatrixND GrossValueOtherSpeciesPerStrMet = MatrixFactory
+ .getInstance()
+ .create(
+ ResultName.MATRIX_GROSS_VALUE_OF_LANDINGS_OTHER_SPECIES_PER_STRATEGY_MET,
+ new List[] { strs, metiers },
+ new String[] { n_("Strategies"), n_("Metiers") });
+ log.info("GrossValueOtherSpeciesPerStrMet initialisee "
+ + GrossValueOtherSpeciesPerStrMet);
+
+ // si ann�e>=1 alors on fait le calcul des gravit� puis on met � jour les gross value otherspecies
+ if ((date.getYear() > 0) & (param_gravite == true)) {
+ ////////Initialisation des matrices qui resultent de la simulation////////////////////////////////////////////////////////////
+ log.info("calcul de Gravite");
+ //Calcul de l effort nominal par strategy met
+ MatrixND EffortNominalPerStrMet = null;
+ EffortNominalPerStrMet = resultmanager.getMatrix(date
+ .previousYear(),
+ ResultName.MATRIX_EFFORT_NOMINAL_PER_STRATEGY_MET);
+ log.info("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(),
+ ResultName.MATRIX_GROSS_VALUE_OF_LANDINGS_PER_STRATEGY_MET)
+ .copy();
+ log.info("GrossValuePerStrMet calculee " + GrossValuePerStrMet);
+
+ //ajouter pour tous les m�tiers les valeurs li�es qux autres esp�ces calcul�es par modele lineaire
+ // Boucle sur les strategies de mes strategies
+ //List <Strategy> mStr = strs;
+ for (Strategy strIndex : strs) {
+ // interdit de faire des set sur les strategies de la semantique de la matrice, il faut recuperer les strategies de la date courante
+ Strategy str = (Strategy) context.getDB().findByTopiaId(
+ strIndex.getTopiaId());
+
+ StrategyMonthInfo smi = str.getStrategyMonthInfo(date
+ .getMonth());
+ Collection<EffortDescription> strMet = str
+ .getSetOfVessels().getPossibleMetiers();
+ //2) calcul les valeurs non simulees du mois l ann�e pr�c�dante
+ for (EffortDescription effort : strMet) {
+ Metier met = effort.getPossibleMetiers();
+ log.info("Boucle metier 1, metier possible: "
+ + met.getName());
+ double eff = EffortNominalPerStrMet.getValue(str, met);
+ log.info("effort str" + str.getName() + met.getName()
+ + " : " + eff);
+
+ //GrossValueAutres par strat�gie
+ // Hypothese 1 = pas de distinction entre les m�tiers n'agira donc pas sur la gravit�)
+ // Hypothese 2 = a distinguer selon les m�tiers - agira sur la gravit�
+ // l'hypothese est le resultat des coef dans la matrice en entr�e si tous identiques quelque soit le metier dans la strat�gie alors H1
+ // sinon H2
+ double valMetOther = matrixCoeffOthers.getValue(str,
+ met, ALPHA_O)
+ + matrixCoeffOthers.getValue(str, met, BETA_O)
+ * eff;
+ if (valMetOther < 0) {
+ valMetOther = 0;
+ }
+ double valMet = valMetOther
+ + GrossValuePerStrMet.getValue(str, met);
+ //log.info("valOtherMetAnchois :"+matrixCoeffOthers.getValue(str,met)*eff);
+ //log.info("GrossValuePerStrMet avant : "+GrossValuePerStrMet.getValue(str,met));
+ GrossValuePerStrMet.setValue(str, met, valMet);
+ log.info("valOtherMetLangoustine : " + valMet);
+ log.info("GrossValuePerStrMet apres : "
+ + GrossValuePerStrMet.getValue(str, met));
+
+ }
+ }
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////
+ valuePerUnitOfEffort.map(nanFunction); //r�initialisation avant calcul pour date
+
+ for (Strategy str : strs) {
+ log.info("INFO: Boucle creation valuePerUnitEffort : "
+ + str.getName());
+ //log.info("Boucle creation catchperuniteffort : "+ str.getName());
+ StrategyMonthInfo smi = str.getStrategyMonthInfo(date
+ .getMonth());
+ Collection<EffortDescription> strMet = str
+ .getSetOfVessels().getPossibleMetiers();
+ //SiMatrix.getSiMatrix(context).getMetiers(str, date);
+
+ // boucle pour tester s'il existe un metier pour lequel effort(metier)=0 et PropInitiale(metier)=0 (Condition)
+ boolean testCondition = false;
+ double somme = 0;//initialisation de la somme des VPUE des metiers de la strategie
+ for (EffortDescription ed : strMet) {
+ Metier strMetier = ed.getPossibleMetiers();
+ log.info("Pour str=" + str.getName() + " et metier="
+ + strMetier.getName());
+ double effort = EffortNominalPerStrMet.getValue(str,
+ strMetier);
+ // on teste effort pour le calcul des VPUE
+ // si effort != 0 , valeur/effort
+ //sinon (effort =0) , deux cas de figure :
+ // 1. soit propInitiale =0 pour ce m�tier et dans ce cas VPUE =0 et ca ne doit pas impacter le calcul de la gravite pour les autres metiers de str
+ // 2. soit propInitiale! =0 et dans ce cas, on mettra PropInitiale pour tous les metiers de str
+ if (effort > 0) {// a pech� au mois, annee-1
+ //on recupere la capture tot
+ double value = GrossValuePerStrMet.getValue(str,
+ strMetier);
+ log.info("DEBUG: value : " + value);
+ log.info("DEBUG: effort : " + effort);
+ double vpue = value / effort;
+ valuePerUnitOfEffort.setValue(str, strMetier, 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);
+ 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
+ log
+ .info("n'a pas peche au mois, annee -1, mais avait une prop d'effort non nul a l'annee=0");
+ }
+ }
+ log.info("testCondition pour str" + str.getName() + ":"
+ + testCondition);
+ // � partir des VPUE stockees dans valuePerUnitOfEffort, on calcule la gravit�
+ double newProp = 0;
+ log
+ .info("� partir des VPUE stockees dans valuePerUnitOfEffort, on calcule la gravit�");
+ if (!testCondition) {
+ double SommeVPUEstrat = somme;
+ log.info("SommeVPUEstrat=" + SommeVPUEstrat);
+ for (EffortDescription ed : strMet) {
+ Metier strMetier = ed.getPossibleMetiers();
+ log.info("PropStrInitiale(metier="
+ + strMetier.getName() + ")"
+ + smi.getProportionMetier(strMetier));
+ log
+ .info("SommePropInitial.getValue(str, date.getMonth()="
+ + SommePropInitial.getValue(str,
+ date.getMonth()));
+ log
+ .info("valuePerUnitOfEffort.getValue(str, strMetier)"
+ + valuePerUnitOfEffort.getValue(
+ str, strMetier));
+ if (SommeVPUEstrat == 0) {
+ newProp = 0;
+ } else {
+ newProp = SommePropInitial.getValue(str, date
+ .getMonth())
+ * valuePerUnitOfEffort.getValue(str,
+ strMetier) / SommeVPUEstrat;
+ }
+ log.info("newProp(metier=" + strMetier.getName()
+ + ")" + newProp);
+ smi.setProportionMetier(strMetier, newProp);
+ log.info("PropStrNouvelle(metier="
+ + strMetier.getName() + ")"
+ + smi.getProportionMetier(strMetier));
+ // annee>= 1 calcul des gross Value otherSpecies avec les nouvelles valeurs d'effort calcul�es par gravite
+ //avec la nouvelle proportion on en d�duit la gross Value of Species de date pour ce str-met
+ double valMetOtherSpecies = matrixCoeffOthers
+ .getValue(str, strMetier, ALPHA_O)
+ + matrixCoeffOthers.getValue(str,
+ strMetier, BETA_O) * newProp;
+ //tester si valMetOtherSpecies <= alors mettre � 0
+ if (valMetOtherSpecies < 0) {
+ valMetOtherSpecies = 0;
+ }
+ GrossValueOtherSpeciesPerStrMet.setValue(str,
+ strMetier, valMetOtherSpecies);
+ log.info("valOtherMetLangoustine : "
+ + valMetOtherSpecies);
+ log.info("GrossValuePerStrMet apres : "
+ + GrossValueOtherSpeciesPerStrMet.getValue(
+ str, strMetier));
+ }
+ }
+ // else ie on met propInitiale dans PropStr(str,annee,mois)
+ // rien n'a faire car au debut de chaque pas de temps, PropStr est par d�faut initialis� � la valeur de la base de donn�es (val initiales)
+ }//fin de boucle sur strategy
+ // r�sultats grossvalue otherspecies mis dans le resultManager
+ resultmanager
+ .addResult(
+ date,
+ ResultName.MATRIX_GROSS_VALUE_OF_LANDINGS_OTHER_SPECIES_PER_STRATEGY_MET,
+ GrossValueOtherSpeciesPerStrMet);
+
+ } else if ((date.getYear() == 0) || (param_gravite == false)) {
+ //si ann�e==0 alors on ne fait que le calcul des gross value other species
+ for (Strategy str : strs) {
+ log.info("INFO: Boucle creation valuePerUnitEffort : "
+ + str.getName());
+ //log.info("Boucle creation catchperuniteffort : "+ str.getName());
+ StrategyMonthInfo smi = str.getStrategyMonthInfo(date
+ .getMonth());
+ Collection<EffortDescription> strMet = str
+ .getSetOfVessels().getPossibleMetiers();
+ for (EffortDescription ed : strMet) {
+ Metier strMetier = ed.getPossibleMetiers();
+ log.info("PropStrInitiale(metier="
+ + strMetier.getName() + ")"
+ + smi.getProportionMetier(strMetier));
+ double valMetOtherSpecies = matrixCoeffOthers.getValue(
+ str, strMetier, ALPHA_O)
+ + matrixCoeffOthers.getValue(str, strMetier,
+ BETA_O)
+ * smi.getProportionMetier(strMetier);
+ //tester si valMetOtherSpecies <= alors mettre � 0
+ if (valMetOtherSpecies < 0) {
+ valMetOtherSpecies = 0;
+ }
+ GrossValueOtherSpeciesPerStrMet.setValue(str,
+ strMetier, valMetOtherSpecies);
+ log.info("valOtherMetLangoustine : "
+ + valMetOtherSpecies);
+ log.info("GrossValuePerStrMet apres : "
+ + GrossValueOtherSpeciesPerStrMet.getValue(str,
+ strMetier));
+ }
+ }
+ // r�sultats grossvalue otherspecies mis dans le resultManager
+ resultmanager
+ .addResult(
+ date,
+ ResultName.MATRIX_GROSS_VALUE_OF_LANDINGS_OTHER_SPECIES_PER_STRATEGY_MET,
+ GrossValueOtherSpeciesPerStrMet);
+ } // fin de calcul pour ann�e ==0
+ first = false;
+
+ }// fin de first= true
+
+ if (log.isDebugEnabled()) {
+ log.debug("fin Gravite CPUEAction avant");
+ }
+
+ }
+
+ /**
+ * Si la condition est vrai alors cette action est execut�e apres le pas de
+ * temps de la simulation.
+ *
+ * @param simulation
+ * La simulation pour lequel on utilise cette regle
+ */
+ public void postAction(SimulationContext context, Date date, Metier metier)
+ throws Exception {
+ first = true;
+
+ }
+
+}
Modified: trunk/rules/TACpoids.java
===================================================================
--- trunk/rules/TACpoids.java 2009-04-22 16:32:05 UTC (rev 120)
+++ trunk/rules/TACpoids.java 2009-04-28 13:19:55 UTC (rev 121)
@@ -1,21 +1,19 @@
package rules;
+import static org.codelutin.i18n.I18n._;
+
import java.util.HashSet;
-import java.util.List;
import java.util.Set;
-import static org.codelutin.i18n.I18n._;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.codelutin.math.matrix.MatrixFactory;
import org.codelutin.math.matrix.MatrixIterator;
import org.codelutin.math.matrix.MatrixND;
import scripts.ResultName;
import scripts.RuleUtil;
import scripts.SiMatrix;
-
+import fr.ifremer.isisfish.datastore.ResultStorage;
import fr.ifremer.isisfish.entities.EffortDescription;
import fr.ifremer.isisfish.entities.Metier;
import fr.ifremer.isisfish.entities.Population;
@@ -29,107 +27,119 @@
import fr.ifremer.isisfish.simulator.SimulationContext;
import fr.ifremer.isisfish.types.Date;
import fr.ifremer.isisfish.types.Month;
+import fr.ifremer.isisfish.util.Doc;
-import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605)
-
/**
* TAC.java
*
* Created: 7 septembre 2006
*
* @author anonymous <anonymous(a)labs.libre-entreprise.org>
- * @version $Revision: 1.5 $
+ * @version $Revision: 1.3 $
*
- * Last update: $Date: 2007-11-20 15:50:09 $
- * by : $Author: bpoussin $
+ * Last update: $Date: 290607 $
+ * by : $Author: sigrid $
*/
/**
- * TAC peut-etre utilisé pour les différents TAC, en proportion des effectifs
+ * TAC peut-etre utilis� pour les diff�rents TAC, en proportion des effectifs
* et/ou avec survie ou non.
*
- * <li>Pour utiliser le tac proportionnel, il faut mettre dans le parametre propTac
- * une valeur > 0, le TAC sera alors recalculé a chaque mois de janvier.
- * <li>Pour utiliser la survie il faut mettre dans le paramètre propSurvie
- * une valeur > 0, automatiquement les suvie seront ajouté aux effectifs
- *
+ * <li>Pour utiliser le tac proportionnel, il faut mettre dans le parametre
+ * propTac une valeur > 0, le TAC sera alors recalcul� a chaque mois de janvier.
+ * <li>Pour utiliser la survie il faut mettre dans le param�tre propSurvie une
+ * valeur > 0, automatiquement les suvie seront ajout� aux effectifs
+ *
*/
public class TACpoids extends AbstractRule {
/** to use log facility, just put in your code: log.info("..."); */
static private Log log = LogFactory.getLog(TACpoids.class);
- @Doc(value="do the doc of param species")
+ @Doc(value = "do the doc of param species")
public Species param_species = null;
- @Doc(value="do the doc of param beginDate")
+ @Doc(value = "do the doc of param beginDate")
public Date param_beginDate = new Date(0);
- @Doc(value="do the doc of param endDate")
- public Date param_endDate = new Date(22);
- @Doc(value="do the doc of param propSurvie")
+ @Doc(value = "do the doc of param endDate")
+ public Date param_endDate = new Date(90);
+ @Doc(value = "do the doc of param propSurvie")
public double param_propSurvie = 0;
- @Doc(value="do the doc of param propTac")
+ @Doc(value = "do the doc of param propTac")
public double param_propTac = 0;
- /** TAC in tonne */
- public double param_tacInTons = 0;
-
+ /** TAC in tonnes */
+ @Doc(value = "TAC in tons")
+ public double param_tacInTons = 900;
+
boolean affectation = false;
-
- protected String [] necessaryResult = {
- // put here all necessary result for this rule
- // example:
- // ResultName.MATRIX_BIOMASS,
- // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET,
+
+ protected String[] necessaryResult = {
+ // put here all necessary result for this rule
+ // example:
+ // ResultName.MATRIX_BIOMASS,
+ // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET,
};
-
+
/**
* @return the necessaryResult
*/
public String[] getNecessaryResult() {
return this.necessaryResult;
}
-
+
/**
* Permet d'afficher a l'utilisateur une aide sur la regle.
+ *
* @return L'aide ou la description de la regle
*/
public String getDescription() {
- return _("TAC weight in tons.\nIf you want survival discard use propSurvie other than 0.\nIf you wish TAC computed use propTac other than 0.");
+ 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.");
}
-
+
/**
- * Appelé au démarrage de la simulation, cette méthode permet d'initialiser
+ * Appel� au d�marrage de la simulation, cette m�thode permet d'initialiser
* des valeurs
- * @param simulation La simulation pour lequel on utilise cette regle
+ *
+ * @param simulation
+ * La simulation pour lequel on utilise cette regle
*/
- public void init(SimulationContext context) throws Exception {
+ public void init(SimulationContext context) throws Exception {
}
-
+
/**
* La condition qui doit etre vrai pour faire les actions
- * @param simulation La simulation pour lequel on utilise cette regle
+ *
+ * @param simulation
+ * La simulation pour lequel on utilise cette regle
* @return vrai si on souhaite que les actions soit faites
*/
- public boolean condition(SimulationContext context, Date date, Metier metier) throws Exception {
+ public boolean condition(SimulationContext context, Date date, Metier metier)
+ throws Exception {
+
+ log.info("test si TAC atteint");
// read species in current session
- param_species = (Species)context.getDB().findByTopiaId(param_species.getTopiaId());
-
- // on fait le calcul du tac si nécessaire
- if (param_propTac > 0 && date.getMonth().equals(Month.JANUARY)){
+ param_species = (Species) context.getDB().findByTopiaId(
+ param_species.getTopiaId());
+
+ // on fait le calcul du tac si n�cessaire
+ if (param_propTac > 0 && date.getMonth().equals(Month.JANUARY)) {
PopulationMonitor popMon = context.getPopulationMonitor();
param_tacInTons = popMon.getBiomass(param_species) * param_propTac;
- }
-
+ }
+
boolean result = false;
- if(date.before(param_beginDate)) {
+ if (date.before(param_beginDate)) {
result = false;
- } else if(date.after(param_endDate)) {
- result = false;
+ } else if (date.after(param_endDate)) {
+ result = false;
} else {
- TargetSpecies ts = metier.getMetierSeasonInfo(date.getMonth()).getSpeciesTargetSpecies(param_species);
+ TargetSpecies ts = metier.getMetierSeasonInfo(date.getMonth())
+ .getSpeciesTargetSpecies(param_species);
if (ts != null) {
- double catchTons = RuleUtil.getTotalCatchTons(context, param_species, date);
- log.info("[TAC] catchTons = " + catchTons + " >= param_tacInTons:" + param_tacInTons );
+ double catchTons = RuleUtil.getTotalCatchTons(context,
+ param_species, date);
+ log.info("[TAC] catchTons = " + catchTons
+ + " >= param_tacInTons:" + param_tacInTons);
if (catchTons >= param_tacInTons) {
result = true;
}
@@ -137,39 +147,47 @@
}
return result;
}
-
+
/**
- * Si la condition est vrai alors cette action est executée avant le pas
- * de temps de la simulation.
- * @param simulation La simulation pour lequel on utilise cette regle
+ * Si la condition est vrai alors cette action est execut�e avant le pas de
+ * temps de la simulation.
+ *
+ * @param simulation
+ * La simulation pour lequel on utilise cette regle
*/
- public void preAction(SimulationContext context, Date date, Metier metier) throws Exception {
+ public void preAction(SimulationContext context, Date date, Metier metier)
+ throws Exception {
affectation = false;
+
log.info("[TAC] preAction for: " + metier);
-
- TargetSpecies ts = metier.getMetierSeasonInfo(date.getMonth()).getSpeciesTargetSpecies(param_species);
- if(ts != null && ts.getPrimaryCatch()) {
+ log.info(" TAC atteint [TAC] preAction for: " + metier);
+ TargetSpecies ts = metier.getMetierSeasonInfo(date.getMonth())
+ .getSpeciesTargetSpecies(param_species);
+ if (ts != null && ts.getPrimaryCatch()) {
// recupere tous les metiers qui ont l'espece en capture principale =>metiers vises
- List<Metier> aimedMetiers = context.getDB().find("select distinct(metierSeasonInfo.metier) " +
- "from fr.ifremer.isisfish.entities.TargetSpecies " +
- "where species=? and primaryCatch=true", param_species);
+ // 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);
+ log.info("aimed Metier: " + aimedMetiers);*/
context.getMetierMonitor().addforbiddenMetier(metier);
-
- //récupere toutes les stratégies pratiquant le métier et pour lesquelles la proportion !=0
+
+ //r�cupere toutes les strat�gies pratiquant le m�tier et pour lesquelles la proportion !=0
SiMatrix siMatrix = SiMatrix.getSiMatrix(context);
Set<Strategy> strs = new HashSet<Strategy>();
for (Strategy str : siMatrix.getStrategies(date)) {
- double prop = str.getStrategyMonthInfo(date.getMonth()).getProportionMetier(metier);
+ double prop = str.getStrategyMonthInfo(date.getMonth())
+ .getProportionMetier(metier);
if (prop != 0) {
strs.add(str);
}
}
-
- for (Strategy str : strs){
- StrategyMonthInfo smi = str.getStrategyMonthInfo(date.getMonth());
-
+
+ for (Strategy str : strs) {
+ StrategyMonthInfo smi = str.getStrategyMonthInfo(date
+ .getMonth());
+
// 1er cas de figure: l'effort est reporte sur un metier de la
// meme strategie, n'ayant pas l'espece comme capture principale
// et pechant avec le meme engin
@@ -181,35 +199,38 @@
// sans consideration sur les engins, et pour lesquels la
// proportion peut etre nulle
Set<Metier> possibleMetierCase3 = new HashSet<Metier>();
-
- for (EffortDescription effort : str.getSetOfVessels().getPossibleMetiers()) {
+
+ for (EffortDescription effort : str.getSetOfVessels()
+ .getPossibleMetiers()) {
Metier newMetier = effort.getPossibleMetiers();
if (
- !aimedMetiers.contains(newMetier)
- && !metier.getName().equalsIgnoreCase("nonActiviy")
+ /*!aimedMetiers.contains(newMetier)
+ &&*/!metier.getName().equalsIgnoreCase("nonActiviy")
&& !metier.getName().equalsIgnoreCase("nonActivie")
- && !context.getMetierMonitor().getForbiddenMetier().contains(newMetier)
- ) {
+ && !metier.getName().equalsIgnoreCase(
+ "non Activit�")
+ && !context.getMetierMonitor().getForbiddenMetier()
+ .contains(newMetier)) {
possibleMetierCase3.add(newMetier);
-
+
if (smi.getProportionMetier(newMetier) != 0) {
possibleMetierCase2.add(newMetier);
-
+
if (metier.getGear().equals(newMetier.getGear())) {
possibleMetierCase1.add(newMetier);
}
}
}
}
-
+
Set<Metier> possibleMetier = null;
- if (possibleMetierCase1.size() != 0){
+ if (possibleMetierCase1.size() != 0) {
log.info("[TAC] Use case 1");
possibleMetier = possibleMetierCase1;
} else if (possibleMetierCase2.size() != 0) {
log.info("[TAC] Use case 2");
possibleMetier = possibleMetierCase2;
- } else if (possibleMetierCase3.size() != 0){
+ } else if (possibleMetierCase3.size() != 0) {
log.info("[TAC] Use case 3");
possibleMetier = possibleMetierCase3;
}
@@ -219,46 +240,52 @@
// possibles dans la meme strategie si un metier possible existe
// bien la repartion est proportionnelle a l'effort deja alloue
// dans la strategie
-
- double somme=0;
- for (Metier met : possibleMetierCase1) {
+
+ double somme = 0;
+ for (Metier met : possibleMetier) {
somme += smi.getProportionMetier(met);
}
- for (Metier met : possibleMetierCase1) {
- double newProportion =
- smi.getProportionMetier(met)
- + (smi.getProportionMetier(metier)
- * smi.getProportionMetier(met) / somme);
+ for (Metier met : possibleMetier) {
+ double newProportion = smi.getProportionMetier(met)
+ + (smi.getProportionMetier(metier)
+ * smi.getProportionMetier(met) / somme);
smi.setProportionMetier(met, newProportion);
}
- smi.setProportionMetier(metier, 0); //le metier vise a alors une proportion nulle
- } else{
+ smi.setProportionMetier(metier, 0); //le metier vise a alors une proportion nulle
+ log.info("[TAC] il y a des metiers possibles");
+ } else {
log.info("[TAC] Use no activity");
-
+
// sinon on met tout dans le metier nonActivite
MetierMonitor metierMon = context.getMetierMonitor();
MatrixND mat = metierMon.getOrCreateNoActivity(date,
- ResultName.MATRIX_NO_ACTIVITY,
- siMatrix.getStrategies(date),
- siMatrix.getMetiers(date));
+ ResultName.MATRIX_NO_ACTIVITY, siMatrix
+ .getStrategies(date), siMatrix
+ .getMetiers(date));
mat.setValue(str, metier, smi.getProportionMetier(metier));
-
+
smi.getProportionMetier().setValue(metier, 0);
- }
+ }
}
}
}
-
+
/**
- * Si la condition est vrai alors cette action est executée apres le pas
- * de temps de la simulation.
- * @param simulation La simulation pour lequel on utilise cette regle
+ * Si la condition est vrai alors cette action est execut�e apres le pas de
+ * temps de la simulation.
+ *
+ * @param simulation
+ * La simulation pour lequel on utilise cette regle
*/
- public void postAction(SimulationContext context, Date date, Metier metier) throws Exception {
+ public void postAction(SimulationContext context, Date date, Metier metier)
+ throws Exception {
+ ResultStorage resultmanager = context.getSimulationStorage()
+ .getResultStorage();
log.info("[TAC] postAction for: " + metier);
- TargetSpecies ts = metier.getMetierSeasonInfo(date.getMonth()).getSpeciesTargetSpecies(param_species);
- if(ts != null){
- if (!affectation){
+ TargetSpecies ts = metier.getMetierSeasonInfo(date.getMonth())
+ .getSpeciesTargetSpecies(param_species);
+ if (ts != null) {
+ if (!affectation) {
// ATTENTION
// les captures pour cette metapop ne sont plus du qu'au metier
// pour qui l'espece est secondaire: elles sont affectees aux
@@ -270,36 +297,46 @@
// pour les captures)
//////
PopulationMonitor popMon = context.getPopulationMonitor();
+ log.info("popMon biomass" + popMon.getBiomass(param_species));
for (Population pop : param_species.getPopulation()) {
- // si on a deja une matrice rejet on le vide (elle vient
- // forcement de la regle taille minimale or si le tac est
- // atteint, tout va dorenavent dans les rejets et on mais
- // TOUTES les captures dans les rejets
- MatrixND discard = popMon.getDiscard(date, pop);
- if (discard != null) {
- discard.mults(0);
- }
-
- discard = popMon.getCatch(pop).copy();
- discard.setName(ResultName.MATRIX_DISCARDS_PER_STR_MET_PER_ZONE_POP);
- popMon.addDiscard(date, pop, discard);
- log.info("[TAC] add discard for " + pop + ": " + discard);
-
- if (param_propSurvie > 0) {
- MatrixND eff = popMon.getN(pop);
- //on réajoute les survivants aux effectifs
- for (MatrixIterator i=discard.iterator(); i.next();){
- Object [] coord = i.getSemanticsCoordinates();
- eff.setValue(coord[2],coord[3],
- eff.getValue(coord[2],coord[3])+i.getValue()*param_propSurvie);
+ if (!pop.getName().equals("Population_new")) {
+ log.info("pop : " + pop.getName());
+ // si on a deja une matrice rejet on le vide (elle vient
+ // forcement de la regle taille minimale or si le tac est
+ // atteint, tout va dorenavent dans les rejets et on mais
+ // TOUTES les captures dans les rejets
+ MatrixND discard = popMon.getDiscard(date, pop);
+ log.info("discard : " + discard);
+ if (discard != null) {
+ discard.mults(0);
}
+ log.info("catch = " + popMon.getCatch(pop));
+ 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);
+ popMon.addDiscard(date, pop, discard);
+ log.info("[TAC] add discard for " + pop + ": "
+ + discard);
+ // ne manquerait-il pas
+ resultmanager.addResult(date, pop, discard);
+ if (param_propSurvie > 0) {
+ MatrixND eff = popMon.getN(pop);
+ //on r�ajoute les survivants aux effectifs
+ for (MatrixIterator i = discard.iterator(); i
+ .next();) {
+ Object[] coord = i.getSemanticsCoordinates();
+ eff.setValue(coord[2], coord[3], eff.getValue(
+ coord[2], coord[3])
+ + i.getValue() * param_propSurvie);
+ }
+ }
+
}
+ // on a affecte une fois cette meta pop au rejet il ne faut pas
+ // le refaire
+ affectation = true;
}
-
- // on a affecte une fois cette meta pop au rejet il ne faut pas
- // le refaire
- affectation=true;
}
}
}
Modified: trunk/scripts/ResultName.java
===================================================================
--- trunk/scripts/ResultName.java 2009-04-22 16:32:05 UTC (rev 120)
+++ trunk/scripts/ResultName.java 2009-04-28 13:19:55 UTC (rev 121)
@@ -1,6 +1,6 @@
/* *##%
* Copyright (C) 2006
- * Code Lutin, Cédric Pineau, Benjamin Poussin
+ * 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
@@ -20,7 +20,7 @@
/* *
* ResultName.java
*
- * Created: 23 août 2006 15:09:37
+ * Created: 23 ao�t 2006 15:09:37
*
* @author poussin
* @version $Revision: 1.10 $
@@ -37,54 +37,48 @@
/**
* Contient l'ensemble des noms des differents resultats. Le mieux lorsque l'on
- * veut un nouveau résultat est d'ajouter une constante ici, et de l'utiliser
- * ensuite lors de la création de la matrice.
+ * veut un nouveau r�sultat est d'ajouter une constante ici, et de l'utiliser
+ * ensuite lors de la cr�ation de la matrice.
* <p>
- * Ceci permet d'avoir un endroit unique ou l'on voit l'ensemble des résultats
- * potentiellement disponible et de ne pas ce tromper en écrivent le nom
- * d'un résultat
+ * Ceci permet d'avoir un endroit unique ou l'on voit l'ensemble des r�sultats
+ * potentiellement disponible et de ne pas ce tromper en �crivent le nom
+ * d'un r�sultat
* <p>
* Cette classe ne doit contenir que des noms de resultat en static public String
* l'interface de lancement de simulation se base sur cette classe pour
- * afficher l'ensemble des résultats disponible
+ * afficher l'ensemble des r�sultats disponible
*
* @author poussin
*/
public class ResultName {
@Doc(value = "do the doc of Result matrixDiscardsWeightPerStrMet")
- static final public String MATRIX_DISCARDS_WEIGHT_PER_STR_MET_PER_ZONE_POP = n_("matrixDiscardsWeightPerStrMet");
+ static final public String MATRIX_DISCARDS_WEIGHT_PER_STR_MET = n_("matrixDiscardsWeightPerStrMet");
@Doc(value = "do the doc of Result matrixDiscardsPerStrMet")
- static final public String MATRIX_DISCARDS_PER_STR_MET_PER_ZONE_POP = n_("matrixDiscardsPerStrMet");
+ static final public String MATRIX_DISCARDS_PER_STR_MET = n_("matrixDiscardsPerStrMet");
@Doc(value = "do the doc of Result matrixLandingPerMet")
static final public String MATRIX_LANDING_PER_MET = n_("matrixLandingPerMet");
@Doc(value = "do the doc of Result matrixEffortPerStrategyMet")
static final public String MATRIX_EFFORT_PER_STRATEGY_MET = n_("matrixEffortPerStrategyMet");
+ @Doc(value = "do the doc of Result 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");
- @Doc(value = "Disponible uniquement avec les simulations par Zone. do the doc of Result matrixCatchRatePerStrategyMet")
- static final public String MATRIX_CATCH_RATE_PER_STRATEGY_MET_PER_ZONE_POP = n_("matrixCatchRatePerStrategyMet");
- @Doc(value = "do the doc of Result matrixCatchPerStrategyMetPerZoneMet")
- static final public String MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_MET = n_("matrixCatchPerStrategyMetPerZoneMet");
- @Doc(value = "do the doc of Result matrixCatchPerStrategyMetPerZonePop")
- static final public String MATRIX_CATCH_PER_STRATEGY_MET_PER_ZONE_POP = n_("matrixCatchPerStrategyMetPerZonePop");
- @Doc(value = "do the doc of Result matrixCatchWeightPerStrategyMetPerZoneMet")
- static final public String MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_MET = n_("matrixCatchWeightPerStrategyMetPerZoneMet");
- @Doc(value = "do the doc of Result matrixCatchWeightPerStrategyMetPerZonePop")
- static final public String MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP = n_("matrixCatchWeightPerStrategyMetPerZonePop");
- @Doc(value = "Disponible uniquement avec les simulations par Zone. do the doc of Result matrixFishingMortality")
+ @Doc(value = "do the doc of Result matrixCatchRatePerStrategyMet")
+ static final public String MATRIX_CATCH_RATE_PER_STRATEGY_MET = n_("matrixCatchRatePerStrategyMet");
+ @Doc(value = "do the doc of Result matrixCatchPerStrategyMet")
+ static final public String MATRIX_CATCH_PER_STRATEGY_MET = n_("matrixCatchPerStrategyMet");
+ @Doc(value = "do the doc of Result matrixFishingMortality")
static final public String MATRIX_FISHING_MORTALITY = n_("matrixFishingMortality");
+ @Doc(value = "do the doc of Result matrixCatchWeightPerStrategyMet")
+ static final public String MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET = n_("matrixCatchWeightPerStrategyMet");
@Doc(value = "do the doc of Result matrixAbundance")
static final public String MATRIX_ABUNDANCE = n_("matrixAbundance");
@Doc(value = "do the doc of Result matrixBiomass")
static final public String MATRIX_BIOMASS = n_("matrixBiomass");
- @Doc(value = "do the doc of Result matrixBiomassBeginMonth")
- static final public String MATRIX_BIOMASS_BEGIN_MONTH = n_("matrixBiomassBeginMonth");
- @Doc(value = "do the doc of Result matrixBiomassBeginMonth")
- static final public String MATRIX_ABONDANCE_BEGIN_MONTH = n_("matrixAbondanceBeginMonth");
@Doc(value = "do the doc of Result matrixFishingTimePerMonthPerVessel")
static final public String MATRIX_FISHING_TIME_PER_MONTH_PER_VESSEL = n_("matrixFishingTimePerMonthPerVessel");
@@ -105,6 +99,8 @@
static final public String MATRIX_GROSS_VALUE_OF_LANDINGS_PER_SPECIES_PER_STRATEGY_MET = n_("matrixGrossValueOfLandingsPerSpeciesPerStrategyMet");
@Doc(value = "do the doc of Result matrixGrossValueOfLandingsPerStrategyMet")
static final public String MATRIX_GROSS_VALUE_OF_LANDINGS_PER_STRATEGY_MET = n_("matrixGrossValueOfLandingsPerStrategyMet");
+ @Doc(value = "do the doc of Result matrixGrossValueOfLandingsOtherSpeciesPerStrategyMet")
+ static final public String MATRIX_GROSS_VALUE_OF_LANDINGS_OTHER_SPECIES_PER_STRATEGY_MET = n_("matrixGrossValueOfLandingsOtherSpeciesPerStrategyMet");
@Doc(value = "do the doc of Result matrixGrossValueOfLandingsPerStrategyMetPerVessel")
static final public String MATRIX_GROSS_VALUE_OF_LANDINGS_PER_STRATEGY_MET_PER_VESSEL = n_("matrixGrossValueOfLandingsPerStrategyMetPerVessel");
@Doc(value = "do the doc of Result matrixNetValueOfLandingsPerStrategyMet")
1
0
Author: jcouteau
Date: 2009-04-22 16:32:05 +0000 (Wed, 22 Apr 2009)
New Revision: 120
Modified:
trunk/sensitivity/SensitivityCalculatorJavaExpandGrid.java
trunk/sensitivity/SensitivityCalculatorRFrF2.java
Log:
Code formatting and some corrections
Modified: trunk/sensitivity/SensitivityCalculatorJavaExpandGrid.java
===================================================================
--- trunk/sensitivity/SensitivityCalculatorJavaExpandGrid.java 2009-04-22 16:31:17 UTC (rev 119)
+++ trunk/sensitivity/SensitivityCalculatorJavaExpandGrid.java 2009-04-22 16:32:05 UTC (rev 120)
@@ -392,14 +392,7 @@
+ ")");
log.info("Message sent to R : "
+ "isis.simule<-data.frame(isis.simule," + name + ")");
- }
- for (int k = 0; k < sensitivityNumber; k++) {
-
- // Creates the R expression to import results in R
- String name = simulationStorages.get(0).getParameter()
- .getSensitivityExport().get(k).getExportFilename();
-
//Create the dataforaov data.frame
String dataframe = "dataforaov<-data.frame(factors," + name
+ "=" + name + ")";
Modified: trunk/sensitivity/SensitivityCalculatorRFrF2.java
===================================================================
--- trunk/sensitivity/SensitivityCalculatorRFrF2.java 2009-04-22 16:31:17 UTC (rev 119)
+++ trunk/sensitivity/SensitivityCalculatorRFrF2.java 2009-04-22 16:32:05 UTC (rev 120)
@@ -19,9 +19,7 @@
package sensitivity;
import java.io.File;
-import java.io.Serializable;
import java.util.List;
-import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -31,15 +29,12 @@
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.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.SensitivityCalculator;
-
-import fr.ifremer.isisfish.simulator.sensitivity.AbstractSensitivityCalculator;
import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios;
import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
import fr.ifremer.isisfish.simulator.sensitivity.domain.DiscreteDomain;
@@ -163,8 +158,7 @@
for (int j = 0; j < nbExperiments; j++) {
Scenario experimentScenario = new Scenario();
for (int i = 0; i < factorNumber; i++) {
- Factor factor = plan.getFactors()
- .get(i);
+ Factor factor = plan.getFactors().get(i);
if ((factor.getDomain() instanceof MatrixContinuousDomain)
|| (factor.getDomain() instanceof EquationContinuousDomain)) {
if (frf2.getValue(new int[] { i, j }) == -1) {
@@ -178,15 +172,13 @@
}
} else {
if (frf2.getValue(new int[] { i, j }) == -1) {
- factor
- .setValueForIdentifier(((ContinuousDomain) factor
- .getDomain()).getMinBound());
+ factor.setValueForIdentifier(((ContinuousDomain) factor
+ .getDomain()).getMinBound());
}
if (frf2.getValue(new int[] { i, j }) == 1) {
- factor
- .setValueForIdentifier(((ContinuousDomain) factor
- .getDomain()).getMaxBound());
+ factor.setValueForIdentifier(((ContinuousDomain) factor
+ .getDomain()).getMaxBound());
}
}
experimentScenario.addFactor(factor);
@@ -197,8 +189,8 @@
try {
//Create the factors vectors
for (int j = 0; j < factorNumber; j++) {
- Factor factor = thisExperimentScenarios
- .get(0).getFactors().get(j);
+ Factor factor = thisExperimentScenarios.get(0).getFactors()
+ .get(j);
if (factor.getDomain() instanceof EquationContinuousDomain) {
String vector = "factor" + j + "<-c(";
@@ -477,7 +469,6 @@
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,\""
1
0
Author: jcouteau
Date: 2009-04-22 16:31:17 +0000 (Wed, 22 Apr 2009)
New Revision: 119
Modified:
trunk/sensitivity/SensitivityCalculatorRRandomLHS.java
Log:
RandomLHS conform to new CDC
Modified: trunk/sensitivity/SensitivityCalculatorRRandomLHS.java
===================================================================
--- trunk/sensitivity/SensitivityCalculatorRRandomLHS.java 2009-04-22 14:33:10 UTC (rev 118)
+++ trunk/sensitivity/SensitivityCalculatorRRandomLHS.java 2009-04-22 16:31:17 UTC (rev 119)
@@ -19,9 +19,10 @@
package sensitivity;
import java.io.File;
-import java.io.Serializable;
import java.util.List;
+import javax.swing.JOptionPane;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codelutin.j2r.REngine;
@@ -31,14 +32,15 @@
import org.codelutin.util.FileUtil;
import fr.ifremer.isisfish.datastore.SimulationStorage;
+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.SensitivityCalculator;
-import fr.ifremer.isisfish.simulator.sensitivity.AbstractSensitivityCalculator;
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;
@@ -51,14 +53,15 @@
*
*/
@Doc("Random Latin Hypercube")
-public class SensitivityCalculatorRRandomLHS extends AbstractSensitivityCalculator {
+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;
+ public int param_simulationNumber = 10;
/**
* Retourne vrai si le calculateur sait gerer la cardinalité des facteurs
@@ -73,12 +76,28 @@
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;
}
@@ -86,6 +105,14 @@
REngine engine = new RProxy();
try {
+ //Set working directory to get Isis R session
+ log.info("setwd(\"" + outputdirectory.getParent() + "\")");
+ engine.voidEval("setwd(\"" + outputdirectory.getParent() + "\")");
+
+ //Get Isis R session
+ log.info("load(\".RData\")");
+ engine.voidEval("load(\".RData\")");
+
//Load the lhs library
engine.voidEval("library(lhs)");
log.info("Message sent to R : " + "library(lhs)");
@@ -108,8 +135,7 @@
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 factor = plan.getFactors().get(i);
if ((factor.getDomain() instanceof MatrixContinuousDomain)
|| (factor.getDomain() instanceof EquationContinuousDomain)) {
factor
@@ -131,13 +157,74 @@
thisExperiment.setScenarios(thisExperimentScenarios);
}
- //Create the factors vectors
- for (int j = 0; j < factornumber; j++) {
- Factor factor = thisExperimentScenarios
- .get(0).getFactors().get(j);
+ 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" + j + "<-c(";
+ String vector = factor.getName().replaceAll(" ", "")
+ + "<-c(";
for (int i = 0; i < param_simulationNumber; i++) {
if (i < (param_simulationNumber - 1)) {
vector = vector
@@ -156,7 +243,9 @@
engine.voidEval(vector);
log.info("Message sent to R : " + vector);
} else if (factor.getDomain() instanceof MatrixContinuousDomain) {
- String vector = "factor" + j + "<-c(";
+ //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
@@ -175,7 +264,9 @@
engine.voidEval(vector);
log.info("Message sent to R : " + vector);
} else {
- String vector = "factor" + j + "<-c(";
+ //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
@@ -193,15 +284,13 @@
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 + "),";
+ if (j < factors.size() - 1) {
+ data += factor.getName().replaceAll(" ", "") + "=factor("
+ + factor.getName().replaceAll(" ", "") + "),";
} else {
- data = data + "factor" + j + "=factor(factor" + j + "))";
+ data += factor.getName().replaceAll(" ", "") + "=factor("
+ + factor.getName().replaceAll(" ", "") + "))";
}
}
@@ -241,6 +330,14 @@
log.info("Message sent to R"
+ "dput(factornames,file=\".factornames\")");
+ //Set working directory to save Isis R session
+ log.info("setwd(\"" + outputdirectory.getParent() + "\")");
+ engine.voidEval("setwd(\"" + outputdirectory.getParent() + "\")");
+
+ // Save Isis R session
+ log.info("save.image()");
+ engine.voidEval("save.image()");
+
engine.terminate();
} catch (Exception e) {
@@ -261,36 +358,44 @@
REngine engine = new RProxy();
try {
- param_simulationNumber = simulationStorages.get(0).getParameter()
- .getSensitivityExport().size();
+ //Set working directory to get Isis R session
+ log.info("setwd(\"" + outputdirectory.getParent() + "\")");
+ engine.voidEval("setwd(\"" + outputdirectory.getParent() + "\")");
- for (int k = 0; k < param_simulationNumber; k++) {
+ //Get Isis R session
+ log.info("load(\".RData\")");
+ engine.voidEval("load(\".RData\")");
- // Set output directory
- engine.voidEval("setwd(\"" + outputdirectory.getAbsolutePath()
- + "\")");
- log.info("Message sent to R : setwd(\""
- + outputdirectory.getAbsolutePath() + "\")");
+ // Set output directory
+ engine.voidEval("setwd(\"" + outputdirectory.getAbsolutePath()
+ + "\")");
+ log.info("Message sent to R : setwd(\""
+ + outputdirectory.getAbsolutePath() + "\")");
- //Get back the scenarios
- //engine.voidEval("factors<-read.csv(\".expandgrid.csv\",row.names=1,col.names=1)");
- engine.voidEval("factors<-read.csv(\".randomlhs.csv\")");
- log
- .info("Message sent to R : factors<-read.csv(\".randomlhs.csv\")");
+ //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 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();
- //factorNumber=factorNumber-1;
+ //Get back the factors number
+ int factorNumber = ((Double) engine.eval("length(factors)-1"))
+ .intValue();
- //Create the results vectors
- String result = "result<-c(";
- for (int l = 0; l < simulationStorages.size(); l++) {
+ param_simulationNumber = simulationStorages.get(0).getParameter()
+ .getSensitivityExport().size();
+
+ for (int k = 0; k < param_simulationNumber; k++) {
+
+ // Creates the R expression to import results in R
+ String name = simulationStorages.get(0).getParameter()
+ .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
@@ -304,27 +409,64 @@
String simulResult = FileUtil.readAsString(importFile);
double simulationResult = Double.valueOf(simulResult);
if (l < simulationStorages.size() - 1) {
- result = result + simulationResult + ",";
+ rInstruction = rInstruction + simulationResult + ",";
} else {
- result = result + simulationResult;
+ rInstruction = rInstruction + simulationResult;
}
}
- result = result + ")";
- engine.voidEval(result);
- log.info("Message sent to R : " + result);
+ 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 < param_simulationNumber; k++) {
+
+ // Creates the R expression to import results in R
+ String name = simulationStorages.get(0).getParameter()
+ .getSensitivityExport().get(k).getExportFilename();
+
//Create the dataforaov data.frame
- String dataframe = "dataforaov<-data.frame(factors,result=result)";
+ String dataframe = "dataforaov<-data.frame(factors," + name
+ + "=" + name + ")";
engine.voidEval(dataframe);
log.info("Message sent to R : " + dataframe);
//Call aov()
- String aovCall = "aovresult<-aov(result~";
+ 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 + "factor" + j + "+";
+ aovCall = aovCall
+ + engine
+ .eval("names(factors)[" + (j + 2) + "]")
+ + "+";
} else {
- aovCall = aovCall + "factor" + j + ",data=dataforaov)";
+ aovCall = aovCall
+ + engine
+ .eval("names(factors)[" + (j + 2) + "]")
+ + ",data=dataforaov)";
}
}
engine.voidEval(aovCall);
@@ -367,14 +509,6 @@
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()
- + "\")");
- log.info("Message sent to R : setwd(\""
- + outputdirectory.getAbsolutePath() + "\")");
-
//Set dataforaov names
engine
.voidEval("resultsnames<-c(\"Simulation\",factornames,\"Result\")");
@@ -385,6 +519,14 @@
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()
+ + "\")");
+ log.info("Message sent to R : setwd(\""
+ + outputdirectory.getAbsolutePath() + "\")");
+
//Save the results with the scenarios.
engine.voidEval("write.csv(dataforaov,\""
+ simulationStorages.get(0).getParameter()
@@ -407,10 +549,71 @@
.getExportFilename()
+ "_SensitivityIndices.csv\")");
//FIXME export through java to enable export when using Rserve (when distant Rserve).
- engine.terminate();
+
+ //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 + "\"" + ",aovresult)");
+ engine
+ .voidEval("isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\""
+ + aovCall + "\"" + ",aovresult)");
+
+ 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));
+
}
- log.info("end");
+ //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() + "\")");
+ engine.voidEval("setwd(\"" + outputdirectory.getParent() + "\")");
+
+ // Save Isis R session
+ log.info("save.image()");
+ engine.voidEval("save.image()");
+
+ engine.terminate();
+
} catch (Exception e) {
e.printStackTrace();
// Error while processing
1
0
Author: jcouteau
Date: 2009-04-22 14:33:10 +0000 (Wed, 22 Apr 2009)
New Revision: 118
Modified:
trunk/sensitivity/SensitivityCalculatorJavaExpandGrid.java
trunk/sensitivity/SensitivityCalculatorRegularFractions.java
Log:
Changing attributes instruction in R
Modified: trunk/sensitivity/SensitivityCalculatorJavaExpandGrid.java
===================================================================
--- trunk/sensitivity/SensitivityCalculatorJavaExpandGrid.java 2009-04-21 12:27:21 UTC (rev 117)
+++ trunk/sensitivity/SensitivityCalculatorJavaExpandGrid.java 2009-04-22 14:33:10 UTC (rev 118)
@@ -284,9 +284,9 @@
log
.info("Message sent to R : "
- + "attributes(isis.MethodExp)<-list(nomModel=\"isis-fish-externe-R\")");
+ + "attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
engine
- .voidEval("attributes(isis.MethodExp)<-list(nomModel=\"isis-fish-externe-R\")");
+ .voidEval("attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
//Create isis.Simule
log.info("Message sent to R : " + "isis.simule<-data.frame(data)");
@@ -294,9 +294,9 @@
log
.info("Message sent to R : "
- + "attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+ + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
engine
- .voidEval("attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+ .voidEval("attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
log.info("Message sent to R : "
+ "names(isis.simule)<-isis.factors[[1]]");
@@ -394,13 +394,6 @@
+ "isis.simule<-data.frame(isis.simule," + name + ")");
}
- //adding attribute to isis.Simule
- log
- .info("Message sent to R : "
- + "attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
- engine
- .voidEval("attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
-
for (int k = 0; k < sensitivityNumber; k++) {
// Creates the R expression to import results in R
@@ -521,6 +514,12 @@
.voidEval("isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\""
+ aovCall + "\"" + ",aovresult)");
+ 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("-", "");
Modified: trunk/sensitivity/SensitivityCalculatorRegularFractions.java
===================================================================
--- trunk/sensitivity/SensitivityCalculatorRegularFractions.java 2009-04-21 12:27:21 UTC (rev 117)
+++ trunk/sensitivity/SensitivityCalculatorRegularFractions.java 2009-04-22 14:33:10 UTC (rev 118)
@@ -303,9 +303,9 @@
log
.info("Message sent to R : "
- + "attributes(isis.MethodExp)<-list(nomModel=\"isis-fish-externe-R\")");
+ + "attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
engine
- .voidEval("attributes(isis.MethodExp)<-list(nomModel=\"isis-fish-externe-R\")");
+ .voidEval("attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
//Create isis.Simule
log.info("Message sent to R : " + "isis.simule<-data.frame(data)");
@@ -313,20 +313,18 @@
log
.info("Message sent to R : "
- + "attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+ + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
engine
- .voidEval("attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+ .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 .expandgrid file
+
+ // Export the data.frame object for the second run in a .expandgrid file
engine.voidEval("write.csv(data,file=\".data.csv\")");
- log
- .info("Message sent to R : 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() + "\")");
engine.voidEval("setwd(\"" + outputdirectory.getParent() + "\")");
@@ -374,11 +372,10 @@
engine.voidEval("factornames<-dget(\".factornames\")");
log.info("Message sent to R : "
+ "factornames<-dget(\".factornames\")");
-
- //Get back the scenarios
+
+ //Get back the scenarios
engine.voidEval("factors<-read.csv(\".data.csv\")");
- log
- .info("Message sent to R : 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"))
@@ -427,9 +424,9 @@
//adding attribute to isis.Simule
log
.info("Message sent to R : "
- + "attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+ + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
engine
- .voidEval("attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+ .voidEval("attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
for (int k = 0; k < sensitivityNumber; k++) {
@@ -551,6 +548,12 @@
.voidEval("isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\""
+ aovCall + "\"" + ",aovresult)");
+ 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("-", "");
1
0
Author: jcouteau
Date: 2009-04-21 12:27:21 +0000 (Tue, 21 Apr 2009)
New Revision: 117
Modified:
trunk/sensitivity/SensitivityCalculatorRMorris.java
Log:
Fixed attributes bug in R
Modified: trunk/sensitivity/SensitivityCalculatorRMorris.java
===================================================================
--- trunk/sensitivity/SensitivityCalculatorRMorris.java 2009-04-20 16:25:44 UTC (rev 116)
+++ trunk/sensitivity/SensitivityCalculatorRMorris.java 2009-04-21 12:27:21 UTC (rev 117)
@@ -209,9 +209,29 @@
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 : "
- + "isis.factor.distribution<-c(0.0)");
- engine.voidEval("isis.factor.distribution<-c(0.0)");
+ + 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");
@@ -224,18 +244,18 @@
log
.info("Message sent to R : "
- + "attributes(isis.MethodExp)<-list(nomModel=\"isis-fish-externe-R\")");
+ + "attr(isis.MethodExp,\"nomModel\")<-\"isis-fish-externe-R\"");
engine
- .voidEval("attributes(isis.MethodExp)<-list(nomModel=\"isis-fish-externe-R\")");
+ .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 : "
- + "attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+ + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
engine
- .voidEval("attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+ .voidEval("attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
log.info("Message sent to R : "
+ "names(isis.simule)<-isis.factors[[1]]");
@@ -318,7 +338,7 @@
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)");
@@ -368,9 +388,15 @@
//adding attribute to isis.Simule
log
.info("Message sent to R : "
- + "attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+ + "attr(isis.simule,\"nomModel\")<-\"isis-fish-externe-R\"");
engine
- .voidEval("attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+ .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++) {
@@ -386,11 +412,17 @@
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 + ")" + "\",a)");
+ + 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 + ")" + "\",a)");
+ + 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)");
1
0
Author: jcouteau
Date: 2009-04-20 16:25:44 +0000 (Mon, 20 Apr 2009)
New Revision: 116
Added:
trunk/sensitivity/SensitivityCalculatorRegularFractions.java
trunk/sensitivity/regularfractions.R
Log:
Regular Fractions method working, conform to the new CDC.
Added: trunk/sensitivity/SensitivityCalculatorRegularFractions.java
===================================================================
--- trunk/sensitivity/SensitivityCalculatorRegularFractions.java (rev 0)
+++ trunk/sensitivity/SensitivityCalculatorRegularFractions.java 2009-04-20 16:25:44 UTC (rev 116)
@@ -0,0 +1,614 @@
+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.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")
+ 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
+ */
+ public boolean canManageCardinality() {
+ return true;
+ }
+
+ public SensitivityScenarios compute(DesignPlan plan, File outputdirectory) {
+
+ setIsisFactorsR(plan, outputdirectory);
+
+ double[] dataframeplan = 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();
+
+ 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 {
+
+ //Set working directory to get Isis R session
+ log.info("setwd(\"" + outputdirectory.getParent() + "\")");
+ engine.voidEval("setwd(\"" + outputdirectory.getParent() + "\")");
+
+ //Get Isis R session
+ log.info("load(\".RData\")");
+ engine.voidEval("load(\".RData\")");
+
+ //Set the working directory (to import the R function)
+ engine.voidEval("setwd(\"" + param_pathToFunction + "\")");
+ log.info("Message sent to R : " + "setwd(\"" + param_pathToFunction
+ + "\")");
+
+ //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()
+ + "\")");
+ log.info("Message sent to R : " + "setwd(\""
+ + outputdirectory.getAbsolutePath() + "\")");
+
+ // Export the morris object for the second run in a .morris 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$plan");
+ log.info("Message sent to R : " + "x$plan");
+
+ //Get back the simulation number
+ log.info("length(x[,1])");
+ int simulationNumber = (Integer) engine.eval("length(x$plan[,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 : "
+ + "attributes(isis.MethodExp)<-list(nomModel=\"isis-fish-externe-R\")");
+ engine
+ .voidEval("attributes(isis.MethodExp)<-list(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 : "
+ + "attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+ engine
+ .voidEval("attributes(isis.simule)<-list(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 .expandgrid 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() + "\")");
+ engine.voidEval("setwd(\"" + outputdirectory.getParent() + "\")");
+
+ // Save Isis R session
+ log.info("save.image()");
+ engine.voidEval("save.image()");
+
+ engine.terminate();
+
+ } catch (RException eee) {
+ eee.printStackTrace();
+ throw new RuntimeException("R evaluation failed", eee);
+ }
+
+ return thisExperiment;
+
+ }
+
+ public void analyzeResult(List<SimulationStorage> simulationStorages,
+ File outputdirectory) throws SensitivityException {
+
+ REngine engine = new RProxy();
+ try {
+
+ //Set working directory to get Isis R session
+ log.info("setwd(\"" + outputdirectory.getParent() + "\")");
+ engine.voidEval("setwd(\"" + outputdirectory.getParent() + "\")");
+
+ //Get Isis R session
+ log.info("load(\".RData\")");
+ engine.voidEval("load(\".RData\")");
+
+ // Set output directory
+ engine.voidEval("setwd(\"" + outputdirectory.getAbsolutePath()
+ + "\")");
+ log.info("Message sent to R : setwd(\""
+ + outputdirectory.getAbsolutePath() + "\")");
+
+ // 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();
+
+ int sensitivityNumber = simulationStorages.get(0).getParameter()
+ .getSensitivityExport().size();
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ String name = simulationStorages.get(0).getParameter()
+ .getSensitivityExport().get(k).getExportFilename();
+
+ //Create the results vectors
+ String result = 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,
+ simulationStorages.get(l).getParameter()
+ .getSensitivityExport().get(k)
+ .getExportFilename()
+ + simulationStorages.get(l).getParameter()
+ .getSensitivityExport().get(k)
+ .getExtensionFilename());
+ String simulResult = FileUtil.readAsString(importFile);
+ double simulationResult = Double.valueOf(simulResult);
+ if (l < simulationStorages.size() - 1) {
+ result = result + simulationResult + ",";
+ } else {
+ result = result + simulationResult;
+ }
+ }
+ result = result + ")";
+ engine.voidEval(result);
+ log.info("Message sent to R : " + result);
+
+ //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 : "
+ + "attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+ engine
+ .voidEval("attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ // Creates the R expression to import results in R
+ String name = simulationStorages.get(0).getParameter()
+ .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()
+ + "\")");
+ log.info("Message sent to R : setwd(\""
+ + outputdirectory.getAbsolutePath() + "\")");
+
+ //Save the results with the scenarios.
+ engine.voidEval("write.csv(dataforaov,\""
+ + simulationStorages.get(0).getParameter()
+ .getSensitivityExport().get(k)
+ .getExportFilename() + "_Results.csv\")");
+ log.info("Message sent to R : write.csv(dataforaov,\""
+ + simulationStorages.get(0).getParameter()
+ .getSensitivityExport().get(k)
+ .getExportFilename() + "_Results.csv\")");
+
+ //Save the sensitivity indices
+ engine.voidEval("write.csv(exportsensitivity,\""
+ + simulationStorages.get(0).getParameter()
+ .getSensitivityExport().get(k)
+ .getExportFilename()
+ + "_SensitivityIndices.csv\")");
+ log.info("Message sent to R : write.csv(exportsensitivity,\""
+ + simulationStorages.get(0).getParameter()
+ .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 + "\"" + ",aovresult)");
+ engine
+ .voidEval("isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\""
+ + aovCall + "\"" + ",aovresult)");
+
+ 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() + "\")");
+ engine.voidEval("setwd(\"" + outputdirectory.getParent() + "\")");
+
+ // Save Isis R session
+ log.info("save.image()");
+ engine.voidEval("save.image()");
+
+ engine.terminate();
+
+ } catch (Exception eee) {
+ eee.printStackTrace();
+ throw new RuntimeException("R evaluation failed", eee);
+ }
+
+ }
+
+ public String getDescription() {
+ return "Implementation of Regular fractions method using R";
+ }
+
+}
Added: trunk/sensitivity/regularfractions.R
===================================================================
--- trunk/sensitivity/regularfractions.R (rev 0)
+++ trunk/sensitivity/regularfractions.R 2009-04-20 16:25:44 UTC (rev 116)
@@ -0,0 +1,211 @@
+#================================================================================
+# FONCTIONS DE CALCUL D'UNE FRACTION REGULIERE DE RESOLUTION DONNEE
+# Auteur: H. Monod, INRA Jouy en Josas
+# Copyright INRA 2009
+# Ce programme est une version preliminaire et simplifiee d'une librairie R
+# en preparation par A. Kobilinsky, H. Monod, A. Bouvier
+#================================================================================
+regular.fraction <- function(s,p,r,resolution){
+ # DESCRIPTION
+ # generates a regular fractional factorial design of given resolution,
+ # for s factors at p levels in p^r units
+ # ARGUMENTS
+ # s : number of input factors
+ # p : unique prime number of levels of all input and unit factors
+ # r : number of unit factors (so that there are N=p^r units)
+ # resolution : resolution of the fraction
+ # max.sol : maximum number of solutions
+ # DETAILS
+ # This is a simplified version of a more general library in preparation.
+ # In this version, all factors must have the same prime number of levels
+ # and only fractions with a given resolution can be constructed. The first
+ # q factors are used as basic factors. The first solution is kept although
+ # it may not be the most interesting one (no control of aberration). This
+ # function is programmed entirely in R and so it is not efficient with respect
+ # to computer time. There is no explicit check on the arguments and so it
+ # is up to the user to restrict p to a prime number such as 2, 3, 5 or 7.
+ # OUTPUT:
+ # a list with two components: plan (the design in base p) and matrice.cle
+ # (the design key). The design has N=p^r rows (units) and s columns (factors).
+ # All its elements are integers modulo p that represent the factor levels.
+
+ # ensemble ineligible
+ cat("Determination des termes ineligibles: ")
+ ineligible <- diag(s)
+ for(reso in 2:(resolution-1)){
+ combis <- combn(s,reso)
+ ncombi <- ncol(combis)
+ select <- cbind( c(combis), rep(seq(ncombi),rep(reso,ncombi)) )
+ ineli <- matrix(0,s,ncombi)
+ ineli[select] <- 1
+ ineligible <- cbind(ineligible,ineli)
+ }
+ cat(ncol(ineligible)," termes ineligibles.\n")
+ if( (p!=2) ){
+ ineligible <- representative.basep(ineligible,p)
+ }
+ # Identification of the last non-zero coefficients in each ineligible trt character
+ ineligible.lnz <- apply(ineligible, 2, function(x){max(seq(along=x)[x!=0])})
+ # initialisation of PhiStar by using the first q factors as basic factors
+ PhiStar <- diag(r)
+ #
+ f <- ncol(PhiStar)
+ if(s == f){
+ check <- !any(apply(((PhiStar %*% ineligible)%%p)==0, 2, all))
+ if(check) return(list(PhiStar))
+ }
+ # Calculation of the set of initially admissible elements of U*
+ admissible <- t(convertinto.basep(seq((p^r)-1),p))
+ nb.admissible <- ncol(admissible)
+ # Backtrack search - preliminaries
+ eeU <- list(length=s-f)
+ leeU <- rep(NA,s-f)
+ neeU <- rep(0,s-f)
+ # Backtrack search
+ cat("Recherche d'une solution (algorithme backtrack).\n")
+ jprev <- 0 ; j <- 1
+ solved <- FALSE
+ while((j > 0)&(!solved)){
+ PhiStar <- PhiStar[,seq(f+j-1), drop=FALSE]
+ if(jprev < j){
+ ineligible.j <- ineligible[ seq(f+j-1), ineligible.lnz==(f+j), drop=FALSE ]
+ admissible.keep <- planor.kernelcheck.basep(PhiStar, admissible, ineligible.j, p)
+ eeU[[j]] <- seq(nb.admissible)[admissible.keep]
+ leeU[j] <- length(eeU[[j]])
+ neeU[j] <- 0
+ }
+ if(neeU[j] < leeU[j]){
+ neeU[j] <- neeU[j]+1
+ newcolj <- (eeU[[j]])[neeU[j]]
+ PhiStar <- cbind(PhiStar,admissible[,newcolj])
+ if(j == (s-f)){
+ cat("Solution obtenue. ")
+ solved <- TRUE
+ jprev <- j ; j <- j
+ }
+ else{
+ jprev <- j ; j <- j+1
+ }
+ }
+ else{
+ jprev <- j ; j <- j-1
+ }
+ }
+ if(solved){
+ # Construction du plan
+ plan <- crossing(rep(p,r),start=0) %*% PhiStar %%p
+ # Sortie
+ out <- list(plan=plan, matrice.cle=PhiStar, p=p)
+ }
+ else{
+ cat("Pas de solution. ")
+ out <- NULL
+ }
+ cat("Recherche terminee.\n")
+ return(out)
+}
+#---------------------------------------------------------------------------
+planor.kernelcheck.basep <- function(PhiStar, admissible, IneligibleSet, p){
+ ImagesIS <- (- PhiStar %*% IneligibleSet)%%p
+ avoid <- convertfrom.basep( t(ImagesIS), p)
+ candidate <- convertfrom.basep( t(admissible), p)
+ test <- !(candidate %in% avoid)
+ return(test)
+}
+#---------------------------------------------------------------------------
+convertinto.basep <- function (x, p) {
+ # Conversion of an integer or integer vector x into base p
+ # The coefficients are ordered by increasing powers of p
+ if (!is.numeric(x))
+ stop("cannot decompose non-numeric arguments")
+ if (length(x) > 1) {
+ l <- matrix(0, length(x), length(Recall(max(x),p)))
+ for(i in seq(along = x)){
+ dec.i <- Recall(x[i],p)
+ l[i, seq(along=dec.i) ] <- dec.i
+ }
+ return(l)
+ }
+ if (x != round(x) || x < 0)
+ return(x)
+ val <- x%%p
+ while ( (x <- x%/%p) > 0 ) {
+ newval <- x%%p
+ val <- c(val,newval)
+ }
+ return(val)
+}
+#---------------------------------------------------------------------------
+convertfrom.basep <- function (x, p) {
+ # Conversion of integers x coded as vectors of coefficients in base p
+ # to classical integers in base 10
+
+ if (!is.numeric(x))
+ stop("cannot recompose non-numeric arguments")
+ if( (max(x)>p) || (min(x)<0) )
+ stop("x must be reduced modulo p")
+ if (is.matrix(x)) {
+ l <- rep(NA, nrow(x))
+ for(i in seq(along = l)){
+ l[i] <- Recall(x[i,],p)
+ }
+ return(l)
+ }
+ val <- sum( x * p^(seq(along=x)-1) )
+ return(val)
+}
+#---------------------------------------------------------------------------
+inverses.basep <- function(p){
+ # Raw calculation of the inverses modulo p
+
+ if(p==2) return(1)
+ else if(p==3) return(c(1,2))
+ products <- outer(seq(2,p-2), seq(2,p-2), "*")%%p
+ inverses <- 1 + apply(products, 1, function(x){ seq(along=x)[x==1] })
+ return( c(1,inverses,p-1) )
+}
+#---------------------------------------------------------------------------
+representative.basep <- function(mat,p){
+ # generates the minimal set of representatives in base p
+ # of the columns x of matrix mat
+
+ mat <- as.matrix(mat)
+ #
+ if(p==2) return(mat %%2)
+ #
+ representative <- NULL
+ for(j in seq(ncol(mat))){
+ x <- mat[,j]
+ select <- seq(x)[x != 0]
+ nbtocross <- length(select)-1
+ if( nbtocross <= 0 ) mat.j <- x
+ else{
+ select <- select[seq(nbtocross)]
+ N <- (p-1)^nbtocross
+ mat.j <- matrix(x, nrow(mat), N)
+ mat.j[select,] <- t( crossing(rep(p-1,nbtocross),start=1) )
+ }
+ representative <- cbind(representative, mat.j)
+ }
+ return(representative %%p)
+}
+#---------------------------------------------------------------------------
+crossing <- function(n,start=1){
+ # Generates all n1 x n2 x ... x ns combinations of size s with n1,...,ns integers
+
+ N <- prod(n)
+ s <- length(n)
+ n <- c(n,1)
+ crosses <- matrix(NA, N, s)
+ for(i in seq(s))
+ {
+ motif <- start + seq(n[s+1-i])-1
+ repet1 <- rep( prod(n[s+1-i+seq(i)]), n[s+1-i] )
+ if(i==s){ repet2 <- 1 }
+ else{ repet2 <- prod(n[seq(s-i)]) }
+ crosses[,s-i+1] <- rep( rep( motif, repet1 ), repet2 )
+ }
+ return(crosses)
+}
+#---------------------------------------------------------------------------
+
1
0
Author: jcouteau
Date: 2009-04-20 13:40:15 +0000 (Mon, 20 Apr 2009)
New Revision: 115
Modified:
trunk/sensitivity/SensitivityCalculatorJavaExpandGrid.java
trunk/sensitivity/SensitivityCalculatorRMorris.java
Log:
Expand Grid conform to CDC, fixed bug on Morris (in R).
Modified: trunk/sensitivity/SensitivityCalculatorJavaExpandGrid.java
===================================================================
--- trunk/sensitivity/SensitivityCalculatorJavaExpandGrid.java 2009-04-20 08:28:32 UTC (rev 114)
+++ trunk/sensitivity/SensitivityCalculatorJavaExpandGrid.java 2009-04-20 13:40:15 UTC (rev 115)
@@ -28,10 +28,10 @@
import org.codelutin.util.FileUtil;
import fr.ifremer.isisfish.datastore.SimulationStorage;
+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.AbstractSensitivityCalculator;
import fr.ifremer.isisfish.simulator.sensitivity.SensitivityException;
import fr.ifremer.isisfish.simulator.sensitivity.SensitivityScenarios;
import fr.ifremer.isisfish.simulator.sensitivity.domain.ContinuousDomain;
@@ -68,24 +68,26 @@
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) {
+ if (((ContinuousDomain) factors.get(i).getDomain())
+ .getCardinality() != 0) {
k = k
- * ((ContinuousDomain) factors
- .get(i).getDomain()).getCardinality();
+ * ((ContinuousDomain) factors.get(i).getDomain())
+ .getCardinality();
}
} else if (factors.get(i).getDomain() instanceof DiscreteDomain) {
- if (((DiscreteDomain) factors.get(i)
- .getDomain()).getValues().size() != 0) {
+ if (((DiscreteDomain) factors.get(i).getDomain()).getValues()
+ .size() != 0) {
k = k
- * ((DiscreteDomain) factors
- .get(i).getDomain()).getValues().size();
+ * ((DiscreteDomain) factors.get(i).getDomain())
+ .getValues().size();
}
}
}
@@ -104,8 +106,8 @@
.getMaxBound();
Double min = ((ContinuousDomain) factor.getDomain())
.getMinBound();
- int card = ((ContinuousDomain) factor
- .getDomain()).getCardinality();
+ int card = ((ContinuousDomain) factor.getDomain())
+ .getCardinality();
result = (int) Math.floor(rest / card);
rest = rest - (card * result);
@@ -118,8 +120,8 @@
}
}
if (factor.getDomain() instanceof DiscreteDomain) {
- int card = ((DiscreteDomain) factor
- .getDomain()).getValues().size();
+ int card = ((DiscreteDomain) factor.getDomain())
+ .getValues().size();
result = (int) Math.floor(rest / card);
rest = rest - (card * result);
factor.setValueForIdentifier(rest);
@@ -141,13 +143,26 @@
REngine engine = new RProxy();
try {
- //Create the factors vectors
+
+ //Set working directory to get Isis R session
+ log.info("setwd(\"" + outputdirectory.getParent() + "\")");
+ engine.voidEval("setwd(\"" + outputdirectory.getParent() + "\")");
+
+ //Get Isis R session
+ log.info("load(\".RData\")");
+ engine.voidEval("load(\".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);
+ Factor factor = thisExperimentScenarios.get(0).getFactors()
+ .get(j);
if (factor.getDomain() instanceof EquationContinuousDomain) {
- String vector = "factor" + j + "<-c(";
+ //String vector = "factor" + j + "<-c(";
+ String vector = factor.getName().replaceAll(" ", "")
+ + "<-c(";
for (int i = 0; i < scenariosNumber; i++) {
if (i < (scenariosNumber - 1)) {
vector = vector
@@ -166,7 +181,9 @@
engine.voidEval(vector);
log.info("Message sent to R : " + vector);
} else if (factor.getDomain() instanceof MatrixContinuousDomain) {
- String vector = "factor" + j + "<-c(";
+ //String vector = "factor" + j + "<-c(";
+ String vector = factor.getName().replaceAll(" ", "")
+ + "<-c(";
for (int i = 0; i < scenariosNumber; i++) {
if (i < (scenariosNumber - 1)) {
vector = vector
@@ -185,7 +202,9 @@
engine.voidEval(vector);
log.info("Message sent to R : " + vector);
} else {
- String vector = "factor" + j + "<-c(";
+ //String vector = "factor" + j + "<-c(";
+ String vector = factor.getName().replaceAll(" ", "")
+ + "<-c(";
for (int i = 0; i < scenariosNumber; i++) {
if (i < (scenariosNumber - 1)) {
vector = vector
@@ -204,16 +223,13 @@
log.info("Message sent to R : " + vector);
}
- }
-
- //Create the data data.frame from the factors
- String dataframe = "data<-data.frame(";
- for (int j = 0; j < factorNumber; j++) {
if (j < factorNumber - 1) {
- dataframe = dataframe + "factor" + j + "=factor(factor" + j
- + "),";
+ dataframe = dataframe
+ + factor.getName().replaceAll(" ", "") + "=factor("
+ + factor.getName().replaceAll(" ", "") + "),";
} else {
- dataframe = dataframe + "factor" + j + "=factor(factor" + j
+ dataframe += factor.getName().replaceAll(" ", "")
+ + "=factor(" + factor.getName().replaceAll(" ", "")
+ "))";
}
@@ -254,6 +270,46 @@
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 : "
+ + "attributes(isis.MethodExp)<-list(nomModel=\"isis-fish-externe-R\")");
+ engine
+ .voidEval("attributes(isis.MethodExp)<-list(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 : "
+ + "attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+ engine
+ .voidEval("attributes(isis.simule)<-list(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() + "\")");
+ engine.voidEval("setwd(\"" + outputdirectory.getParent() + "\")");
+
+ // Save Isis R session
+ log.info("save.image()");
+ engine.voidEval("save.image()");
+
engine.terminate();
} catch (Exception e) {
@@ -270,39 +326,44 @@
REngine engine = new RProxy();
try {
- /*int scenariosNumber = sensitivityScenarios.getScenarios().size();
- int factorNumber = sensitivityScenarios.getScenarios().get(0)
- .getFactors().size();*/
+ //Set working directory to get Isis R session
+ log.info("setwd(\"" + outputdirectory.getParent() + "\")");
+ engine.voidEval("setwd(\"" + outputdirectory.getParent() + "\")");
+ //Get Isis R session
+ log.info("load(\".RData\")");
+ engine.voidEval("load(\".RData\")");
+
+ // Set output directory
+ engine.voidEval("setwd(\"" + outputdirectory.getAbsolutePath()
+ + "\")");
+ log.info("Message sent to R : setwd(\""
+ + outputdirectory.getAbsolutePath() + "\")");
+
+ //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();
+
int sensitivityNumber = simulationStorages.get(0).getParameter()
.getSensitivityExport().size();
for (int k = 0; k < sensitivityNumber; k++) {
- // Set output directory
- engine.voidEval("setwd(\"" + outputdirectory.getAbsolutePath()
- + "\")");
- log.info("Message sent to R : setwd(\""
- + outputdirectory.getAbsolutePath() + "\")");
+ String name = simulationStorages.get(0).getParameter()
+ .getSensitivityExport().get(k).getExportFilename();
- //Get back the scenarios
- //engine.voidEval("factors<-read.csv(\".expandgrid.csv\",row.names=1,col.names=1)");
- 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();
- //factorNumber=factorNumber-1;
-
//Create the results vectors
- String result = "result<-c(";
+ String result = name + "<-c(";
for (int l = 0; l < simulationStorages.size(); l++) {
File importFile = new File(simulationStorages.get(l)
.getDirectory().toString()
@@ -326,18 +387,48 @@
engine.voidEval(result);
log.info("Message sent to R : " + result);
+ //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 : "
+ + "attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+ engine
+ .voidEval("attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ // Creates the R expression to import results in R
+ String name = simulationStorages.get(0).getParameter()
+ .getSensitivityExport().get(k).getExportFilename();
+
//Create the dataforaov data.frame
- String dataframe = "dataforaov<-data.frame(factors,result=result)";
+ String dataframe = "dataforaov<-data.frame(factors," + name
+ + "=" + name + ")";
engine.voidEval(dataframe);
log.info("Message sent to R : " + dataframe);
//Call aov()
- String aovCall = "aovresult<-aov(result~";
+ 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 + "factor" + j + "+";
+ aovCall = aovCall
+ + engine
+ .eval("names(factors)[" + (j + 2) + "]")
+ + "+";
} else {
- aovCall = aovCall + "factor" + j + ",data=dataforaov)";
+ aovCall = aovCall
+ + engine
+ .eval("names(factors)[" + (j + 2) + "]")
+ + ",data=dataforaov)";
}
}
engine.voidEval(aovCall);
@@ -420,10 +511,65 @@
.getExportFilename()
+ "_SensitivityIndices.csv\")");
//FIXME export through java to enable export when using Rserve (when distant Rserve).
- engine.terminate();
+
+ //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 + "\"" + ",aovresult)");
+ engine
+ .voidEval("isis.methodAnalyse<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"isis.simule\"=isis.simule,call_method=\""
+ + aovCall + "\"" + ",aovresult)");
+
+ 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));
+
}
- log.info("end");
+ //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() + "\")");
+ engine.voidEval("setwd(\"" + outputdirectory.getParent() + "\")");
+
+ // Save Isis R session
+ log.info("save.image()");
+ engine.voidEval("save.image()");
+
+ engine.terminate();
+
} catch (Exception e) {
e.printStackTrace();
// Error while processing
Modified: trunk/sensitivity/SensitivityCalculatorRMorris.java
===================================================================
--- trunk/sensitivity/SensitivityCalculatorRMorris.java 2009-04-20 08:28:32 UTC (rev 114)
+++ trunk/sensitivity/SensitivityCalculatorRMorris.java 2009-04-20 13:40:15 UTC (rev 115)
@@ -318,8 +318,7 @@
engine.voidEval("factornames<-dget(\".factornames\")");
log.info("Message sent to R : "
+ "factornames<-dget(\".factornames\")");
-
- /*int scenariosNumber = sensitivityScenarios.getScenarios().size();*/
+
int scenariosNumber = ((Double) engine
.eval("length(a$X)/length(a$factors)")).intValue();
log.info("Message sent to R : " + "length(a$X)/length(a$factors)");
@@ -359,10 +358,39 @@
// 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 : "
+ + "attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+ engine
+ .voidEval("attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
+
+ for (int k = 0; k < sensitivityNumber; k++) {
+
+ // Creates the R expression to import results in R
+ String name = simulationStorages.get(0).getParameter()
+ .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 + ")" + "\",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 + ")" + "\",a)");
+
// 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)");
@@ -429,35 +457,6 @@
.getExportFilename() + "_Results.csv\")");
//FIXME export through java to enable export when using Rserve
- //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 : "
- + "attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
- engine
- .voidEval("attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
-
- for (int k = 0; k < sensitivityNumber; k++) {
-
- // Creates the R expression to import results in R
- String name = simulationStorages.get(0).getParameter()
- .getSensitivityExport().get(k).getExportFilename();
-
- //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 + ")" + "\",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 + ")" + "\",a)");
-
String renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-isis.methodAnalyse";
String simulationName = simulationStorages.get(0).getName()
.replaceAll("-", "");
1
0
Author: jcouteau
Date: 2009-04-20 08:28:32 +0000 (Mon, 20 Apr 2009)
New Revision: 114
Modified:
trunk/sensitivity/SensitivityCalculatorRMorris.java
Log:
Morris method managing more than one export (in R)
Modified: trunk/sensitivity/SensitivityCalculatorRMorris.java
===================================================================
--- trunk/sensitivity/SensitivityCalculatorRMorris.java 2009-04-18 13:12:30 UTC (rev 113)
+++ trunk/sensitivity/SensitivityCalculatorRMorris.java 2009-04-20 08:28:32 UTC (rev 114)
@@ -58,6 +58,7 @@
* Last update : $Date$ By :
* $Author$
*/
+
@Doc("Morris method")
public class SensitivityCalculatorRMorris extends AbstractSensitivityCalculator {
@@ -217,9 +218,9 @@
log
.info("Message sent to R : "
- + "isis.MethodExp<-list(isis.factors,isis.factor.distribution,call)");
+ + "isis.MethodExp<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"call\"=call)");
engine
- .voidEval("isis.MethodExp<-list(isis.factors,isis.factor.distribution,call)");
+ .voidEval("isis.MethodExp<-list(\"isis.factors\"=isis.factors,\"isis.factor.distribution\"=isis.factor.distribution,\"call\"=call)");
log
.info("Message sent to R : "
@@ -359,8 +360,8 @@
engine.voidEval(rInstruction);
//Compute results
- engine.voidEval("tell(a,y=name)");
- log.info("Message sent to R : " + "tell(a,y=name)");
+ engine.voidEval("tell(a,y=" + name + ")");
+ log.info("Message sent to R : " + "tell(a,y=" + name + ")");
// Get back the sensitivity results, mu, mu star and sigma.
engine.voidEval("mu<-apply(a$ee, 2, mean)");
@@ -433,7 +434,6 @@
+ ")");
log.info("Message sent to R : "
+ "isis.simule<-data.frame(isis.simule," + name + ")");
-
}
//adding attribute to isis.Simule
@@ -443,20 +443,38 @@
engine
.voidEval("attributes(isis.simule)<-list(nomModel=\"isis-fish-externe-R\")");
- //creating isis.methodAnalyse
- log
- .info("Message sent to R : "
- + "isis.methodAnalyse<-list(isis.factor,isis.factor.distribution,isis.simule,call_method=\"tell(a,results)\",a)");
- engine
- .voidEval("isis.methodAnalyse<-list(isis.factor,isis.factor.distribution,isis.simule,call_method=\"tell(a,results)\",a)");
+ for (int k = 0; k < sensitivityNumber; k++) {
+ // Creates the R expression to import results in R
+ String name = simulationStorages.get(0).getParameter()
+ .getSensitivityExport().get(k).getExportFilename();
+
+ //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 + ")" + "\",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 + ")" + "\",a)");
+
+ 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 renameIsisMethodAnalyse = "%s.isis.methodAnalyse<-isis.methodAnalyse";
String renameIsisFactorDistribution = "%s.isis.factor.distribution<-isis.factor.distribution";
- String renameIsisFactor = "%s.isis.factor<-isis.factor";
- String renameIsisMethodExp = "%s.isis.methodExp<-isis.methodExp";
+ String renameIsisFactor = "%s.isis.factor<-isis.factors";
+ String renameIsisMethodExp = "%s.isis.methodExp<-isis.MethodExp";
String simulationName = simulationStorages.get(0).getName()
.replaceAll("-", "");
@@ -466,11 +484,6 @@
engine.voidEval(String.format(renameIsisSimule, simulationName));
log.info("Message sent to R : "
- + String.format(renameIsisMethodAnalyse, simulationName));
- engine.voidEval(String.format(renameIsisMethodAnalyse,
- simulationName));
-
- log.info("Message sent to R : "
+ String.format(renameIsisFactorDistribution,
simulationName));
engine.voidEval(String.format(renameIsisFactorDistribution,
1
0
Author: jcouteau
Date: 2009-04-18 13:12:30 +0000 (Sat, 18 Apr 2009)
New Revision: 113
Modified:
trunk/exports/SensitivityBiomassReferenceY9.java
trunk/exports/SensitivityBiomassRelativeReferenceY12.java
trunk/exports/SensitivityCapturesWeightReferenceY7.java
trunk/exports/SensitivityCapturesWeightRelativeReferenceY10.java
trunk/exports/SensitivityGenitorBiomassReferenceY8.java
trunk/exports/SensitivityGenitorBiomassRelativeReferenceY11.java
Log:
Fixed resultStorage bug on exports
Modified: trunk/exports/SensitivityBiomassReferenceY9.java
===================================================================
--- trunk/exports/SensitivityBiomassReferenceY9.java 2009-04-17 13:51:32 UTC (rev 112)
+++ trunk/exports/SensitivityBiomassReferenceY9.java 2009-04-18 13:12:30 UTC (rev 113)
@@ -7,6 +7,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codelutin.math.matrix.MatrixND;
+import org.codelutin.topia.TopiaContext;
import scripts.ResultName;
import fr.ifremer.isisfish.datastore.ResultStorage;
@@ -43,6 +44,8 @@
Double biomass = 0.0;
Double referenceBiomass = 0.0;
+ System.out.println("reference simul : " + param_referenceSimulation);
+
for (Population pop : simulation.getParameter().getPopulations()) {
if (pop.getName().equals(param_pop.getName())) {
@@ -50,14 +53,26 @@
MatrixND matlastdate = resultStorage.getMatrix(lastDate, pop,
ResultName.MATRIX_BIOMASS);
biomass = matlastdate.sumAll();
+ System.out.println("matlastdate:" + (Object) matlastdate);
- //Get the reference biomass of the last time step
+ TopiaContext tx = referenceSimulation.getStorage()
+ .beginTransaction();
+
MatrixND matreferencelastdate = referenceResultStorage
- .getMatrix(lastDate, pop, ResultName.MATRIX_BIOMASS);
+ .getMatrix(lastDate, ResultName.MATRIX_BIOMASS + " "
+ + pop, tx);
referenceBiomass = matreferencelastdate.sumAll();
+ tx.commitTransaction();
+ tx.closeContext();
}
}
+ 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));
Modified: trunk/exports/SensitivityBiomassRelativeReferenceY12.java
===================================================================
--- trunk/exports/SensitivityBiomassRelativeReferenceY12.java 2009-04-17 13:51:32 UTC (rev 112)
+++ trunk/exports/SensitivityBiomassRelativeReferenceY12.java 2009-04-18 13:12:30 UTC (rev 113)
@@ -7,6 +7,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codelutin.math.matrix.MatrixND;
+import org.codelutin.topia.TopiaContext;
import scripts.ResultName;
import fr.ifremer.isisfish.datastore.ResultStorage;
@@ -30,7 +31,7 @@
public Population param_pop;
@Doc("Name of the reference simulation")
- public String param_referenceSimulation="";
+ public String param_referenceSimulation = "";
@Override
public void export(SimulationStorage simulation, Writer out)
@@ -61,14 +62,23 @@
biomass = matlastdate.sumAll();
//Get the biomass on december of the first year
+ TopiaContext tx = referenceSimulation.getStorage()
+ .beginTransaction();
MatrixND matfirstdatereference = referenceResultStorage
- .getMatrix(firstDate, pop, ResultName.MATRIX_BIOMASS);
+ .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, pop, ResultName.MATRIX_BIOMASS);
+ .getMatrix(lastDate, ResultName.MATRIX_BIOMASS + " "
+ + pop, tx);
biomassReference = matlastdatereference.sumAll();
+ tx.commitTransaction();
+ tx.closeContext();
}
}
Modified: trunk/exports/SensitivityCapturesWeightReferenceY7.java
===================================================================
--- trunk/exports/SensitivityCapturesWeightReferenceY7.java 2009-04-17 13:51:32 UTC (rev 112)
+++ trunk/exports/SensitivityCapturesWeightReferenceY7.java 2009-04-18 13:12:30 UTC (rev 113)
@@ -7,6 +7,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codelutin.math.matrix.MatrixND;
+import org.codelutin.topia.TopiaContext;
import scripts.ResultName;
import fr.ifremer.isisfish.datastore.ResultStorage;
@@ -29,7 +30,7 @@
public Population param_pop;
@Doc("Name of the reference simulation")
- public String param_referenceSimulation="";
+ public String param_referenceSimulation = "";
@Override
public void export(SimulationStorage simulation, Writer out)
@@ -56,12 +57,16 @@
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),
- pop,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP
+ + " " + pop, tx);
capturesWeightReference += matlastdatereference.sumAll();
+ tx.commitTransaction();
+ tx.closeContext();
}
Modified: trunk/exports/SensitivityCapturesWeightRelativeReferenceY10.java
===================================================================
--- trunk/exports/SensitivityCapturesWeightRelativeReferenceY10.java 2009-04-17 13:51:32 UTC (rev 112)
+++ trunk/exports/SensitivityCapturesWeightRelativeReferenceY10.java 2009-04-18 13:12:30 UTC (rev 113)
@@ -7,6 +7,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codelutin.math.matrix.MatrixND;
+import org.codelutin.topia.TopiaContext;
import scripts.ResultName;
import fr.ifremer.isisfish.datastore.ResultStorage;
@@ -67,21 +68,27 @@
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),
- pop,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ 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),
- pop,
- ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP);
+ ResultName.MATRIX_CATCH_WEIGHT_PER_STRATEGY_MET_PER_ZONE_POP
+ + " " + pop, tx);
capturesWeightfirstreference += matfirstdatereference
.sumAll();
+ tx.commitTransaction();
+ tx.closeContext();
}
}
}
Modified: trunk/exports/SensitivityGenitorBiomassReferenceY8.java
===================================================================
--- trunk/exports/SensitivityGenitorBiomassReferenceY8.java 2009-04-17 13:51:32 UTC (rev 112)
+++ trunk/exports/SensitivityGenitorBiomassReferenceY8.java 2009-04-18 13:12:30 UTC (rev 113)
@@ -8,6 +8,7 @@
import org.apache.commons.logging.LogFactory;
import org.codelutin.math.matrix.MatrixIterator;
import org.codelutin.math.matrix.MatrixND;
+import org.codelutin.topia.TopiaContext;
import scripts.ResultName;
import fr.ifremer.isisfish.datastore.ResultStorage;
@@ -62,8 +63,10 @@
}
//Get the reference biomass of the last time step
+ TopiaContext tx = referenceSimulation.getStorage()
+ .beginTransaction();
MatrixND matlastdatereference = referenceResultStorage
- .getMatrix(pop, ResultName.MATRIX_BIOMASS);
+ .getMatrix(ResultName.MATRIX_BIOMASS + " " + pop, tx);
for (MatrixIterator i = matlastdatereference.iterator(); i
.hasNext();) {
i.next();
@@ -75,6 +78,8 @@
* group.getReproductionRate();
}
}
+ tx.commitTransaction();
+ tx.closeContext();
}
}
out.write(Double.toString(biomass / referenceBiomass));
Modified: trunk/exports/SensitivityGenitorBiomassRelativeReferenceY11.java
===================================================================
--- trunk/exports/SensitivityGenitorBiomassRelativeReferenceY11.java 2009-04-17 13:51:32 UTC (rev 112)
+++ trunk/exports/SensitivityGenitorBiomassRelativeReferenceY11.java 2009-04-18 13:12:30 UTC (rev 113)
@@ -8,6 +8,7 @@
import org.apache.commons.logging.LogFactory;
import org.codelutin.math.matrix.MatrixIterator;
import org.codelutin.math.matrix.MatrixND;
+import org.codelutin.topia.TopiaContext;
import scripts.ResultName;
import fr.ifremer.isisfish.datastore.ResultStorage;
@@ -81,8 +82,10 @@
}
//Get the reference biomass of the first time step
+ TopiaContext tx = referenceSimulation.getStorage()
+ .beginTransaction();
MatrixND matfirstdatereference = referenceResultStorage
- .getMatrix(pop, ResultName.MATRIX_BIOMASS);
+ .getMatrix(ResultName.MATRIX_BIOMASS + " " + pop, tx);
for (MatrixIterator i = matfirstdatereference.iterator(); i
.hasNext();) {
i.next();
@@ -97,7 +100,7 @@
//Get the reference biomass of the last time step
MatrixND matlastdatereference = referenceResultStorage
- .getMatrix(pop, ResultName.MATRIX_BIOMASS);
+ .getMatrix(ResultName.MATRIX_BIOMASS + " " + pop, tx);
for (MatrixIterator i = matlastdatereference.iterator(); i
.hasNext();) {
i.next();
@@ -109,6 +112,8 @@
* group.getReproductionRate();
}
}
+ tx.commitTransaction();
+ tx.closeContext();
}
}
out.write(Double.toString((biomass / firstbiomass)
1
0