diff --git a/AMAKFX/src/fr/irit/smac/amak/Configuration.java b/AMAKFX/src/fr/irit/smac/amak/Configuration.java index fd9eb44a8e21212a4b7340c2669e75291f57f451..bc8050f8b87e296f7497acf1932764c02508c4f2 100644 --- a/AMAKFX/src/fr/irit/smac/amak/Configuration.java +++ b/AMAKFX/src/fr/irit/smac/amak/Configuration.java @@ -1,44 +1,50 @@ -package fr.irit.smac.amak; - -import fr.irit.smac.amak.Amas.ExecutionPolicy; - -/** - * This class is used to define global configuration BEFORE calling any other - * classes/methods of the framework. - * - * @author Alexandre Perles - * - */ -public class Configuration { - /** - * The maximal number of threads that can be executed simultaneously - */ - public static int allowedSimultaneousAgentsExecution = 1; - /** - * The execution policy refers to the synchronization between agents execution. - * ONE_PHASE means that agents can realize simultaneous cycles and wait for each - * other after the action. TWO_PHASES means that agents perceive simultaneously - * then wait for each others and then decide and act simultaneously and finally - * wait for each others. - */ - public static ExecutionPolicy executionPolicy = ExecutionPolicy.ONE_PHASE; - - /** - * By default, mas made with amak are meant to be executed on a graphical - * environment. However, some may need to execute a mas without any GUI. To - * guarantee the well functioning of this option, you have to check that you - * only render stuff in methods such as onUpdaterRender - * onRenderingInitialization... Also, do not forget to set your schedulers to - * HIDDEN or DEFAULT - */ - public static boolean commandLineMode = false; - - /** - * By default AMAK will wait for all graphical update to finish before - * moving on to the next cycle. This will likely slow down your amas, but - * you'll be able to see it in real time. - * If you set it to false, you have to make sure that the GUI can keep up, - * or else you may experience freeze on the GUI. - */ - public static boolean waitForGUI = true; -} +package fr.irit.smac.amak; + +import fr.irit.smac.amak.Amas.ExecutionPolicy; + +/** + * This class is used to define global configuration BEFORE calling any other + * classes/methods of the framework. + * + * @author Alexandre Perles + * + */ +public class Configuration { + /** + * The maximal number of threads that can be executed simultaneously + */ + public static int allowedSimultaneousAgentsExecution = 1; + /** + * The execution policy refers to the synchronization between agents execution. + * ONE_PHASE means that agents can realize simultaneous cycles and wait for each + * other after the action. TWO_PHASES means that agents perceive simultaneously + * then wait for each others and then decide and act simultaneously and finally + * wait for each others. + */ + public static ExecutionPolicy executionPolicy = ExecutionPolicy.ONE_PHASE; + + /** + * By default, mas made with amak are meant to be executed on a graphical + * environment. However, some may need to execute a mas without any GUI. To + * guarantee the well functioning of this option, you have to check that you + * only render stuff in methods such as onUpdaterRender + * onRenderingInitialization... Also, do not forget to set your schedulers to + * HIDDEN or DEFAULT + */ + public static boolean commandLineMode = false; + + /** + * By default AMAK will wait for all graphical update to finish before + * moving on to the next cycle. This will likely slow down your amas, but + * you'll be able to see it in real time. + * If you set it to false, you have to make sure that the GUI can keep up, + * or else you may experience freeze on the GUI. + */ + public static boolean waitForGUI = true; + + + /** + * By default AMAK will wait for 1 sec before updating the plots + */ + public static double plotMilliSecondsUpdate = 1000; +} diff --git a/AMAKFX/src/fr/irit/smac/amak/ui/AmakPlot.java b/AMAKFX/src/fr/irit/smac/amak/ui/AmakPlot.java index 970c79eddd9c0fc23f0e6a88b2794f3c0536bc0a..60a58286244634a53702a0cea0126b6a792c29aa 100644 --- a/AMAKFX/src/fr/irit/smac/amak/ui/AmakPlot.java +++ b/AMAKFX/src/fr/irit/smac/amak/ui/AmakPlot.java @@ -10,6 +10,7 @@ import org.jfree.chart.renderer.xy.SamplingXYLineRenderer; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; +import fr.irit.smac.amak.Configuration; import fr.irit.smac.amak.tools.RunLaterHelper; import javafx.animation.KeyFrame; import javafx.animation.Timeline; @@ -157,7 +158,7 @@ public class AmakPlot { if(!getNotifySent()) { setNotifySent(); Timeline tl = new Timeline(new KeyFrame( - Duration.millis(1000), + Duration.millis(Configuration.plotMilliSecondsUpdate), ae -> {seriesCollection.setNotify(true);; resetNotifySent();})); tl.play(); } diff --git a/AMOEBAonAMAK/src/agents/context/Context.java b/AMOEBAonAMAK/src/agents/context/Context.java index ef9394229c82aeb9728ede1a9d310733d7860a97..55fd51a44ae95f2d0927ef004f79cd4a1763bf08 100644 --- a/AMOEBAonAMAK/src/agents/context/Context.java +++ b/AMOEBAonAMAK/src/agents/context/Context.java @@ -10,6 +10,9 @@ import agents.AmoebaAgent; import agents.context.localModel.LocalModel; import agents.context.localModel.LocalModelMillerRegression; import agents.context.localModel.TypeLocalModel; +import agents.head.Criticalities; +import agents.head.DynamicPerformance; +import agents.head.EndogenousRequest; import agents.head.Head; import agents.percept.Percept; import gui.ContextRendererFX; @@ -55,12 +58,18 @@ public class Context extends AmoebaAgent { private HashMap<Percept, Boolean> perceptValidities = new HashMap<>(); private HashMap<Percept, Boolean> perceptNeighborhoodValidities = new HashMap<>(); + private ArrayList<EndogenousRequest> waitingRequests = new ArrayList<EndogenousRequest>(); + public DynamicPerformance regressionPerformance; + public Criticalities criticalities ; public Context(AMOEBA amoeba) { super(amoeba); buildContext(); + criticalities = new Criticalities(3); + //regressionPerformance = new DynamicPerformance(10, 10, 200, 0.5, 0.5, 1); + regressionPerformance = new DynamicPerformance(3, 3, getAmas().getHeadAgent().getAverageRegressionPerformanceIndicator(), 0.5, 0.5, 1); getAmas().getEnvironment().trace(new ArrayList<String>(Arrays.asList("CTXT CREATION", this.getName()))); } @@ -69,6 +78,9 @@ public class Context extends AmoebaAgent { buildContext(bestNearestContext); getAmas().getEnvironment() .trace(new ArrayList<String>(Arrays.asList("CTXT CREATION WITH GODFATHER", this.getName()))); + criticalities = new Criticalities(3); + //regressionPerformance = new DynamicPerformance(10, 10, 200, 0.5, 0.5, 1); + regressionPerformance = new DynamicPerformance(3, 3, getAmas().getHeadAgent().getAverageRegressionPerformanceIndicator(), 0.5, 0.5, 1); //TODO in amak, cannot kill a agent before its 1st cycle //NCSDetection_Uselessness(); @@ -151,7 +163,7 @@ public class Context extends AmoebaAgent { } - //// System.out.println("NEW CONTEXT " + this.getName()); + // world.trace(new ArrayList<String>(Arrays.asList(this.getName(), "EXPS"))); } @@ -311,10 +323,7 @@ public class Context extends AmoebaAgent { for (Context ctxtNeigbor : contextNeighbors) { for (Percept pct : ranges.keySet()) { if (pct != pctDirection) { - //// System.out.println("DISTANCE " + ctxtNeigbor.getName()+ " " + - //// pct.getName()+ " " + expandingContext.distance(pct, - //// ctxtNeigbor.getRanges().get(pct)) + " " + ( expandingContext.distance(pct, - //// ctxtNeigbor.getRanges().get(pct))<0)) ; + test = test && (expandingContext.distance(pct, ctxtNeigbor.getRanges().get(pct)) < -0.0001); } } @@ -369,8 +378,7 @@ public class Context extends AmoebaAgent { for (Percept pct : ranges.keySet()) { double startExpansion = Math.abs(ranges.get(pct).getStart() - biggerContextForCreation.getStart(pct)); double endExpansion = Math.abs(ranges.get(pct).getEnd() - biggerContextForCreation.getEnd(pct)); - //// System.out.println("EXPANSION " + pct.getName() +" < " + startExpansion + " - //// , " + endExpansion + " > / < " +pct.getMin() + " , " +pct.getMax() + " >"); + ranges.get(pct).setStart(biggerContextForCreation.getStart(pct)); ranges.get(pct).setEnd(biggerContextForCreation.getEnd(pct)); @@ -379,6 +387,8 @@ public class Context extends AmoebaAgent { public Pair<Double, Double> getMaxExpansionsForContextExpansionAfterCreation( ArrayList<Context> contextNeighborsInOneDirection, Percept pct) { + + double startRadiusFromCreation = Math.abs(pct.getValue() - this.getRanges().get(pct).getStart()); double endRadiusFromCreation = Math.abs(pct.getValue() - this.getRanges().get(pct).getEnd()); // Pair<Double, Double> maxExpansions = new Pair<Double, Double>( @@ -396,15 +406,11 @@ public class Context extends AmoebaAgent { // for(Context ctxt:partialNeighborContexts.get(pct)) { for (Context ctxt : contextNeighborsInOneDirection) { - //// System.out.println("DISTANCE " + pct.getName() + " " + - //// ctxt.getRanges().get(pct).centerDistance(pct.getValue())); + if (ctxt.getRanges().get(pct).centerDistance(pct.getValue()) < 0) { // End radius currentEndExpansion = ctxt.getRanges().get(pct).distance(ranges.get(pct)); - //// System.out.println("DISTANCE 2 " + pct.getName() + " " + - //// ctxt.getRanges().get(pct).distance(ranges.get(pct))); - ////// System.out.println(ctxt.getName() + " " + pct.getName() + " " + - //// currentRadius + " " + maxRadius); + if (currentEndExpansion < maxExpansions.getB() && currentEndExpansion >= -0.00001) { if (Math.abs(currentEndExpansion) < 0.0001) { currentEndExpansion = 0.0; @@ -416,8 +422,7 @@ public class Context extends AmoebaAgent { if (ctxt.getRanges().get(pct).centerDistance(pct.getValue()) > 0) { // Start radius currentStartExpansion = ctxt.getRanges().get(pct).distance(ranges.get(pct)); - ////// System.out.println(ctxt.getName() + " " + pct.getName() + " " + - ////// currentRadius + " " + maxRadius); + if (currentStartExpansion < maxExpansions.getA() && currentStartExpansion >= -0.00001) { if (Math.abs(currentStartExpansion) < 0.0001) { currentEndExpansion = 0.0; @@ -434,7 +439,7 @@ public class Context extends AmoebaAgent { // TODO these methods look very similar, maybe factorization is possible ? public void updateRequestNeighborState() { // faire le update dans le head attention partial et full if (nonValidNeightborPercepts.size() == 0) { - ////// System.out.println("VALID NEIGHBOR : " + this.getName()); + getAmas().getHeadAgent().addRequestNeighbor(this); } else { getAmas().getHeadAgent().removeRequestNeighbor(this); @@ -443,7 +448,7 @@ public class Context extends AmoebaAgent { public void updateActivatedContexts() { // faire le update dans le head attention partial et full if (nonValidPercepts.size() == 0) { - ////// System.out.println("VALID NEIGHBOR : " + this.getName()); + getAmas().getHeadAgent().addActivatedContext(this); } else { getAmas().getHeadAgent().removeActivatedContext(this); @@ -452,7 +457,7 @@ public class Context extends AmoebaAgent { public void updateActivatedContextsCopyForUpdate() { // faire le update dans le head attention partial et full if (nonValidPercepts.size() == 0) { - ////// System.out.println("VALID NEIGHBOR : " + this.getName()); + getAmas().getHeadAgent().addActivatedContextCopy(this); } else { getAmas().getHeadAgent().removeActivatedContextCopy(this); @@ -480,8 +485,7 @@ public class Context extends AmoebaAgent { public void solveNCS_IncompetentHead(Head head) { getEnvironment().trace(new ArrayList<String>(Arrays.asList(this.getName(), "*********************************************************************************************************** SOLVE NCS INCOMPETENT HEAD"))); - ////// System.out.println(world.getScheduler().getTick() +" " + this.getName()+ - ////// " " +"solveNCS_IncompetentHead"); + getEnvironment().raiseNCS(NCS.HEAD_INCOMPETENT); growRanges(); getAmas().getHeadAgent().setBadCurrentCriticalityMapping(); @@ -495,8 +499,7 @@ public class Context extends AmoebaAgent { public void solveNCS_Concurrence(Head head) { getEnvironment().trace(new ArrayList<String>(Arrays.asList(this.getName(), "*********************************************************************************************************** SOLVE NCS CONCURENCE"))); - ////// System.out.println(world.getScheduler().getTick() +" " + this.getName()+ - ////// " " + "solveNCS_Concurrence"); + getEnvironment().raiseNCS(NCS.CONTEXT_CONCURRENCE); this.shrinkRangesToJoinBorders(head.getBestContext()); @@ -586,6 +589,9 @@ public class Context extends AmoebaAgent { } public void analyzeResults4(Head head, Context closestContextToOracle) { + + + if (head.getCriticity(this) < head.getErrorAllowed()) { confidence++; } else { @@ -654,6 +660,91 @@ public class Context extends AmoebaAgent { } } + + + + public EndogenousRequest boundsToEndogenousRequest(HashMap<Percept, Pair<Double, Double>> bounds) { + HashMap<String, Double> request = new HashMap<String, Double>(); + + for(Percept pct : bounds.keySet()) { + + if(bounds.get(pct) != null) { + getEnvironment().trace(new ArrayList<String>(Arrays.asList("ENDO REQUESTS BOUNDS", pct.getName(),""+ bounds.get(pct).getA(),""+ bounds.get(pct).getB(), ""+((bounds.get(pct).getB() + bounds.get(pct).getA())/2)) )); + request.put(pct.getName(), (bounds.get(pct).getB() + bounds.get(pct).getA())/2); + }else { + getEnvironment().trace(new ArrayList<String>(Arrays.asList("ENDO REQUESTS ERROR missing percept bounds"))); + } + + + } + + return new EndogenousRequest(request, null); + } + + public EndogenousRequest endogenousRequest(Context ctxt) { + + HashMap<Percept, Double> voidDistances = new HashMap<Percept, Double>(); + HashMap<Percept, Double> overlapDistances = new HashMap<Percept, Double>(); + HashMap<Percept, Pair<Double, Double>> bounds = new HashMap<Percept, Pair<Double, Double>>(); + + double currentDistance = 0.0; + + int overlapCounts = 0; + Percept voidPercept = null; + double voidDistance = 0.0; + + for (Percept pct : getAmas().getPercepts()) { + currentDistance = this.distance(ctxt, pct); + + if(currentDistance<-(pct.getMappingErrorAllowed()*0.1)) { + getEnvironment().trace(new ArrayList<String>(Arrays.asList("OVERLAP",pct.getName(), ""+this,""+ctxt)) ); + overlapCounts+=1; + overlapDistances.put(pct, Math.abs(currentDistance)); + bounds.put(pct, this.overlapBounds(ctxt, pct)); + + + } + + + if (currentDistance > (pct.getMappingErrorAllowed()*0.1)) { + getEnvironment().trace(new ArrayList<String>(Arrays.asList("VOID",pct.getName(), ""+this,""+ctxt)) ); + voidDistances.put(pct, currentDistance); + bounds.put(pct, this.voidBounds(ctxt, pct)); + } + + + + + + } + + if (overlapCounts == getAmas().getPercepts().size()) { + + getEnvironment().trace(new ArrayList<String>(Arrays.asList(getAmas().getPercepts().size() + "OVERLAPS", ""+this,""+ctxt)) ); + + EndogenousRequest request = boundsToEndogenousRequest(bounds); + if(request.getRequest() != null) { + return new EndogenousRequest(request.getRequest(), 5, new ArrayList<Context>(Arrays.asList(this,ctxt))); + } + } +// else if(overlapCounts == getAmas().getPercepts().size()-1 && voidDistances.size() == 1) { +// +// getEnvironment().trace(new ArrayList<String>(Arrays.asList("VOID", ""+this,""+ctxt)) ); +// +// EndogenousRequest request = boundsToEndogenousRequest(bounds); +// if(request.getRequest() != null) { +// +// if(getAmas().getHeadAgent().isVoid(request.getRequest())) { +// return new EndogenousRequest(request.getRequest(), 7, new ArrayList<Context>(Arrays.asList(this,ctxt))); +// } +// } +// } + else { + return null; + } + + return null; + } public double distanceAsVolume(Context ctxt) { double totalDistanceAsVolume = 1.0; @@ -661,7 +752,7 @@ public class Context extends AmoebaAgent { for (Percept pct : getAmas().getPercepts()) { double currentDistance = this.distanceForVolume(ctxt, pct); totalDistanceAsVolume *= currentDistance; - // System.out.println(pct.getName() + " " + currentDistance); + } @@ -676,7 +767,7 @@ public class Context extends AmoebaAgent { if (currentDistance > maxDistance) { maxDistance = currentDistance; } - // System.out.println(pct.getName() + " " + currentDistance); + } @@ -688,7 +779,7 @@ public class Context extends AmoebaAgent { for (Percept pct : getAmas().getPercepts()) { minDistance = Math.min(minDistance, this.distanceForMaxOrMin(ctxt, pct) / pct.getMinMaxDistance()); - // System.out.println(pct.getName() + " " + currentDistance); + } return minDistance; } @@ -725,7 +816,8 @@ public class Context extends AmoebaAgent { public void NCSDetection_OverMapping() { - boolean fusionAcomplished = false; + getEnvironment().trace(new ArrayList<String>(Arrays.asList(this.getName(), + "*********************************************************************************************************** SOLVE NCS OVERMAPPING"))); for(Context ctxt : getAmas().getHeadAgent().getActivatedNeighborsContexts()) { @@ -733,19 +825,17 @@ public class Context extends AmoebaAgent { if(ctxt != this && !ctxt.isDying()) { - fusionAcomplished = false; + double currentDistanceToOraclePrediction = this.getLocalModel().distance(this.getCurrentExperiment()); double otherContextDistanceToOraclePrediction = ctxt.getLocalModel().distance(ctxt.getCurrentExperiment()); - - - - - //if(this.sameModelAs(ctxt, world.getScheduler().getHeadAgent().getErrorAllowed()/10) ) { - if((currentDistanceToOraclePrediction<getAmas().getHeadAgent().getDistanceToRegressionAllowed()) && (otherContextDistanceToOraclePrediction<getAmas().getHeadAgent().getDistanceToRegressionAllowed())) { + //double minDistanceToOraclePrediction = Math.min(getAmas().getHeadAgent().getDistanceToRegressionAllowed(), getAmas().getHeadAgent().getDistanceToRegressionAllowed()); + double averageDistanceToOraclePrediction = getAmas().getHeadAgent().getAverageRegressionPerformanceIndicator(); + + if((currentDistanceToOraclePrediction<averageDistanceToOraclePrediction) && (otherContextDistanceToOraclePrediction<averageDistanceToOraclePrediction)) { - getEnvironment().trace(new ArrayList<String>(Arrays.asList("currentDistanceToOraclePrediction",""+ currentDistanceToOraclePrediction,"otherContextDistanceToOraclePrediction",""+ otherContextDistanceToOraclePrediction))); + getEnvironment().trace(new ArrayList<String>( Arrays.asList(this.getName(),"currentDistanceToOraclePrediction",""+ currentDistanceToOraclePrediction,"otherContextDistanceToOraclePrediction",""+ otherContextDistanceToOraclePrediction))); for(Percept pct : ranges.keySet()) { @@ -753,7 +843,7 @@ public class Context extends AmoebaAgent { boolean fusionTest = true; getEnvironment().trace(new ArrayList<String>(Arrays.asList(this.getName(),ctxt.getName(),pct.getName(), ""+Math.abs(this.distance(ctxt, pct)), "DISTANCE", "" + getEnvironment().getMappingErrorAllowed()))); - if(Math.abs(this.distance(ctxt, pct)) < pct.getMappingErrorAllowed()){ + if(Math.abs(this.distance(ctxt, pct)) < pct.getMappingErrorAllowed()/2){ for(Percept otherPct : ranges.keySet()) { @@ -767,8 +857,7 @@ public class Context extends AmoebaAgent { } if(fusionTest) { - solveNCS_OverMapping(ctxt,pct); - fusionAcomplished = true; + solveNCS_OverMapping(ctxt); } } @@ -781,18 +870,17 @@ public class Context extends AmoebaAgent { } - private void solveNCS_OverMapping(Context fusionContext, Percept perceptFusion) { + private void solveNCS_OverMapping(Context fusionContext) { getEnvironment().trace(new ArrayList<String>(Arrays.asList(this.getName(), "*********************************************************************************************************** SOLVE NCS OVERMAPPING"))); getEnvironment().raiseNCS(NCS.CONTEXT_OVERMAPPING); - if (this.getRanges().get(perceptFusion).getCenter() < fusionContext.getRanges().get(perceptFusion) - .getCenter()) { - this.getRanges().get(perceptFusion).setEnd(fusionContext.getRanges().get(perceptFusion).getEnd()); - } else { - this.getRanges().get(perceptFusion).setStart(fusionContext.getRanges().get(perceptFusion).getStart()); + + for(Percept pct : getAmas().getPercepts()) { + this.getRanges().get(pct).setEnd(Math.max(this.getRanges().get(pct).getEnd(), fusionContext.getRanges().get(pct).getEnd())); + this.getRanges().get(pct).setStart(Math.min(this.getRanges().get(pct).getStart(), fusionContext.getRanges().get(pct).getStart())); } - + this.setConfidence(Math.max(this.getConfidence(), fusionContext.getConfidence())); fusionContext.destroy(); @@ -800,13 +888,12 @@ public class Context extends AmoebaAgent { } public void solveNCS_ChildContext() { - getAmas().getHeadAgent().setActiveLearning(true); HashMap<String, Double> request = new HashMap<String, Double>(); for(Percept pct : getAmas().getPercepts()) { request.put(pct.getName(), getRandomValueInRange(pct)); } - - getAmas().getHeadAgent().setSelfRequest(request); + getEnvironment().trace(new ArrayList<String>(Arrays.asList("NEW ENDO REQUEST","10", ""+request, ""+this.getName()))); + getAmas().getHeadAgent().addSelfRequest(request, 10,this); } private Double getRandomValueInRange(Percept pct) { @@ -991,7 +1078,7 @@ public class Context extends AmoebaAgent { double volumeLost = Double.MAX_VALUE; double vol = 1.0; - ////// System.out.println("PerceptWithLesserImpactOnVolumeNotIncludedIn ..."); + for (Percept percept : containingRanges) { if (!ranges.get(percept).isPerceptEnum()) { @@ -1000,40 +1087,34 @@ public class Context extends AmoebaAgent { if (!(otherRanges.getStart() <= ranges.get(percept).getStart() && ranges.get(percept).getEnd() <= otherRanges.getEnd())) { - ////// System.out.println(percept.getName()); + if (ranges.get(percept).getNearestLimit(percept.getValue()) == false) { - ////// System.out.println("end simu : " + - ////// ranges.get(percept).simulateNegativeAVTFeedbackEnd(percept.getValue()) + - ////// " start : " + ranges.get(percept).getStart()); + vol = ranges.get(percept).simulateNegativeAVTFeedbackEnd(percept.getValue()) - ranges.get(percept).getStart(); } else { - ////// System.out.println("end : " + ranges.get(percept).getEnd() + " start simu - ////// : " + - ////// ranges.get(percept).simulateNegativeAVTFeedbackStart(percept.getValue())); + vol = ranges.get(percept).getEnd() - ranges.get(percept).simulateNegativeAVTFeedbackStart(percept.getValue()); } - ////// System.out.println("Vol1 : " + vol); + for (Percept p2 : ranges.keySet()) { if (!ranges.get(p2).isPerceptEnum() && p2 != percept) { - ////// System.out.println(p2.getName()); + vol *= ranges.get(p2).getLenght(); - ////// System.out.println(p2.getName() + " " + ranges.get(p2).getLenght() + " " - ////// + getName()); + } } - ////// System.out.println("Vol2 : " + vol); + if (vol < volumeLost) { volumeLost = vol; p = percept; } - ////// System.out.println("Vol lost : " + volumeLost + "percept " + - ////// p.getName()); + } } } @@ -1046,7 +1127,7 @@ public class Context extends AmoebaAgent { double volumeLost = Double.MAX_VALUE; double vol = 1.0; - //////// System.out.println("LESSER ..."); + for (Percept percept : containingRanges) { if (!ranges.get(percept).isPerceptEnum()) { @@ -1055,36 +1136,35 @@ public class Context extends AmoebaAgent { if (!(otherRanges.getStart() <= ranges.get(percept).getStart() && ranges.get(percept).getEnd() <= otherRanges.getEnd())) { - //////// System.out.println(percept.getName()); + vol = Math.abs(Math.abs(otherRanges.getCenter() - ranges.get(percept).getCenter()) - otherRanges.getRadius() - ranges.get(percept).getRadius()); // if (ranges.get(percept).getNearestLimit(percept.getValue()) == false) { -// ////////System.out.println("end simu : " + ranges.get(percept).simulateNegativeAVTFeedbackMax(percept.getValue()) + " start : " + ranges.get(percept).getStart()); + // vol = percept.getValue() - ranges.get(percept).getStart(); // } else { -// ////////System.out.println("end : " + ranges.get(percept).getEnd() + " start simu : " + ranges.get(percept).simulateNegativeAVTFeedbackMin(percept.getValue())); + // vol = ranges.get(percept).getEnd() - percept.getValue(); // } - //////// System.out.println("Vol1 : " + vol); + for (Percept p2 : ranges.keySet()) { if (!ranges.get(p2).isPerceptEnum() && p2 != percept) { - //////// System.out.println(p2.getName()); + vol *= ranges.get(p2).getLenght(); - //////// System.out.println(p2.getName() + " " + ranges.get(p2).getLenght() + " - //////// " + getName()); + } } - //////// System.out.println("Vol2 : " + vol); + if (vol < volumeLost) { volumeLost = vol; p = percept; } - //////// System.out.println("Vol lost : " + volumeLost); + } } @@ -1207,7 +1287,7 @@ public class Context extends AmoebaAgent { } } } - //////// System.out.println("percept " + p.getName()); + return p; } @@ -1388,8 +1468,7 @@ public class Context extends AmoebaAgent { Double influence = 1.0; for (Percept pct : situation.keySet()) { - ////////// System.out.println("INFLUTEST " + getInfluenceByPerceptSituation(pct, - ////////// situation.get(pct))); + influence *= getInfluenceByPerceptSituationWithConfidence(pct, situation.get(pct)); } @@ -1404,8 +1483,7 @@ public class Context extends AmoebaAgent { Double influence = 1.0; for (Percept pct : situation.keySet()) { - ////////// System.out.println("INFLUTEST " + getInfluenceByPerceptSituation(pct, - ////////// situation.get(pct))); + influence *= getInfluenceByPerceptSituation(pct, situation.get(pct)); } @@ -1417,8 +1495,7 @@ public class Context extends AmoebaAgent { Double currentInfluence = 0.0; for (Percept pct : situation.keySet()) { - ////////// System.out.println("INFLUTEST " + getInfluenceByPerceptSituation(pct, - ////////// situation.get(pct))); + currentInfluence = getInfluenceByPerceptSituationWithConfidence(pct, situation.get(pct)); if (currentInfluence < worstInfluence) { worstInfluence = currentInfluence; @@ -1433,8 +1510,7 @@ public class Context extends AmoebaAgent { Double currentInfluence = 0.0; for (Percept pct : situation.keySet()) { - ////////// System.out.println("INFLUTEST " + getInfluenceByPerceptSituation(pct, - ////////// situation.get(pct))); + currentInfluence = getInfluenceByPerceptSituation(pct, situation.get(pct)); if (currentInfluence < worstInfluence) { worstInfluence = currentInfluence; @@ -1513,11 +1589,11 @@ public class Context extends AmoebaAgent { * @param head the head */ public void growRanges() { - ////////System.out.println("Grow " + this.getName() ); + ArrayList<Percept> allPercepts = getAmas().getPercepts(); for (Percept pct : allPercepts) { boolean contain = ranges.get(pct).contains(pct.getValue()) == 0 ; - ////////System.out.println(pct.getName() + " " + contain); + if (!contain) { if(ranges.get(pct).getLenght()<(pct.getMappingErrorAllowed()*1.5)) { ranges.get(pct).adapt(pct.getValue()); @@ -1573,6 +1649,49 @@ public class Context extends AmoebaAgent { private double distance(Context ctxt, Percept pct) { return this.getRanges().get(pct).distance(ctxt.getRanges().get(pct)); + } + + private Pair<Double,Double> overlapBounds(Context ctxt, Percept pct) { + + + if (pct.contextIncludedIn(this, ctxt)) { + + return new Pair<Double, Double>(this.getRanges().get(pct).getStart(), this.getRanges().get(pct).getEnd()); + + } else if (pct.contextIncludedIn(ctxt, this)) { + + return new Pair<Double, Double>(ctxt.getRanges().get(pct).getStart(), ctxt.getRanges().get(pct).getEnd()); + + } else if (pct.contextOrder(this, ctxt)) { + + return new Pair<Double, Double>(ctxt.getRanges().get(pct).getStart(), this.getRanges().get(pct).getEnd()); + + } else if (pct.contextOrder(ctxt, this)) { + + return new Pair<Double, Double>(this.getRanges().get(pct).getStart(), ctxt.getRanges().get(pct).getEnd()); + + } else { + + return null; + } + + + + } + + private Pair<Double,Double> voidBounds(Context ctxt, Percept pct) { + + + + if(this.getRanges().get(pct).getEnd() < ctxt.getRanges().get(pct).getStart()) { + return new Pair<Double, Double>(this.getRanges().get(pct).getEnd(), ctxt.getRanges().get(pct).getStart()); + } + else { + return new Pair<Double, Double>(ctxt.getRanges().get(pct).getEnd(), this.getRanges().get(pct).getStart()); + } + + + } private double distanceForVolume(Context ctxt, Percept pct) { @@ -1787,6 +1906,19 @@ public class Context extends AmoebaAgent { return s; } + public ArrayList<String> toStringArrayPierre() { + ArrayList<String> array = new ArrayList<String>(); + array.add(getName()); + array.add(""+localModel.getCoef()[0] ); + for(int i =1;i<localModel.getCoef().length;i++) { + array.add(""+localModel.getCoef()[i]); + } + array.add(""+ getLocalModel().getMinProposition(this)); + array.add(""+ getLocalModel().getMaxProposition(this)); + + return array; + } + public String toStringFull() { String s = ""; s += "Context : " + getName() + "\n"; @@ -1808,6 +1940,11 @@ public class Context extends AmoebaAgent { s += "Max Prediction " + getLocalModel().getMaxProposition(this) + "\n"; s += "Min Prediction " + getLocalModel().getMinProposition(this) + "\n"; + s += "Mean Distance To Regression " + criticalities.getCriticalityMean("distanceToRegression") + "\n"; + s += "Distance To Regression Allowed " + regressionPerformance.getPerformanceIndicator() +"\n\n"; + + + for (Percept v : ranges.keySet()) { s += v.getName() + " : " + ranges.get(v).toString() + "\n"; @@ -1915,6 +2052,8 @@ public class Context extends AmoebaAgent { for (Percept percept : getAmas().getPercepts()) { percept.deleteContextProjection(this); } + + super.destroy(); } @@ -1979,4 +2118,18 @@ public class Context extends AmoebaAgent { this.localModel = localModel; this.localModel.context = this; } + + + public void addWaitingRequest(EndogenousRequest request) { + waitingRequests.add(request); + } + + public void deleteWaitingRequest(EndogenousRequest request) { + waitingRequests.remove(request); + } + + public double getDistanceToRegressionAllowed() { + return regressionPerformance.getPerformanceIndicator(); + } + } diff --git a/AMOEBAonAMAK/src/agents/context/Range.java b/AMOEBAonAMAK/src/agents/context/Range.java index d1bba530d56dc6986ffc40e15c383112c2fdf1c8..704b4f5c2b9fabf03948ca5c2e97ffd8b36a3f1b 100644 --- a/AMOEBAonAMAK/src/agents/context/Range.java +++ b/AMOEBAonAMAK/src/agents/context/Range.java @@ -794,7 +794,7 @@ public class Range implements Serializable, Comparable, Cloneable { * @return boolean representing if the range is too small. */ public boolean isTooSmall() { - if((end - start) < percept.getMappingErrorAllowed()*0.5 && (end - start)>0) { + if((end - start) < percept.getMappingErrorAllowed()*0.1 && (end - start)>0) { ////// System.out.println("£££££££££££££££££££££££££££££ mininimalRange :" + ////// mininimalRange + " ~~~ " + (end - start)); } @@ -1446,16 +1446,18 @@ public class Range implements Serializable, Comparable, Cloneable { ////// " + (Math.abs(newStartValue-this.start))); } - if ((Double) newStartValue != null) { - if (newStartValue < percept.getMin()) { - this.start = percept.getMin(); - - } else { - this.start = newStartValue; - } - } else { - this.start = newStartValue; - } +// if ((Double) newStartValue != null) { +// if (newStartValue < percept.getMin()) { +// this.start = percept.getMin(); +// +// } else { +// this.start = newStartValue; +// } +// } else { +// this.start = newStartValue; +// } + + this.start = newStartValue; if (this.context != null) { lastStartTickModification = this.context.getAmas().getCycle(); @@ -1506,15 +1508,17 @@ public class Range implements Serializable, Comparable, Cloneable { ////// System.out.println(context.getName() + " " + percept.getName() + " END " ////// + (Math.abs(newEndValue-this.end))); } - if ((Double) newEndValue != null) { - if (newEndValue > percept.getMax()) { - this.end = percept.getMax(); - } else { - this.end = newEndValue; - } - } else { - this.end = newEndValue; - } +// if ((Double) newEndValue != null) { +// if (newEndValue > percept.getMax()) { +// this.end = percept.getMax(); +// } else { +// this.end = newEndValue; +// } +// } else { +// this.end = newEndValue; +// } + + this.end = newEndValue; if (this.context != null) { lastEndTickModification = context.getAmas().getCycle(); diff --git a/AMOEBAonAMAK/src/agents/head/Criticalities.java b/AMOEBAonAMAK/src/agents/head/Criticalities.java index 2885a8f0bd3023937e5ad79c1a2510ca0d61606c..900e01832d9df06b8c4f12f222047b201edfe510 100644 --- a/AMOEBAonAMAK/src/agents/head/Criticalities.java +++ b/AMOEBAonAMAK/src/agents/head/Criticalities.java @@ -66,5 +66,11 @@ public class Criticalities implements Cloneable{ } + + public HashMap<String, ArrayList<Double>> getLastValues() { + + return lastValues; + + } } diff --git a/AMOEBAonAMAK/src/agents/head/DynamicPerformance.java b/AMOEBAonAMAK/src/agents/head/DynamicPerformance.java index af33b83ff1322985584a199b0ec41c908eaa32e1..4c0652297e33f9e77ea424b41ecaa11d5c53ffa3 100644 --- a/AMOEBAonAMAK/src/agents/head/DynamicPerformance.java +++ b/AMOEBAonAMAK/src/agents/head/DynamicPerformance.java @@ -7,13 +7,13 @@ public class DynamicPerformance implements Serializable{ public int successesBeforeDiminution; public int conflictsBeforeAugmentation; - public double performanceIndicator; + public Double performanceIndicator; public int performanceCounter; public double augmentationFactor; public double diminutionFactor; - public double minPerformanceIndicator; + public Double minPerformanceIndicator; // Required for serialization by XML public DynamicPerformance() {}; diff --git a/AMOEBAonAMAK/src/agents/head/EndogenousRequest.java b/AMOEBAonAMAK/src/agents/head/EndogenousRequest.java new file mode 100644 index 0000000000000000000000000000000000000000..cf949f0be04caa310ac02eee908519083ebf5102 --- /dev/null +++ b/AMOEBAonAMAK/src/agents/head/EndogenousRequest.java @@ -0,0 +1,74 @@ +package agents.head; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; + +import org.junit.platform.commons.util.ToStringBuilder; + +import agents.context.Context; + +public class EndogenousRequest { + + + private Integer priority; + private HashMap<String, Double> request; + private ArrayList<Context> askingContexts; + private String name; + + public EndogenousRequest(HashMap<String, Double> rqst, int prty, ArrayList<Context> contexts) { + + request = rqst; + priority = prty; + askingContexts = contexts; + + name = ""; + + for(Context ctxt: askingContexts) { + name += ctxt.getName(); + } + } + + public EndogenousRequest(HashMap<String, Double> rqst, Integer prty) { + + request = rqst; + priority = prty; + } + + public Integer getPriority() { + return priority; + } + + public HashMap<String, Double> getRequest(){ + return request; + } + + public String toString() { + String m=""; + for(Context ctxt : askingContexts) { + m+= ctxt.getName() + " "; + } + m+=priority + " "; + m+= request; + return m; + } + + public ArrayList<Context> getAskingContexts(){ + return askingContexts; + } + + public String getName() { + return name; + } + + public boolean testIfContextsAlreadyAsked(ArrayList<Context> contexts) { + boolean test = true; + for(Context ctxt : contexts) { + test = test && askingContexts.contains(ctxt); + } + return test; + } + + + +} diff --git a/AMOEBAonAMAK/src/agents/head/Head.java b/AMOEBAonAMAK/src/agents/head/Head.java index 6e1a106a30a90bc23d115cb082d3e8893a0233b4..61101743d8ac488b42dfec53cade0a761391f1d4 100644 --- a/AMOEBAonAMAK/src/agents/head/Head.java +++ b/AMOEBAonAMAK/src/agents/head/Head.java @@ -3,8 +3,12 @@ package agents.head; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.List; +import java.util.Iterator; +import java.util.PriorityQueue; +import java.util.Queue; import agents.AmoebaAgent; import agents.context.Context; @@ -49,8 +53,13 @@ public class Head extends AmoebaAgent { private ArrayList<Context> contextsInCompetition = new ArrayList<Context>(); - static double lembda = 0.99; + Queue<EndogenousRequest> endogenousRequests = new PriorityQueue<EndogenousRequest>(new Comparator<EndogenousRequest>(){ + public int compare(EndogenousRequest r1, EndogenousRequest r2) { + return r2.getPriority().compareTo(r1.getPriority()); + } + }); + static double lembda = 0.99; // ----------------------------- public void setDataForErrorMargin(double errorAllowed, double augmentationFactorError, double diminutionFactorError, @@ -67,6 +76,15 @@ public class Head extends AmoebaAgent { public Head(AMOEBA amoeba) { super(amoeba); + + for(int i =0 ; i< 20;i++) { + getAmas().data.executionTimesSums[i]=0.0; + } + + + + + } @@ -126,7 +144,7 @@ public class Head extends AmoebaAgent { private void playWithOracle() { - getAmas().data.playExecutionTime = System.currentTimeMillis(); + getAmas().data.executionTimes[0]=System.currentTimeMillis(); if (activatedContexts.size() > 0) { selectBestContext(); // using highest confidence // selectBestContextWithDistanceToModel(); @@ -153,42 +171,44 @@ public class Head extends AmoebaAgent { "*********************************************************************************************************** BEST CONTEXT"))); } - getAmas().data.playExecutionTime = System.currentTimeMillis() - getAmas().data.playExecutionTime; + getAmas().data.executionTimes[0]=System.currentTimeMillis()- getAmas().data.executionTimes[0]; - getAmas().data.endogenousExecutionTime = System.currentTimeMillis(); + getAmas().data.executionTimes[1]=System.currentTimeMillis(); // endogenousPlay(); - getAmas().data.endogenousExecutionTime = System.currentTimeMillis() - getAmas().data.endogenousExecutionTime; + getAmas().data.executionTimes[1]=System.currentTimeMillis()- getAmas().data.executionTimes[1]; - getAmas().data.contextSelfAnalisisExecutionTime = System.currentTimeMillis(); + getAmas().data.executionTimes[2]=System.currentTimeMillis(); selfAnalysationOfContexts4(); - getAmas().data.contextSelfAnalisisExecutionTime = System.currentTimeMillis() - getAmas().data.contextSelfAnalisisExecutionTime; + getAmas().data.executionTimes[2]=System.currentTimeMillis()- getAmas().data.executionTimes[2]; + - getAmas().data.incompetentHeadNCSExecutionTime = System.currentTimeMillis(); + getAmas().data.executionTimes[3]=System.currentTimeMillis(); NCSDetection_IncompetentHead(); /* - * If there isn't any proposition or only bad propositions, the head is - * incompetent. It needs help from a context. - */ - getAmas().data.incompetentHeadNCSExecutionTime = System.currentTimeMillis() - getAmas().data.incompetentHeadNCSExecutionTime; + * If there isn't any proposition or only bad propositions, the head is + * incompetent. It needs help from a context. + */ + getAmas().data.executionTimes[3]=System.currentTimeMillis()- getAmas().data.executionTimes[3]; + - getAmas().data.concurrenceNCSExecutionTime = System.currentTimeMillis(); + getAmas().data.executionTimes[4]=System.currentTimeMillis(); NCSDetection_Concurrence(); /* If result is good, shrink redundant context (concurrence NCS) */ - getAmas().data.concurrenceNCSExecutionTime = System.currentTimeMillis() - getAmas().data.concurrenceNCSExecutionTime; + getAmas().data.executionTimes[4]=System.currentTimeMillis()- getAmas().data.executionTimes[4]; - getAmas().data.create_New_ContextNCSExecutionTime = System.currentTimeMillis(); + getAmas().data.executionTimes[5]=System.currentTimeMillis(); NCSDetection_Create_New_Context(); /* Finally, head agent check the need for a new context agent */ - getAmas().data.create_New_ContextNCSExecutionTime = System.currentTimeMillis() - getAmas().data.create_New_ContextNCSExecutionTime; + getAmas().data.executionTimes[5]=System.currentTimeMillis()- getAmas().data.executionTimes[5]; - getAmas().data.overmappingNCSExecutionTime = System.currentTimeMillis(); - //NCSDetection_Context_Overmapping(); - getAmas().data.overmappingNCSExecutionTime = System.currentTimeMillis() - getAmas().data.overmappingNCSExecutionTime; + getAmas().data.executionTimes[6]=System.currentTimeMillis(); + NCSDetection_Context_Overmapping(); + getAmas().data.executionTimes[6]=System.currentTimeMillis()- getAmas().data.executionTimes[6]; - getAmas().data.memoryCreationExecutionTime = System.currentTimeMillis(); - getAmas().data.memoryCreationExecutionTime = System.currentTimeMillis() - getAmas().data.memoryCreationExecutionTime; - getAmas().data.otherExecutionTime = System.currentTimeMillis(); + getAmas().data.executionTimes[7]=System.currentTimeMillis(); NCSDetection_ChildContext(); + NCSDetection_PotentialRequest(); + criticalities.addCriticality("spatialCriticality", (getMinMaxVolume() - getVolumeOfAllContexts()) / getMinMaxVolume()); @@ -213,7 +233,6 @@ public class Head extends AmoebaAgent { // if(nearestLocalNeighbor(ctxt, otherCtxt)) { Pair<Double, Percept> distanceAndPercept = ctxt.distance(otherCtxt); - // System.out.println("DISTANCE : " + distanceAndPercept.getA() + " " + // distanceAndPercept.getB()); if (distanceAndPercept.getA() < 0) { criticalities.addCriticality("localOverlapMappingCriticality", @@ -243,19 +262,14 @@ public class Head extends AmoebaAgent { getAmas().data.evolutionCriticalityConfidence = (lembda * getAmas().data.evolutionCriticalityConfidence) + ((1 - lembda) * getAmas().data.currentCriticalityConfidence); - getAmas().data.otherExecutionTime = System.currentTimeMillis() - getAmas().data.otherExecutionTime; - - getAmas().data.playExecutionTimeSum += getAmas().data.playExecutionTime; - getAmas().data.endogenousExecutionTimeSum += getAmas().data.endogenousExecutionTime; - getAmas().data.contextSelfAnalisisExecutionTimeSum += getAmas().data.contextSelfAnalisisExecutionTime; + + getAmas().data.executionTimes[7]=System.currentTimeMillis()- getAmas().data.executionTimes[7]; - getAmas().data.incompetentHeadNCSExecutionTimeSum += getAmas().data.incompetentHeadNCSExecutionTime; - getAmas().data.concurrenceNCSExecutionTimeSum += getAmas().data.concurrenceNCSExecutionTime; - getAmas().data.create_New_ContextNCSExecutionTimeSum += getAmas().data.create_New_ContextNCSExecutionTime; - getAmas().data.overmappingNCSExecutionTimeSum += getAmas().data.overmappingNCSExecutionTime; - getAmas().data.memoryCreationExecutionTimeSum += getAmas().data.memoryCreationExecutionTime; + + for(int i = 0 ; i<20;i++) { + getAmas().data.executionTimesSums[i] += getAmas().data.executionTimes[i]; + } - getAmas().data.otherExecutionTimeSum += getAmas().data.otherExecutionTime; } public double getSpatialGeneralizationScore() { @@ -535,9 +549,7 @@ public class Head extends AmoebaAgent { if (activatedContextInOtherPercepts.size() > 0) { - ////////// System.out.println("Partially activated on other percepts than " + - ////////// pct.getName() + " : " + activatedContextInOtherPercepts.size()); - ////////// System.out.println("Value " + pct.getValue()); + CustomComparator rangeStartComparator = new CustomComparator(pct, "start"); Collections.sort(activatedContextInOtherPercepts, rangeStartComparator); @@ -570,7 +582,7 @@ public class Head extends AmoebaAgent { sharedIncompetenceContextPairs.put(pct, nearestContexts); } } else { - ////////// System.out.println("====================================================="); + } } @@ -625,8 +637,7 @@ public class Head extends AmoebaAgent { } private void NCS_EndogenousCompetition() { - //////// System.out.println("NCS Comptetition " + - //////// world.getScheduler().getTick()); + // Creation of twin contexts to give the endogenous prediction // 2 CTXT @@ -742,8 +753,7 @@ public class Head extends AmoebaAgent { double contextInfluenceL = closestContexts.getL().getInfluenceWithConfidence(currentSituation); double contextInfluenceR = closestContexts.getR().getInfluenceWithConfidence(currentSituation); - //////// System.out.println("--------------------------------------------------DIFFERENCE - //////// :" + compareClosestContextPairModels(closestContexts)); + if (compareClosestContextPairModels(closestContexts) < 10) { getAmas().data.endogenousPredictionActivatedContextsSharedIncompetence = (contextInfluenceL @@ -782,6 +792,8 @@ public class Head extends AmoebaAgent { } + + private Double compareClosestContextPairModels(ContextPair<Context, Context> closestContexts) { Double difference = 0.0; @@ -811,13 +823,22 @@ public class Head extends AmoebaAgent { private void NCSDetection_Create_New_Context() { /* Finally, head agent check the need for a new context agent */ + + + boolean newContextCreated = false; - + getAmas().data.executionTimes[9]=System.currentTimeMillis(); if (activatedContexts.size() == 0) { + getEnvironment().trace(new ArrayList<String>(Arrays.asList( + "*********************************************************************************************************** SOLVE NCS CREATE NEW CONTEXT"))); + getAmas().data.executionTimes[8]=System.currentTimeMillis(); Pair<Context, Double> nearestGoodContext = getbestContextInNeighborsWithDistanceToModel(activatedNeighborsContexts); + getAmas().data.executionTimes[8]=System.currentTimeMillis()- getAmas().data.executionTimes[8]; + + Context context; if (nearestGoodContext.getA() != null) { getEnvironment().trace(new ArrayList<String>(Arrays.asList(nearestGoodContext.getA().getName(), @@ -831,12 +852,23 @@ public class Head extends AmoebaAgent { bestContext = context; newContext = context; newContextCreated = true; + + } + getAmas().data.executionTimes[9]=System.currentTimeMillis()- getAmas().data.executionTimes[9]; + + + + + + getAmas().data.executionTimes[10]=System.currentTimeMillis(); if (!newContextCreated) { updateStatisticalInformations(); } + getAmas().data.executionTimes[10]=System.currentTimeMillis()- getAmas().data.executionTimes[10]; + } private void NCSDetection_Context_Overmapping() { @@ -894,6 +926,43 @@ public class Head extends AmoebaAgent { } } + + private void NCSDetection_PotentialRequest() { + + + + + if (activatedNeighborsContexts.size() > 1) { + + int i = 1; + for (Context ctxt : activatedNeighborsContexts) { + + for (Context otherCtxt : activatedNeighborsContexts.subList(i, activatedNeighborsContexts.size())) { + + + if(!this.isDying() && !ctxt.isDying()) { + EndogenousRequest potentialRequest = ctxt.endogenousRequest(otherCtxt); + + if(potentialRequest != null) { + addEndogenousRequest(potentialRequest); + getEnvironment().trace(new ArrayList<String>(Arrays.asList("NEW ENDO REQUEST", ""+potentialRequest))); + } + } + + + } + i++; + } + } + + getEnvironment().trace(new ArrayList<String>(Arrays.asList("ENDO REQUESTS", ""+endogenousRequests.size()))); +// for(EndogenousRequest endoRequest : endogenousRequests) { +// +// System.out.println(endoRequest); +// +// } + + } private void selfAnalysationOfContexts2() { @@ -995,7 +1064,8 @@ public class Head extends AmoebaAgent { getAmas().data.contextNotFinished = true; } - else if (currentDistanceToOraclePrediction < getAmas().data.regressionPerformance.getPerformanceIndicator()) { + else if (currentDistanceToOraclePrediction < getAverageRegressionPerformanceIndicator()) { + //else if (currentDistanceToOraclePrediction < regressionPerformance.getPerformanceIndicator()) { activatedContext.getLocalModel().updateModel(activatedContext.getCurrentExperiment(), getAmas().data.learningSpeed, getAmas().data.numberOfPointsForRegression); @@ -1008,12 +1078,25 @@ public class Head extends AmoebaAgent { if (!getAmas().data.contextNotFinished) { criticalities.addCriticality("distanceToRegression", currentDistanceToOraclePrediction); + } + + activatedContext.criticalities.addCriticality("distanceToRegression", currentDistanceToOraclePrediction); + //getEnvironment().trace(new ArrayList<String>(Arrays.asList("ADD CRITICALITY TO CTXT", ""+activatedContext.getName(), ""+criticalities.getLastValues().get("distanceToRegression").size()))); } activatedContextsCopyForUpdates = new ArrayList<Context>(activatedContexts); for (Context activatedContext : activatedContexts) { + + activatedContext.criticalities.updateMeans(); + + if (activatedContext.criticalities.getCriticalityMean("distanceToRegression") != null) { + activatedContext.regressionPerformance.update(activatedContext.criticalities.getCriticalityMean("distanceToRegression")); + getEnvironment().trace(new ArrayList<String>(Arrays.asList("UPDATE REGRESSION PERFORMANCE", activatedContext.getName(), ""+activatedContext.regressionPerformance.getPerformanceIndicator()))); + } + + activatedContext.analyzeResults4(this, closestContextToOracle); } @@ -1362,8 +1445,6 @@ public class Head extends AmoebaAgent { * @return the context */ private Context createNewContext() { - // ////////System.out.println("Creation d'un nouveau contexte : " + - // contexts.size()); getAmas().data.newContextWasCreated = true; // if (contexts.size() != 0) { // System.exit(0); @@ -1953,9 +2034,7 @@ public class Head extends AmoebaAgent { public boolean requestSurroundingContains(Context ctxt) { for (Percept pct : requestSurroundings.keySet()) { - ////////// System.out.println("REQUEST SURROUNDINGS " + - ////////// requestSurroundings.get(pct).getL().getName() + " ; " + - ////////// requestSurroundings.get(pct).getR().getName()); + if (requestSurroundings.get(pct).contains(ctxt)) { return true; } @@ -1974,8 +2053,7 @@ public class Head extends AmoebaAgent { public void addRequestNeighbor(Context ctxt) { if (!activatedNeighborsContexts.contains(ctxt)) { - //// System.out.println(world.getScheduler().getTick() + " " + ctxt.getName() + - //// " " + "VALID NEIGHBOR"); + activatedNeighborsContexts.add(ctxt); } } @@ -1984,9 +2062,9 @@ public class Head extends AmoebaAgent { if (!activatedContexts.contains(ctxt)) { activatedContexts.add(ctxt); - // System.out.println(world.getScheduler().getTick() + " ACTIVATED CONTEXTS"); + for (Context cxt : activatedContexts) { - // System.out.println("--> " + cxt.getName()); + } } } @@ -1995,9 +2073,9 @@ public class Head extends AmoebaAgent { if (!activatedContextsCopyForUpdates.contains(ctxt)) { activatedContextsCopyForUpdates.add(ctxt); - // System.out.println(world.getScheduler().getTick() + " ACTIVATED CONTEXTS"); + for (Context cxt : activatedContextsCopyForUpdates) { - // System.out.println("--> " + cxt.getName()); + } } } @@ -2016,8 +2094,7 @@ public class Head extends AmoebaAgent { public void removeRequestNeighbor(Context ctxt) { if (activatedNeighborsContexts.contains(ctxt)) { - //// System.out.println(world.getScheduler().getTick() + " " + ctxt.getName() + - //// " " + "NOT VALID NEIGHBOR ANYMORE"); + activatedNeighborsContexts.remove(ctxt); } } @@ -2037,7 +2114,7 @@ public class Head extends AmoebaAgent { public void displayActivatedNeighborsContexts() { for (Context ctxt : activatedNeighborsContexts) { - //////// System.out.println(ctxt.getName()); + } } @@ -2068,8 +2145,7 @@ public class Head extends AmoebaAgent { for (Context ctxt : activatedNeighborsContexts) { currentRadius = ctxt.getRanges().get(pct).distance(pct.getValue()); - //// System.out.println(ctxt.getName() + " " + pct.getName() + " " + - //// currentRadius + " " + maxRadius); + if (currentRadius < maxRadius && currentRadius > 0) { maxRadius = currentRadius; } @@ -2087,6 +2163,8 @@ public class Head extends AmoebaAgent { Pair<Double, Double> maxRadiuses = new Pair<Double, Double>( pct.getRadiusContextForCreation(), pct.getRadiusContextForCreation()); + + //return maxRadiuses; // Pair<Double,Double> maxRadiuses = new // Pair<Double,Double>(pct.getRadiusContextForCreation(),pct.getRadiusContextForCreation()); @@ -2173,21 +2251,59 @@ public class Head extends AmoebaAgent { public boolean isActiveLearning() { - return getAmas().data.activeLearning; + return isSelfRequest(); } - public void setActiveLearning(boolean value) { - getAmas().data.activeLearning = value; - } + public HashMap<String, Double> getSelfRequest(){ - return getAmas().data.selfRequest; + getEnvironment().trace(new ArrayList<String>(Arrays.asList("FUTURE ACTIVE LEARNING", ""+endogenousRequests.element()))); + return endogenousRequests.poll().getRequest(); + } + + public void deleteRequest(Context ctxt) { + + } + + public boolean isSelfRequest(){ + return endogenousRequests.size()>0; } - public void setSelfRequest(HashMap<String, Double> request){ - getAmas().data.selfRequest = request; + public void addSelfRequest(HashMap<String, Double> request, int priority, Context ctxt){ + + addEndogenousRequest(new EndogenousRequest(request, priority,new ArrayList<Context>(Arrays.asList(ctxt)))); } + public void addEndogenousRequest(EndogenousRequest request) { + + boolean existingRequestTest = false; + + if(request.getAskingContexts().size()>1) { + + Iterator<EndogenousRequest> itr = endogenousRequests.iterator(); + while(!existingRequestTest && itr.hasNext()) { + + EndogenousRequest currentRequest = itr.next(); + + if(currentRequest.getAskingContexts().size()>1) { + + existingRequestTest = existingRequestTest || currentRequest.testIfContextsAlreadyAsked(request.getAskingContexts()); + } + + } + if(!existingRequestTest) { + for(Context ctxt : request.getAskingContexts()) { + ctxt.addWaitingRequest(request); + } + endogenousRequests.add(request); + } + }else { + endogenousRequests.add(request); + } + + + + } public void updatePartiallyActivatedNeighbors() { @@ -2204,14 +2320,55 @@ public class Head extends AmoebaAgent { } } + public boolean isVoid(HashMap<String, Double> request) { + boolean test; + + for(Context ctxt : activatedNeighborsContexts) { + + test = true; + for(Percept pct : getAmas().getPercepts()) { + test = test && ctxt.getRanges().get(pct).contains2(request.get(pct.getName())); + } + if(test) { + return false; + } + } + return true; + + + } + + public double getAverageRegressionPerformanceIndicator() { + + + if(activatedNeighborsContexts.size()>1) { + double meanRegressionPerformanceIndicator = 0.0; + + for(Context ctxt : activatedNeighborsContexts) { + + + if(ctxt.regressionPerformance != null) { + meanRegressionPerformanceIndicator += ctxt.regressionPerformance.performanceIndicator; + } + + + } + + return meanRegressionPerformanceIndicator/activatedNeighborsContexts.size(); + } + else { + return 200; + } + + } + // ----------------- // AMOEBAonAMAK --- // ----------------- public void proposition(Context c) { -// System.out.println(c.getName()); -// System.out.println(activatedContexts.size()); + activatedContexts.add(c); } diff --git a/AMOEBAonAMAK/src/experiments/F_XY_System.java b/AMOEBAonAMAK/src/experiments/F_XY_System.java index 42899708ec1a01c6948f08d8fb87fb613dfe2402..d00c161eb53dec5d03ae34d55f7f91b4875f50be 100644 --- a/AMOEBAonAMAK/src/experiments/F_XY_System.java +++ b/AMOEBAonAMAK/src/experiments/F_XY_System.java @@ -80,4 +80,10 @@ public class F_XY_System implements StudiedSystem { // TODO Auto-generated method stub } + + @Override + public HashMap<String, Double> getIntput() { + // TODO Auto-generated method stub + return null; + } } \ No newline at end of file diff --git a/AMOEBAonAMAK/src/experiments/NDimCube.java b/AMOEBAonAMAK/src/experiments/NDimCube.java index 5961a718b19553df77dda21dea7e7c20976a9578..d2400f26ec06abf0bb00f4052278d9c9f97cd28d 100644 --- a/AMOEBAonAMAK/src/experiments/NDimCube.java +++ b/AMOEBAonAMAK/src/experiments/NDimCube.java @@ -127,4 +127,10 @@ public class NDimCube implements StudiedSystem{ // TODO Auto-generated method stub } + + @Override + public HashMap<String, Double> getIntput() { + // TODO Auto-generated method stub + return null; + } } \ No newline at end of file diff --git a/AMOEBAonAMAK/src/experiments/TestMain.java b/AMOEBAonAMAK/src/experiments/TestMain.java new file mode 100644 index 0000000000000000000000000000000000000000..e6b6aab20fd7f2b79cbff5f074c44c5098245a00 --- /dev/null +++ b/AMOEBAonAMAK/src/experiments/TestMain.java @@ -0,0 +1,215 @@ +package experiments; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.PriorityQueue; +import java.util.Queue; + +import agents.head.EndogenousRequest; + + + + +public class TestMain { + + + public static double fact(double n) { + + if(n==0) { + return 1; + } + else { + return n*fact(n-1); + } + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + testPriorityQueue(); + + + + } + + public static void testPriorityQueue() { + + Queue<EndogenousRequest> endogenousRequest = new PriorityQueue<EndogenousRequest>(new Comparator<EndogenousRequest>(){ + public int compare(EndogenousRequest r1, EndogenousRequest r2) { + return r2.getPriority().compareTo(r1.getPriority()); + } + }); + + HashMap<String, Double> hm1 = new HashMap<String, Double>(); + hm1.put("p1", 50.0); + HashMap<String, Double> hm2 = new HashMap<String, Double>(); + hm2.put("p2", 50.0); + HashMap<String, Double> hm3 = new HashMap<String, Double>(); + hm3.put("p3", 50.0); + HashMap<String, Double> hm4 = new HashMap<String, Double>(); + hm4.put("p4", 50.0); + HashMap<String, Double> hm5 = new HashMap<String, Double>(); + hm5.put("p5", 50.0); + HashMap<String, Double> hm6 = new HashMap<String, Double>(); + hm6.put("p6", 50.0); + HashMap<String, Double> hm7 = new HashMap<String, Double>(); + hm7.put("p7", 50.0); + endogenousRequest.add(new EndogenousRequest(hm1, 5)); + endogenousRequest.add(new EndogenousRequest(hm2, 3)); + endogenousRequest.add(new EndogenousRequest(hm3, 1)); + endogenousRequest.add(new EndogenousRequest(hm4, 2)); + endogenousRequest.add(new EndogenousRequest(hm5, 0)); + endogenousRequest.add(new EndogenousRequest(hm6, 5)); + endogenousRequest.add(new EndogenousRequest(hm7, 3)); + + System.out.println(endogenousRequest); + + while(endogenousRequest.size()>0){ + System.out.println(endogenousRequest.poll()); + } + System.out.println(endogenousRequest.poll()); + } + + + public static void testBruitGaussien() { + + double noiseVariance = 0.1; + double noiseMean = 0; + + double max = 0; + + java.util.Random r = new java.util.Random(); + + for(int i =0;i<100000;i++) { + double noise = r.nextGaussian() * Math.sqrt(noiseVariance) + noiseMean; + System.out.println(noise); + if(Math.abs(noise)>max) { + max = Math.abs(noise); + } + } + + System.out.println("-->" + max); + + + + } + + + public static void testCombinaisons() { + ArrayList<String> lettres = new ArrayList<String>(); + + lettres.add("a"); + lettres.add("b"); + lettres.add("c"); + lettres.add("d"); + lettres.add("e"); + lettres.add("f"); + + ArrayList<String> combinaisons = new ArrayList<String>(); + + int i = 1; + for(String lettre : lettres ) { + + for(String otherlettre : lettres.subList(i, lettres.size())) { + + combinaisons.add(lettre + otherlettre); + + } + i++; + + + } + + for(String comb : combinaisons) { + System.out.println(comb); + } + System.out.println(combinaisons.size()); + System.out.println(fact(lettres.size()) / (2*(fact(lettres.size()-2)))); + } + + public static void testCompteurTailleN() { + + int[] countIndices = new int[3]; + int[] bounds = new int[3]; + + countIndices[0]=0; + countIndices[1]=0; + countIndices[2]=0; + + bounds[0]=1; + bounds[1]=3; + bounds[2]=2; + + boolean test = true; + + int i = 0; + + System.out.println(test + " " + countIndices[0] + " " + countIndices[1] + " " + countIndices[2] ); + + while(i<100) { + + test = nextMultiDimCounter(countIndices,bounds); + + System.out.println(test + " " + countIndices[0] + " " + countIndices[1] + " " + countIndices[2] ); + + i++; + } + + } + + public static boolean nextMultiDimCounter(ArrayList<Integer> indices, ArrayList<Integer> bounds){ + + + + for(int i = 0; i<indices.size();i++) { + + if(indices.get(i)==bounds.get(i)-1) { + if(i==indices.size()-1) { + indices.set(i, 0); + return false; + } + else { + indices.set(i, 0); + } + } + else { + indices.set(i, indices.get(i)+1); + return true; + } + + } + + return false; + + + } + + private static boolean nextMultiDimCounter(int[] indices, int[] bounds){ + + + + for(int i = 0; i<indices.length;i++) { + + if(indices[i]==bounds[i]-1) { + if(i==indices.length-1) { + indices[i]=0; + return false; + } + else { + indices[i]=0; + } + } + else { + indices[i] += 1; + return true; + } + + } + + return false; + + + } + +} diff --git a/AMOEBAonAMAK/src/experiments/nDimensionsLaunchers/F_N_Launcher.java b/AMOEBAonAMAK/src/experiments/nDimensionsLaunchers/F_N_Launcher.java index 24f757410b2379ea9134d7d4849726fdc80b7aef..5a9e38b3e7007b38ae8e0c90a8bf84420d1a82eb 100644 --- a/AMOEBAonAMAK/src/experiments/nDimensionsLaunchers/F_N_Launcher.java +++ b/AMOEBAonAMAK/src/experiments/nDimensionsLaunchers/F_N_Launcher.java @@ -3,9 +3,12 @@ package experiments.nDimensionsLaunchers; import java.io.File; import java.io.IOException; import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import agents.context.Context; +import experiments.FILE; import experiments.F_XY_System; import experiments.XmlConfigGenerator; import fr.irit.smac.amak.Configuration; @@ -29,13 +32,13 @@ public class F_N_Launcher implements Serializable { public static final int regressionPoints = 100; public static final int dimension = 2; public static final double spaceSize = 50.0 ; - public static final int nbOfModels = 5 ; + public static final int nbOfModels = 3 ; public static final int normType = 2 ; public static final boolean randomExploration = true; - public static final boolean limitedToSpaceZone = false; - public static final double mappingErrorAllowed = 0.05 ; + public static final boolean limitedToSpaceZone = true; + public static final double mappingErrorAllowed = 0.03; public static final double explorationIncrement = 1.0 ; - public static final double explorationWidht = 1 ; + public static final double explorationWidht = 0.5 ; public static final int nbCycle = 1000; @@ -54,10 +57,13 @@ public class F_N_Launcher implements Serializable { public static void launch() throws IOException{ + + // Set AMAK configuration before creating an AMOEBA Configuration.commandLineMode = false; Configuration.allowedSimultaneousAgentsExecution = 1; Configuration.waitForGUI = true; + Configuration.plotMilliSecondsUpdate = 20000; AMOEBA amoeba = new AMOEBA(); StudiedSystem studiedSystem = new F_N_Manager(spaceSize, dimension, nbOfModels, normType, randomExploration, explorationIncrement,explorationWidht,limitedToSpaceZone); @@ -86,10 +92,19 @@ public class F_N_Launcher implements Serializable { // System.out.println("Done in : " + (end - start) ); - /* XP PIERRE */ -// for (int i = 0; i < 1000; ++i) { +// /* XP PIERRE */ +// +// String fileName = fileName(new ArrayList<String>(Arrays.asList("GaussiennePierre"))); +// +// FILE Pierrefile = new FILE("Pierre",fileName); +// for (int i = 0; i < nbCycle; ++i) { // studiedSystem.playOneStep(); // amoeba.learn(studiedSystem.getOutput()); +// if(amoeba.getHeadAgent().isActiveLearning()) { +// studiedSystem.setActiveLearning(true); +// studiedSystem.setSelfRequest(amoeba.getHeadAgent().getSelfRequest()); +// +// } // } // // for (int i = 0; i < 10; ++i) { @@ -97,17 +112,42 @@ public class F_N_Launcher implements Serializable { // System.out.println(studiedSystem.getOutput()); // System.out.println(amoeba.request(studiedSystem.getOutput())); // +// // } // +// Pierrefile.write(new ArrayList<String>(Arrays.asList("ID contexte","Coeff Cte","Coeff X0","Coeff X1","Min Value","Max Value"))); +// // for(Context ctxt : amoeba.getContexts()) { -// System.out.println(ctxt.toStringPierre()); +// +// writeMessage(Pierrefile, ctxt.toStringArrayPierre()); // // } +// +// +// Pierrefile.close(); + + } + + public static String fileName(ArrayList<String> infos) { + String fileName = ""; + for(String info : infos) { + fileName += info + "_"; + } - - + return fileName; + } + public static void writeMessage(FILE file, ArrayList<String> message) { + + file.initManualMessage(); + + for(String m : message) { + file.addManualMessage(m); + } + + file.sendManualMessage(); + } } diff --git a/AMOEBAonAMAK/src/experiments/nDimensionsLaunchers/F_N_Manager.java b/AMOEBAonAMAK/src/experiments/nDimensionsLaunchers/F_N_Manager.java index 2421a28ffbe2bb9da953d68b3e463468269000f1..dd8eec8e06d319f84820121fbfff7d9d5211946f 100644 --- a/AMOEBAonAMAK/src/experiments/nDimensionsLaunchers/F_N_Manager.java +++ b/AMOEBAonAMAK/src/experiments/nDimensionsLaunchers/F_N_Manager.java @@ -14,7 +14,7 @@ import kernel.StudiedSystem; public class F_N_Manager implements StudiedSystem{ /** The x. */ - double[] x ; + Double[] x ; /** The result. */ @@ -50,7 +50,7 @@ public class F_N_Manager implements StudiedSystem{ /* Parameters */ private static final double gaussianCoef = 1000; - private static final double gaussianVariance = 25; + private static final double gaussianVariance = 10; public F_N_Manager(double size, int dim, int nbOfModels, int nrmType, boolean rndExploration, double explIncrement, double explnVariation, boolean limiteToSpace) { @@ -58,10 +58,12 @@ public class F_N_Manager implements StudiedSystem{ dimension = dim; numberOfModels = nbOfModels; normType = nrmType; - x = new double[dimension]; + x = new Double[dimension]; spaceLimited = limiteToSpace; + //gaussianCoef = Math.random()*2000; + modelCoefs = new int[nbOfModels][dim+1]; modelCenterZones = new double[nbOfModels][dim]; @@ -71,7 +73,7 @@ public class F_N_Manager implements StudiedSystem{ x[i] = 0.0; modelCoefs[nb][i] = (int) (Math.random() * 500 - 255); - modelCenterZones[nb][i] = (Math.random() - 0.5) * spaceSize * 4; + modelCenterZones[nb][i] = spaceSize + (Math.random() - 0.5) * spaceSize * 2; } modelCoefs[nb][dimension] = (int) (Math.random() * 500 - 255); @@ -90,6 +92,7 @@ public class F_N_Manager implements StudiedSystem{ modelCoefs2[dimension] = (int) (Math.random() * 500 - 255); + System.out.println("ZONE 1 DISKS"); for(int nb = 0; nb<nbOfModels; nb++) { System.out.print(modelCoefs[nb][dimension] + "\t"); for(int i =0;i<dimension;i++) { @@ -97,6 +100,26 @@ public class F_N_Manager implements StudiedSystem{ } System.out.println(""); } + System.out.println(""); + + System.out.println("ZONE 2 MULTIDIM GAUSSIAN"); + System.out.println(gaussianCoef + " * exp( - ( x +" + spaceSize + ")² / 2 *" + gaussianVariance + "² )"); + System.out.println(""); + + System.out.println("ZONE 3 SQUARE"); + System.out.print(modelCoefs1[dimension] + "\t"); + for(int i =0;i<dimension;i++) { + System.out.print(modelCoefs1[i] + "\t"); + } + System.out.println(""); + System.out.print(modelCoefs2[dimension] + "\t"); + for(int i =0;i<dimension;i++) { + System.out.print(modelCoefs2[i] + "\t"); + } + System.out.println(""); + System.out.println(""); + + randomExploration= rndExploration; @@ -128,6 +151,9 @@ public class F_N_Manager implements StudiedSystem{ } else if(activeLearning) { + + + activeLearning = false; for(int i = 0 ; i < dimension ; i++) { @@ -186,75 +212,169 @@ public class F_N_Manager implements StudiedSystem{ } - public double model() { +// public double model() { +// +// +// +// /* Disc */ +// //return (x[1]*x[1] + x[0]*x[0] < spaceSize*spaceSize ) ? model1() : model2(); +// +// /* Square */ +// //return (x[1] > -spaceSize && x[1] < spaceSize && x[0] < spaceSize && x[0] > -spaceSize) ? model1() : model2() ; +// //return model1(); +// +// /* Triangle */ +// //return (x[1] > x[0]) ? model1() : model2(); +// +// /* Split */ +// //return ( x <= 0 ) ? 2*x + y : 5*x - 8*y; +// +// /* Exp */ +// //return (x[1] > 100*Math.exp(-(Math.pow(x[0]/25, 2))/2) -50) ? model1() : model2(); +// +// +// /* Cercle */ +//// double rho = Math.sqrt(x[1]*x[1] + x[0]*x[0]); +//// double start = 50.0; +//// double width = 25.0; +//// return ( (start < rho) && (rho < start + width)) ? model1() : model2(); +// +// +// /* Disques */ +// return modelN(); +// +// +// /* Gaussian model */ +// //return gaussianModel(); +// } + + + + + + + public double model(Double[] situation) { + + Double[] xRequest; + + if(situation == null) { + xRequest = x; + }else { + xRequest = situation; + } + + double[] center = new double[2]; + center[0]=0.0; + center[1]=0.0; + //return gaussianModel(xRequest, center,gaussianCoef, gaussianVariance); + + int subzone = subzone2D(xRequest); + + if(subzone == 1) { + /* Disques */ + return modelN(xRequest); + }else if (subzone == 2) { + /* Gaussian model */ + return gaussianModel(xRequest, subZoneCenter2D(2), gaussianCoef, gaussianVariance); + + }else if (subzone == 3) { + /* Square */ + return square2DModel(xRequest, subZoneCenter2D(3)); + + }else if (subzone == 4) { + /* Exp */ + return gaussianMapping2D(xRequest); + } + + return model1(); + /* Disc */ - //return (x[1]*x[1] + x[0]*x[0] < spaceSize*spaceSize ) ? model1() : model2(); + //return (y*y + x*x < spaceSize*spaceSize ) ? 2*x + y : 5*x - 8*y; /* Square */ - //return (x[1] > -spaceSize && x[1] < spaceSize && x[0] < spaceSize && x[0] > -spaceSize) ? model1() : model2() ; + //return (x1 > -spaceSize && x1 < spaceSize && x0 < spaceSize && x0 > -spaceSize) ? model1(x0,x1) : model2(x0,x1) ; //return model1(); /* Triangle */ - //return (x[1] > x[0]) ? model1() : model2(); + //return (y > x) ? 2*x + y : 5*x - 8*y; /* Split */ //return ( x <= 0 ) ? 2*x + y : 5*x - 8*y; - /* Exp */ - //return (x[1] > 100*Math.exp(-(Math.pow(x[0]/25, 2))/2) -50) ? model1() : model2(); /* Cercle */ -// double rho = Math.sqrt(x[1]*x[1] + x[0]*x[0]); +// double rho = Math.sqrt(x1*x1 + x0*x0); // double start = 50.0; // double width = 25.0; // return ( (start < rho) && (rho < start + width)) ? model1() : model2(); - /* Disques */ - //return modelN(); - /* Gaussian model */ - return gaussianModel(); + } - - - - - public double model(double[] xRequest) { + private int subzone2D(Double[] situation) { - /* Disc */ - //return (y*y + x*x < spaceSize*spaceSize ) ? 2*x + y : 5*x - 8*y; + Double[] xRequest; - /* Square */ - //return (x1 > -spaceSize && x1 < spaceSize && x0 < spaceSize && x0 > -spaceSize) ? model1(x0,x1) : model2(x0,x1) ; - //return model1(); + if(situation == null) { + xRequest = x; + }else { + xRequest = situation; + } + if(xRequest[0] > 0 && xRequest[1] > 0) { + return 1; + }else if(xRequest[0] < 0 && xRequest[1] < 0){ + return 2; + }else if(xRequest[0] < 0 && xRequest[1] > 0){ + return 3; + }else if(xRequest[0] > 0 && xRequest[1] < 0){ + return 4; + }else { + return 0; + } + - /* Triangle */ - //return (y > x) ? 2*x + y : 5*x - 8*y; - /* Split */ - //return ( x <= 0 ) ? 2*x + y : 5*x - 8*y; + } + + private double[] subZoneCenter2D(int nb) { - /* Exp */ - //return (xRequest[1] > 100*Math.exp(-(Math.pow(xRequest[0]/25, 2))/2) -50) ? model1() : model2(); + double[] center = new double[2]; - /* Cercle */ -// double rho = Math.sqrt(x1*x1 + x0*x0); -// double start = 50.0; -// double width = 25.0; -// return ( (start < rho) && (rho < start + width)) ? model1() : model2(); - - /* Disques */ - //return modelN(xRequest); + if(nb == 1) { + center[0] = spaceSize; + center[1] = spaceSize; + }else if(nb == 2) { + center[0] = -spaceSize; + center[1] = -spaceSize; + } + else if(nb == 3) { + center[0] = -spaceSize; + center[1] = spaceSize; + } + else if(nb == 4) { + center[0] = spaceSize; + center[1] = -spaceSize; + } + return center; - /* Gaussian model */ - return gaussianModel(xRequest); + } + + private double gaussianMapping2D(Double[] xRequest) { + return (xRequest[1] > 30*Math.exp(-(Math.pow((xRequest[0]-spaceSize)/5, 2))/2) -50) ? model1() : model2(); + } + + private double square2DModel(Double[] xRequest, double[] center) { + return ((center[0]-spaceSize/2) < xRequest[0] && + xRequest[0] < (center[0]+spaceSize/2) && + (center[1]-spaceSize/2) < xRequest[1] && + xRequest[1] < (center[1]+spaceSize/2)) ? model1(xRequest[0],xRequest[1]) : model2(xRequest[0],xRequest[1]) ; } private double gaussianModel() { @@ -265,12 +385,12 @@ public class F_N_Manager implements StudiedSystem{ return gaussianCoef*result; } - private double gaussianModel(double[] xRequest) { + private double gaussianModel(Double[] xRequest, double[] center, double factor, double variance) { double result = 1.0; for(int i=0;i<dimension;i++) { - result *= Math.exp(-(Math.pow(xRequest[i]/gaussianVariance, 2))/2); + result *= Math.exp(-(Math.pow((xRequest[i] - center[i])/variance, 2))/2); } - return gaussianCoef*result; + return factor*result; } private double modelN() { @@ -286,11 +406,11 @@ public class F_N_Manager implements StudiedSystem{ } - private double modelN(double[] xRequest) { + private double modelN(Double[] xRequest) { for(int nb = 0; nb<numberOfModels-1; nb++) { - if(distance(xRequest,modelCenterZones[nb]) < spaceSize) { + if(distance(xRequest,modelCenterZones[nb]) < spaceSize/2) { return modeli(nb, xRequest); } @@ -299,7 +419,7 @@ public class F_N_Manager implements StudiedSystem{ } - private double distance(double[] x1, double[] x2) { + private double distance(Double[] x1, double[] x2) { return normeP(x1,x2,normType); } @@ -313,7 +433,7 @@ public class F_N_Manager implements StudiedSystem{ - private double normeP(double[] x1, double[] x2, int p) { + private double normeP(Double[] x1, double[] x2, int p) { double distance = 0; for(int i = 0; i < x1.length; i ++) { distance += Math.pow(Math.abs(x2[i] - x1[i]), p) ; @@ -346,7 +466,7 @@ public class F_N_Manager implements StudiedSystem{ return result; } - private double modeli(int modelNb, double[] xRequest) { + private double modeli(int modelNb, Double[] xRequest) { double result = 0.0; for(int i = 0; i<dimension;i++) { result += xRequest[i]*modelCoefs[modelNb][i]; @@ -396,7 +516,7 @@ public class F_N_Manager implements StudiedSystem{ public HashMap<String, Double> getOutput() { HashMap<String, Double> out = new HashMap<String, Double>(); - result = model(); + result = model(null); for(int i = 0; i<dimension; i++) { @@ -407,10 +527,22 @@ public class F_N_Manager implements StudiedSystem{ return out; } + public HashMap<String, Double> getIntput() { + HashMap<String, Double> in = new HashMap<String, Double>(); + + + for(int i = 0; i<dimension; i++) { + + in.put("px" + i,x[i]); + + } + return in; + } + public HashMap<String, Double> getOutputWithNoise(double noiseRange) { HashMap<String, Double> out = new HashMap<String, Double>(); - result = model() - noiseRange/2 + Math.random()*noiseRange ; + result = model(null) - noiseRange/2 + Math.random()*noiseRange ; for(int i = 0; i<dimension; i++) { @@ -430,7 +562,7 @@ public class F_N_Manager implements StudiedSystem{ } - result = model() - noiseRange/2 + Math.random()*noiseRange ; + result = model(null) - noiseRange/2 + Math.random()*noiseRange ; for(int i = 0; i<dimension; i++) { @@ -449,7 +581,7 @@ public class F_N_Manager implements StudiedSystem{ } - result = model(); + result = model(null); for(int i = 0; i<dimension; i++) { @@ -470,7 +602,7 @@ public class F_N_Manager implements StudiedSystem{ x[1] = values.get("px1"); - result = model(); + result = model(null); out.put("px0",x[0]); out.put("px1",x[1]); @@ -499,7 +631,7 @@ public class F_N_Manager implements StudiedSystem{ @Override public double requestOracle(HashMap<String, Double> request) { - double[] xRequest = new double[request.size()]; + Double[] xRequest = new Double[request.size()]; for(int i = 0; i<dimension; i++) { diff --git a/AMOEBAonAMAK/src/kernel/AMOEBA.java b/AMOEBAonAMAK/src/kernel/AMOEBA.java index 61f834205e63d499a5dc039d2bb8e4c894c54a95..f85355e2613b8c49861de0c2d198ba9b442a29f8 100644 --- a/AMOEBAonAMAK/src/kernel/AMOEBA.java +++ b/AMOEBAonAMAK/src/kernel/AMOEBA.java @@ -160,14 +160,17 @@ public class AMOEBA extends Amas<World> implements IAMOEBA { gloabalMappingCriticality.addData("Current Value", cycle, head.getAverageSpatialCriticality(), notify); gloabalMappingCriticality.addData("Zero", cycle, 0.0, notify); - timeExecution.addData("HeadPlay", cycle, data.playExecutionTimeSum, notify); - timeExecution.addData("EndogenousPlay", cycle, data.endogenousExecutionTime, notify); - timeExecution.addData("ContextSelfAnalisis", cycle, data.contextSelfAnalisisExecutionTimeSum, notify); - timeExecution.addData("IncompetentNCS", cycle, data.incompetentHeadNCSExecutionTimeSum, notify); - timeExecution.addData("ConcurrenceNCS", cycle, data.concurrenceNCSExecutionTimeSum, notify); - timeExecution.addData("NewContextNCS", cycle, data.create_New_ContextNCSExecutionTimeSum, notify); - timeExecution.addData("OvermappingNCS", cycle, data.overmappingNCSExecutionTimeSum, notify); - timeExecution.addData("Other", cycle, data.otherExecutionTimeSum, notify); + timeExecution.addData("HeadPlay", cycle, data.executionTimesSums[0], notify); + timeExecution.addData("EndogenousPlay", cycle, data.executionTimesSums[1], notify); + timeExecution.addData("ContextSelfAnalisis", cycle, data.executionTimesSums[2], notify); + timeExecution.addData("IncompetentNCS", cycle, data.executionTimesSums[3], notify); + timeExecution.addData("ConcurrenceNCS", cycle, data.executionTimesSums[4], notify); + timeExecution.addData("NewContextNCS", cycle, data.executionTimesSums[5], notify); + timeExecution.addData("OvermappingNCS", cycle, data.executionTimesSums[6], notify); + timeExecution.addData("Other", cycle, data.executionTimesSums[7], notify); + timeExecution.addData("BestContextInNeighbors", cycle, data.executionTimesSums[8], notify); + timeExecution.addData("CreateContext", cycle, data.executionTimesSums[9], notify); + timeExecution.addData("UpdateStatitics", cycle, data.executionTimesSums[10], notify); criticalities.addData("Prediction", cycle, data.evolutionCriticalityPrediction, notify); criticalities.addData("Mapping", cycle, data.evolutionCriticalityMapping, notify); @@ -204,7 +207,9 @@ public class AMOEBA extends Amas<World> implements IAMOEBA { } if (studiedSystem != null) { + studiedSystem.playOneStep(); + perceptions = studiedSystem.getOutput(); @@ -241,7 +246,6 @@ public class AMOEBA extends Amas<World> implements IAMOEBA { if(studiedSystem != null) { if(head.isActiveLearning()) { - head.setActiveLearning(false); studiedSystem.setActiveLearning(true); studiedSystem.setSelfRequest(head.getSelfRequest()); @@ -662,6 +666,7 @@ public class AMOEBA extends Amas<World> implements IAMOEBA { AmoebaWindow.instance().rectangle.move(AmoebaWindow.instance().dimensionSelector.d1().getValue() - getEnvironment().getContextCreationNeighborhood(null, AmoebaWindow.instance().dimensionSelector.d1()), AmoebaWindow.instance().dimensionSelector.d2().getValue() - getEnvironment().getContextCreationNeighborhood(null, AmoebaWindow.instance().dimensionSelector.d2())); AmoebaWindow.instance().mainVUI.updateCanvas(); AmoebaWindow.instance().point.toFront(); + AmoebaWindow.instance().point.setInfo(getCursorInfo()); } /** @@ -795,5 +800,13 @@ public class AMOEBA extends Amas<World> implements IAMOEBA { validContextLock.writeLock().unlock(); } + private String getCursorInfo() { + String message = ""; + for(Percept pct : getPercepts()) { + message += pct.getName() + "\t" + pct.getValue() +"\t[ " + pct.getMin() +" ; " + pct.getMax() + " ]\n" ; + } + return message; + } + } diff --git a/AMOEBAonAMAK/src/kernel/AmoebaData.java b/AMOEBAonAMAK/src/kernel/AmoebaData.java index 40bd70dd0dc40a36a797be88a1ad26d9bcd82499..f8fa12276b77b029c06d061c0159bf79dac9955a 100644 --- a/AMOEBAonAMAK/src/kernel/AmoebaData.java +++ b/AMOEBAonAMAK/src/kernel/AmoebaData.java @@ -65,30 +65,6 @@ public class AmoebaData implements Serializable { public int currentCriticalityMapping = 0; public int currentCriticalityConfidence = 0; - public long playExecutionTime; - public long endogenousExecutionTime; - public long contextSelfAnalisisExecutionTime; - - public long incompetentHeadNCSExecutionTime; - public long concurrenceNCSExecutionTime; - public long create_New_ContextNCSExecutionTime; - public long overmappingNCSExecutionTime; - public long memoryCreationExecutionTime; - - public long otherExecutionTime; - - public long playExecutionTimeSum = 0; - public long endogenousExecutionTimeSum = 0; - public long contextSelfAnalisisExecutionTimeSum = 0; - - public long incompetentHeadNCSExecutionTimeSum = 0; - public long concurrenceNCSExecutionTimeSum = 0; - public long create_New_ContextNCSExecutionTimeSum = 0; - public long overmappingNCSExecutionTimeSum = 0; - public long memoryCreationExecutionTimeSum = 0; - - public long otherExecutionTimeSum = 0; - public double learningSpeed = 0.25; public int numberOfPointsForRegression = 50; @@ -97,4 +73,7 @@ public class AmoebaData implements Serializable { public DynamicPerformance predictionPerformance; public DynamicPerformance regressionPerformance; public DynamicPerformance mappingPerformance; + + public double[] executionTimes = new double[20]; + public double[] executionTimesSums = new double[20]; } \ No newline at end of file diff --git a/AMOEBAonAMAK/src/kernel/StudiedSystem.java b/AMOEBAonAMAK/src/kernel/StudiedSystem.java index 938b53c28f6f5d65421e01fb7ca9ba21f53cc139..60f60d3fae6d565ac711b7f1005d9109d7a6724b 100644 --- a/AMOEBAonAMAK/src/kernel/StudiedSystem.java +++ b/AMOEBAonAMAK/src/kernel/StudiedSystem.java @@ -22,6 +22,7 @@ public interface StudiedSystem extends Serializable{ * @return an {@link HashMap} containing a value for each {@link Percept} of an {@link AMOEBA} and a value for the oracle. */ public HashMap<String, Double> getOutput(); + public HashMap<String, Double> getIntput(); public HashMap<String, Double> getOutputWithNoise(double noiseRange); diff --git a/AMOEBAonAMAK/src/kernel/World.java b/AMOEBAonAMAK/src/kernel/World.java index 10bc68940040657b1793de8c1055d638e06e7e31..9bf8193262b79cf09c60bac4fe5f2720d1a1e44b 100644 --- a/AMOEBAonAMAK/src/kernel/World.java +++ b/AMOEBAonAMAK/src/kernel/World.java @@ -74,11 +74,11 @@ public class World extends Environment { } public void trace(ArrayList<String> infos) { -// String message = "" +amoeba.getCycle(); -// for(String info : infos) { -// message += " " + info; -// } -// System.out.println(message); + String message = "" +amoeba.getCycle(); + for(String info : infos) { + message += " " + info; + } + System.out.println(message); } public double getAVT_acceleration() {