/* * #%L * IsisFish data * %% * Copyright (C) 2006 - 2014 Ifremer, CodeLutin, * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * . * #L% */ package rules; import fr.ifremer.isisfish.datastore.ResultStorage; import fr.ifremer.isisfish.entities.EffortDescription; import fr.ifremer.isisfish.entities.Metier; import fr.ifremer.isisfish.entities.MetierSeasonInfo; import fr.ifremer.isisfish.entities.Population; import fr.ifremer.isisfish.entities.PopulationGroup; import fr.ifremer.isisfish.entities.Result; import fr.ifremer.isisfish.entities.Species; import fr.ifremer.isisfish.entities.Strategy; import fr.ifremer.isisfish.entities.TargetSpecies; import fr.ifremer.isisfish.entities.Zone; import fr.ifremer.isisfish.rule.AbstractRule; import fr.ifremer.isisfish.simulator.PopulationMonitor; import fr.ifremer.isisfish.simulator.ResultManager; import fr.ifremer.isisfish.simulator.SimulationContext; import fr.ifremer.isisfish.types.Month; import fr.ifremer.isisfish.types.TimeStep; import fr.ifremer.isisfish.entities.*; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuiton.math.matrix.MatrixFactory; import org.nuiton.math.matrix.MatrixIterator; import org.nuiton.math.matrix.MatrixND; import org.nuiton.topia.*; import org.nuiton.util.*; //import scripts.ResultName; import scripts.PTAtoolbox; import scripts.RuleUtil; import scripts.SiMatrix; import resultinfos.*; import fr.ifremer.isisfish.annotations.Doc; /** * Cette regles tient compte de la taille minimum des poissons capturable. * * Created: 30 novembre 2006 * * @author smahevas * @version $Revision: 1.1 $ * * Last update: $Date: 2007-01-24 18:25:34 $ by : $Author: bpoussin $ */ public class TACseries_Metier_OptionLO_redistr extends AbstractRule { /** to use log facility, just put in your code: log.info("..."); */ static private Log log = LogFactory.getLog(TACseries_Metier_OptionLO_redistr.class); @Doc(value = "Begin step") public TimeStep param_beginStep = new TimeStep(12); @Doc(value = "End date") public TimeStep param_endStep = new TimeStep(193); @Doc(value = "Affected population") public Population param_pop = null; @Doc(value = "Elements of affected Metiers names separated by | ") public String param_metNames = "OTMPIL|PS_PIL|PTMPIL"; // "PS_ANE_PIL" @Doc(value = "TAC allocation (as a ratio)") public double param_alloc = 0.6; @Doc(value = "If 0, TAC is computed elsewhere, tacName must be filled to retrieve value, otherwise enter TAC in kg time series separated by ; for ISIS fleets") public String param_tacInKgs = "0"; @Doc(value = "If tacInKgs = 0, TAC is computed elsewhere and stored in simulation context into this name") public String param_tacName = "TACisis_"; @Doc(value = "Proportion survival of discards") public double param_propSurvie = 0; @Doc(value = "Landings Obligation Implemented ?") public boolean param_LandingsObligation = true; public boolean param_DeMinimis = false; protected boolean affectation = false; int nbY = param_endStep.getYear() - param_beginStep.getYear()+1 ; protected double [] tacSeries ;//= new double[nbY]; List listMetNames; List listMet = new ArrayList(); protected MatrixND TacPopMatrix; protected String[] necessaryResult = { // put here all necessary result for this rule MatrixCatchPerStrategyMetPerZonePop.NAME, MatrixLandingPerMet.NAME, MatrixLandingWeight.NAME, MatrixTacPerPop.NAME, MatrixDiscardsPerStrMetPerZonePop.NAME // ResultName.MATRIX_BIOMASS, // ResultName.MATRIX_NET_VALUE_OF_LANDINGS_PER_STRATEGY_MET, }; @Override public String[] getNecessaryResult() { return this.necessaryResult; } /** * Permet d'afficher a l'utilisateur une aide sur la regle. * * @return L'aide ou la description de la regle */ @Override public String getDescription() throws Exception { return "Implement Quota for the selected metiers using provided annual values. If TAc = 0, uses values from the simulationContext. Saves month when fishing stops in a matrix."; } /** * Appele au demarrage de la simulation, cette methode permet * d'initialiser des valeurs de la * * @param context La simulation pour laquelle on utilise cette regle */ @Override public void init(SimulationContext context) throws Exception { SiMatrix siMatrix = SiMatrix.getSiMatrix(context); TimeStep date = new TimeStep(0); // Add TAC values to a vector indexed by TAC year (from TAC starting year on) String[] StrTacSeries = param_tacInKgs.split(";"); tacSeries = new double[StrTacSeries.length]; for ( int i = 0 ; i < StrTacSeries.length; i++) { //for ( int i = 0 ; i < tacSeries.length; i++) { if(param_tacInKgs == "0"){ tacSeries[i] = 0 ; }else { tacSeries[i] = Double.parseDouble(StrTacSeries[i]); } } // Add metier names to a list //String[] StrMetNames = param_metNames.split(";"); //listMetNames = new ArrayList(Arrays.asList(StrMetNames)); //listMet = new ArrayList(); List allMets = context.getMetierDAO().findAll(); Pattern countryPattern = Pattern.compile(param_metNames); for(Metier met : allMets){ Matcher metMatch = countryPattern.matcher(met.getName()); if (metMatch.matches()){ listMet.add((Metier) met); listMetNames.add(met.getName());} } System.out.println("on affiche listMet"); for(Metier met : listMet){ System.out.println(met.getName() + " is in listMet"); } } /** * @param context * @param date * @param param_species * @param metier * @return */ private boolean isCaptureDate(TimeStep step, Species species, Metier metier) { MetierSeasonInfo info = metier.getMetierSeasonInfo(step.getMonth()); TargetSpecies target = info.getSpeciesTargetSpecies(species); boolean result; if (target != null) { result = true; } else { result = false; } return result; } /** * La condition qui doit etre vrai pour faire les actions. * * @param context la simulation pour lequel on utilise cette regle * @param step le pas de temps courant * @param metier le metier concerne * @return vrai si on souhaite que les actions soit faites */ @Override public boolean condition(SimulationContext context, TimeStep step, Metier metier) throws Exception { boolean result = false; //if(listMetNames.contains(metier.getName())){ if(listMet.contains(metier)){ System.out.println("Condition true for :"+ metier.getName()); if (step.before(param_beginStep)) { result = false; } else if (step.after(param_endStep)) { result = false; }else {result = true;} } return result; } /** * Si la condition est vrai alors cette action est executee avant le pas de * temps de la simulation. * * @param context la simulation pour lequel on utilise cette regle * @param step le pas de temps courant * @param metier le metier concerne */ @Override public void preAction(SimulationContext context, TimeStep step, Metier metier) throws Exception { log.info ("enters preact for metier "+metier.getName()); if(context.getValue(metier.getName()+param_pop.getName()+"flag") != null && (int) context.getValue(metier.getName()+param_pop.getName()+"flag") == 2){ // context.getMetierMonitor().addforbiddenMetier(metier); log.info("added to forbidden met"); //recupere toutes les strategies pratiquant le metier et pour lesquelles la proportion !=0 SiMatrix siMatrix = SiMatrix.getSiMatrix(context); Set strs = new HashSet<>(); for (Strategy str : siMatrix.getStrategies(step)) { double prop = str.getStrategyMonthInfo(step.getMonth()) .getProportionMetier(metier); if (prop != 0) { strs.add(str); } } for (Strategy str : strs) { StrategyMonthInfo smi = str.getStrategyMonthInfo(step .getMonth()); // list metiers of the strategie with prop !=0 Set possibleMetier = new HashSet<>(); for (EffortDescription effort : str.getSetOfVessels() .getPossibleMetiers()) { Metier newMetier = effort.getPossibleMetiers(); if (smi.getProportionMetier(newMetier) != 0) { possibleMetier.add(newMetier); } } if (possibleMetier != null) { // on repartit maintenant l'effort entre les differents metiers // possibles dans la meme strategie si un metier possible existe // bien la repartion est proportionnelle a l'effort deja alloue // dans la strategie double somme = 0; for (Metier met : possibleMetier) { somme += smi.getProportionMetier(met); } 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 log.info("[TAC] il y a des metiers possibles"); }else { smi.getProportionMetier().setValue(metier, 0); } } } affectation = true; } /** * Si la condition est vrai alors cette action est executee apres le pas * de temps de la simulation. * * @param context La simulation pour lequel on utilise cette regle * @param step le pas de temps courant * @param metier le metier concerne */ @Override public void postAction(SimulationContext context, TimeStep step, Metier metier) throws Exception { if (affectation) { double prevLandings = 0; double catchMonth = 0; double currentCatch = 0; double ratio = 0; PopulationMonitor popMon = context.getPopulationMonitor(); ResultManager resManager = context.getResultManager(); if(context.getValue("TACatteint"+param_pop.getName()+param_metNames)==null || !(Boolean) context.getValue("TACatteint"+param_pop.getName()+param_metNames)){ log.info( "TAC pas encore atteint jusqu ici, test"); // Retrieve TAC value and allocation to the set of metiers double TAC = 0; int tacYear = step.getYear() - param_beginStep.getYear(); if (tacSeries[tacYear] != 0){ TAC = tacSeries[tacYear]; }else if(context.getValue(param_tacName+param_pop.getName()) != null){ // TAC is computed elsewhere TAC = (Double) context.getValue(param_tacName+ param_pop.getName()); }else TAC = 0; TAC = TAC * param_alloc; log.info("TAC value" + TAC); // Compute landings until last step for the set of metiers int year = step.getYear(); ResultStorage matResult = context.getSimulationStorage().getResultStorage(); for (TimeStep dat = new TimeStep(0); dat.before(step); dat = dat.next()) { if( dat.getYear() == year) { MatrixND mat = matResult.getMatrix(dat, param_pop, MatrixLandingWeight.NAME); double catchListMet = 0; for(Metier met : listMet){ prevLandings += mat.getSubMatrix(1,met).sumAll(); } } } // Add catch of the current month String TMP = "tmp"; MatrixND mat = popMon.getCatch(param_pop).copy(); SiMatrix siMatrix = SiMatrix.getSiMatrix(context); MatrixND matW = siMatrix.matrixToWeightMatrix(step, 2, TMP, mat); for(Metier met : listMet){ catchMonth += matW.getSubMatrix(1,met).sumAll(); } currentCatch = prevLandings + catchMonth; // compare TAC and landings log.info("[TAC] landings = " + currentCatch+ " >= TAC:" + TAC); if (currentCatch >= TAC) { context.setValue("TACatteint"+param_pop.getName()+param_metNames,true); log.info("tac atteint for " +param_metNames); ratio = (TAC-prevLandings)/catchMonth; // flag metiers and set price to 0 // metier flag = 0 si pas concern par le TAC ou tac pas atteint // metier flag = 1 si TAC atteint et rejet // metier flag = 2 si TAC atteint et interdit if(param_LandingsObligation){ context.setValue("priceSwitch"+param_pop.getName(),1); // strict application for (Metier met : listMet){ log.info("loop metier flag : "+met.getName()); context.setValue(met.getName()+param_pop.getName()+"flag",2); } }else { for (Metier met : listMet){ context.setValue(met.getName()+param_pop.getName()+"flag",1); } } //---------------------------------------------------------------------------------------------------- // Store infos in MatrixTacPerPop // add the month when TAC was reached to Matrix TAC per pop // Store infos in MatrixTacPerPop if(TacPopMatrix == null){ TacPopMatrix = MatrixFactory.getInstance().create( MatrixTacPerPop.NAME, //new List[] { Arrays.asList(new String[]{"TAC0","listMetcatch0","ratio0","TAC1","listMetcatch1","ratio1"})}); new List[] { Arrays.asList(new String[]{"TAC","catchMonth","prevLandings","ratio","Year","TACreachedMonth"})}); } TacPopMatrix.setValue("TAC", TAC); TacPopMatrix.setValue("catchMonth", catchMonth); TacPopMatrix.setValue("prevLandings", prevLandings); TacPopMatrix.setValue("ratio", ratio); TacPopMatrix.setValue("Year", year); TacPopMatrix.setValue("TACreachedMonth", step.getMonth().getMonthNumber()); TacPopMatrix.setName(MatrixTacPerPop.NAME+param_metNames); //matResult.addResult(step, param_pop, TacPopMatrix); matResult.addResult(true,step,param_pop,TacPopMatrix); } } // fin du test de TAC // Le TAC est atteint if(context.getValue("TACatteint"+param_pop.getName()+param_metNames)!=null && (Boolean) context.getValue("TACatteint"+param_pop.getName()+param_metNames)){ // rejet ou reajustement des captures MatrixND eff = popMon.getN(param_pop); MatrixND cat = popMon.getCatch(param_pop); MatrixND discard = popMon.getDiscard(step, param_pop); // if the matrix does not exist it is created with the same format as catch if(discard == null){ discard = popMon.getCatch(param_pop).copy().mults(0); discard.setName(MatrixDiscardsPerStrMetPerZonePop.NAME); } for (MatrixIterator i = cat.iteratorNotZero(); i.next();) { Object[] coordonnees = i.getSemanticsCoordinates(); Strategy str = (Strategy) coordonnees[0]; Metier met = (Metier) coordonnees[1]; PopulationGroup group = (PopulationGroup) coordonnees[2]; Zone zone = (Zone)coordonnees[3]; if(listMet.contains(met)){ log.info(met.getName()); if(param_LandingsObligation) { eff.setValue(group, zone,eff.getValue(group, zone)+ i.getValue() * (1-ratio)); i.setValue(i.getValue()*ratio); }else{ //discard, catch not modified discard.setValue(str,met,group,zone,i.getValue()*(1-ratio)); if (param_propSurvie > 0) { eff.setValue(group, zone,eff.getValue(group, zone)+ i.getValue() * (1-ratio) * param_propSurvie); } } } } // popMon.holdCatch(param_pop, cat); resManager.addResult(step, param_pop, cat); popMon.addDiscard(step, param_pop, discard); } if(step.getMonth().equals(Month.DECEMBER)){ // reinit priceSwitch at the beginning of each year context.setValue("priceSwitch"+param_pop.getName(),0); context.setValue("TACatteint"+param_pop.getName()+param_metNames,false); for (Metier met : listMet){ context.setValue(met.getName()+param_pop.getName()+"flag",0); log.info("flag?" +context.getValue(met.getName()+param_pop.getName()+"flag")); } } // on a affecte une fois cette meta pop au rejet il ne faut pas le // refaire pour ce pas de temps affectation = false; } } }