/* * #%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.annotations.Doc; import fr.ifremer.isisfish.datastore.ResultStorage; import fr.ifremer.isisfish.entities.*; 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 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 resultinfos.*; import scripts.SiMatrix; import java.util.*; /** * Cette regles tient compte de la taille minimum des poissons capturable. * * Created: 30 novembre 2006 * * @author sl * @version $Revision: 1.1 $ * from TACseries_Metier_OptionLO_postAction.java * Last update: $Date: 2024-09-27 $ by : $Author: bpoussin $ */ public class MCLnetters_EWG2511 extends AbstractRule { /** to use log facility, just put in your code: log.info("..."); */ static private Log log = LogFactory.getLog(MCLnetters_EWG2511.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 = "Affected Metiers names separated by ; ") public String param_metNames = "GNS_ESP_GSA1;GNS_ESP_GSA5;GNS_ESP_GSA6"; @Doc(value = "TAC allocation (as a ratio)") public double param_alloc = 1; @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 = "3000;6000;;"; @Doc(value = "If tacInKgs = 0, TAC is computed elsewhere and stored in simulation context into this name") public String param_tacName = ""; @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(";"); for ( int i = 0 ; i < StrTacSeries.length; i++) { tacSeries[i] = Double.parseDouble(StrTacSeries[i]); } // Add metier names to a list String[] StrMetNames = param_metNames.split(";"); // filets espagnols listMetNames = new ArrayList(Arrays.asList(StrMetNames)); listMet = new ArrayList(); for(String metN : listMetNames) { if((Metier) context.getMetierDAO().findByName(metN) != null){ listMet.add((Metier) context.getMetierDAO().findByName(metN)); System.out.println("Metier list ESP : " + metN); } } if(listMet.isEmpty()) { List listAllMets = context.getMetierDAO().findAll(); listMetNames = new ArrayList(Arrays.asList(StrMetNames)); for (Metier met : listAllMets) { if (met.getName().contains(param_metNames)) { listMet.add(met); listMetNames.add(met.getName()); System.out.println("Metier list FR : " + met.getName()); } } } } /** * @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 (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" + metier.getName()); //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); } } // Pour ces strategies l'effort du metier est mis a 0; pas de reallocation // NB : pourquoi 2 boubles str ? for (Strategy str : strs) { StrategyMonthInfo smi = str.getStrategyMonthInfo(step .getMonth()); smi.getProportionMetier().setValue(metier, 0); log.info("Metier " + metier.getName() + " prop "+smi.getProportionMetier(metier)); } } 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[0] != 0){ TAC = tacSeries[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; } } }