Skip to content
Snippets Groups Projects
Commit 5c3db78f authored by BrunoDatoMeneses's avatar BrunoDatoMeneses
Browse files

CLN: blackbox removal

parent 715d4044
Branches
No related tags found
2 merge requests!2Merge dev into develop,!1Merge Master
Showing
with 2 additions and 2055 deletions
package mas.blackbox;
import java.io.Serializable;
import mas.agents.Agent;
import mas.agents.messages.Message;
import mas.agents.messages.MessageType;
import mas.blackbox.constraints.ConstraintFuncOneLinkOut;
import mas.blackbox.constraints.ConstraintFuncTwoLinkIn;
// TODO: Auto-generated Javadoc
/**
* The Class BBFunction.
*/
public class BBFunction extends BlackBoxAgent implements Serializable{
/** The func. */
private MathFunction func;
/** The agent A. */
private Agent agentA;
/** The agent B. */
private Agent agentB;
/** The a. */
private double a;
/** The b. */
private double b;
/** The result. */
private double result;
/**
* Instantiates a new BB function.
*/
public BBFunction() {
this.addConstraint(new ConstraintFuncTwoLinkIn(this));
this.addConstraint(new ConstraintFuncOneLinkOut(this));
//this.addConstraint(new ConstraintConnectedToOneInput(this));
}
/* (non-Javadoc)
* @see agents.Agent#play()
*/
public void play() {
super.play();
}
/* (non-Javadoc)
* @see blackbox.BlackBoxAgent#fastPlay()
*/
public void fastPlay() {
result = func.compute(a, b);
for (Agent target : targets) {
sendMessage(new Message(result, MessageType.VALUE, this), target);
}
}
/**
* Gets the func.
*
* @return the func
*/
public MathFunction getFunc() {
return func;
}
/**
* Sets the func.
*
* @param func the new func
*/
public void setFunc(MathFunction func) {
this.func = func;
}
/* (non-Javadoc)
* @see blackbox.BlackBoxAgent#computeAMessage(agents.messages.Message)
*/
@Override
public void computeAMessage(Message m) {
if (m.getType() == MessageType.VALUE) {
// Agent ag = (Agent) m.getContent();
if (m.getSender() == agentA) {
a = (double) m.getContent();
} else if (m.getSender() == agentB) {
b = (double) m.getContent();
}
}
}
/**
* Gets the agent A.
*
* @return the agent A
*/
public Agent getAgentA() {
return agentA;
}
/**
* Sets the agent A.
*
* @param agentA the new agent A
*/
public void setAgentA(Agent agentA) {
this.agentA = agentA;
}
/**
* Gets the agent B.
*
* @return the agent B
*/
public Agent getAgentB() {
return agentB;
}
/**
* Sets the agent B.
*
* @param agentB the new agent B
*/
public void setAgentB(Agent agentB) {
this.agentB = agentB;
}
/* (non-Javadoc)
* @see blackbox.BlackBoxAgent#getValue()
*/
public double getValue() {
return result;
}
/**
* Adds the input agent.
*
* @param agent the agent
*/
public void addInputAgent (Agent agent){
if (agentA == null) {
agentA = agent;
} else if (agentB == null) {
agentB = agent;
}
}
/**
* Count free input slot.
*
* @return the int
*/
public int countFreeInputSlot() {
if (agentA == null) {
if (agentB == null) {
return 2;
} else {
return 1;
}
}
else {
if (agentB == null) {
return 1;
} else {
return 0;
}
}
}
/**
* Own specific input.
*
* @param a the a
* @return true, if successful
*/
public boolean ownSpecificInput(Agent a) {
return agentA == a || agentB == a;
}
/**
* Checks if is looping itself.
*
* @return true, if is looping itself
*/
public boolean isLoopingItself() {
return agentA == this || agentB == this;
}
}
package mas.blackbox;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Random;
import mas.kernel.Scheduler;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import mas.agents.Agent;
// TODO: Auto-generated Javadoc
/**
* The Class BlackBox.
*/
public class BlackBox implements Serializable {
/** The scheduler. */
private Scheduler scheduler;
/** The black box agents. */
private HashMap<String, BlackBoxAgent> blackBoxAgents = new HashMap<String, BlackBoxAgent>();
/** The n probes. */
private int nProbes = -1; //Only used with the Unity simulation
/**
* Instantiates a new black box.
*
* @param scheduler the scheduler
* @param systemFile the system file
*/
public BlackBox(Scheduler scheduler, File sourceFile) {
System.out.println("---Initialize the blackbox---");
this.scheduler = scheduler;
buildBlackBoxFromFile(sourceFile);
System.out.println("---End initialize the blackbox---");
}
/**
* Instantiates a new black box.
*/
public BlackBox() {
System.out.println("---Initialize a void blackbox---");
System.out.println("---End initialize a void blackbox---");
}
/**
* Builds the black box from file.
*
* @param systemFile the system file
*/
public void buildBlackBoxFromFile(File systemFile) {
System.out.println("Build from file!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
SAXBuilder sxb = new SAXBuilder();
Document document;
try {
document = sxb.build(systemFile);
Element racine = document.getRootElement();
// System.out.println(racine.getName());
// <Output Name="outC" DefaultValue="0"></Output>
if (nProbes > 0) {
for (int i = 0 ; i < nProbes ; i++) {
// System.out.println("Create new output in virtual XML");
Element elem = new Element("Output");
Attribute attrName = new Attribute("Name", "out_"+i);
Attribute attrDefault = new Attribute("DefaultValue", "0");
Attribute attrPort = new Attribute("Port", ""+(15300+i+1));
elem.setAttribute(attrName);
elem.setAttribute(attrDefault);
elem.setAttribute(attrPort);
racine.getChild("Outputs").addContent(elem);
}
}
// Initialize the Input agents
System.out.println(racine.getChild("Inputs"));
System.out.println(racine.getChild("Inputs").getChildren(
"Input"));
for (Element element : racine.getChild("Inputs").getChildren(
"Input")) {
Input a = new Input();
a.setName(element.getAttributeValue("Name"));
a.setValue(Double.parseDouble(element
.getAttributeValue("DefaultValue")));
// System.out.println("v" + a.getValue());
registerBlackBoxAgent(a);
}
// Initialize the Functions agents
for (Element element : racine.getChild("Functions").getChildren(
"Function")) {
BBFunction a = new BBFunction();
a.setName(element.getAttributeValue("Name"));
a.setFunc(MathFunction.valueOf(element
.getAttributeValue("Func")));
registerBlackBoxAgent(a);
}
// Initialize the Output agents
for (Element element : racine.getChild("Outputs").getChildren(
"Output")) {
// System.out.println("Initialize output");
Output a = new Output();
a.setName(element.getAttributeValue("Name"));
if (element.getAttributeValue("Port") != null) a.setPort(Integer.parseInt(element.getAttributeValue("Port")));
a.setValue(Double.parseDouble(element
.getAttributeValue("DefaultValue")));
a.setInput((Input) blackBoxAgents.get(element.getAttributeValue("Input")));
registerBlackBoxAgent(a);
}
createLinks(racine);
} catch (JDOMException | IOException e) {
e.printStackTrace();
}
}
/**
* Creates the links.
*
* @param root the root
*/
private void createLinks(Element root) {
// Initialize the Input agents
for (Element element : root.getChild("Inputs").getChildren("Input")) {
for (Element target : element.getChildren("Target")) {
blackBoxAgents
.get(element.getAttribute("Name").getValue())
.getTargets()
.add(blackBoxAgents.get(target.getAttribute("Name")
.getValue()));
}
}
// Initialize the Output agents
for (Element element : root.getChild("Outputs").getChildren("Output")) {
for (Element target : element.getChildren("Target")) {
blackBoxAgents
.get(element.getAttribute("Name").getValue())
.getTargets()
.add(blackBoxAgents.get(target.getAttribute("Name")
.getValue()));
}
}
// Initialize the Function agents
for (Element element : root.getChild("Functions").getChildren(
"Function")) {
for (Element target : element.getChildren("Target")) {
blackBoxAgents
.get(element.getAttribute("Name").getValue())
.getTargets()
.add(blackBoxAgents.get(target.getAttribute("Name")
.getValue()));
}
((BBFunction) (blackBoxAgents.get(element.getAttribute("Name")
.getValue()))).setAgentA(blackBoxAgents.get(element
.getChild("InputA").getAttributeValue("Name")));
((BBFunction) (blackBoxAgents.get(element.getAttribute("Name")
.getValue()))).setAgentB(blackBoxAgents.get(element
.getChild("InputB").getAttributeValue("Name")));
}
}
/**
* Gets the agent by name.
*
* @param name the name
* @return the agent by name
*/
private Agent getAgentByName(String name) {
return blackBoxAgents.get(name);
}
/**
* Register a new agent in the black box and in the scheduler.
*
* @param a the a
*/
public void registerBlackBoxAgent(BlackBoxAgent a) {
if (scheduler != null) {
scheduler.registerAgent(a);
}
blackBoxAgents.put(a.getName(), a);
}
/**
* Gets the scheduler.
*
* @return the scheduler
*/
public Scheduler getScheduler() {
return scheduler;
}
/**
* Sets the scheduler.
*
* @param scheduler the new scheduler
*/
public void setScheduler(Scheduler scheduler) {
this.scheduler = scheduler;
}
/**
* Gets the black box agents.
*
* @return the black box agents
*/
public HashMap<String, BlackBoxAgent> getBlackBoxAgents() {
return blackBoxAgents;
}
/**
* Gets the BB aof classes.
*
* @param classes the classes
* @return the BB aof classes
*/
public ArrayList<BlackBoxAgent> getBBAofClasses(Class<?> classes[]) {
ArrayList<BlackBoxAgent> list = new ArrayList<BlackBoxAgent>();
for (String k : blackBoxAgents.keySet()) {
for (Class<?> cl : classes) {
if (cl.isInstance(blackBoxAgents.get(k))) {
list.add(blackBoxAgents.get(k));
}
}
}
long seed = System.nanoTime();
Collections.shuffle(list, new Random(seed));
return list;
}
/**
* Sets the black box agents.
*
* @param blackBoxAgents the black box agents
*/
public void setBlackBoxAgents(HashMap<String, BlackBoxAgent> blackBoxAgents) {
this.blackBoxAgents = blackBoxAgents;
}
/**
* Gets the n probes.
*
* @return the n probes
*/
public int getnProbes() {
return nProbes;
}
/**
* Sets the n probes.
*
* @param nProbes the new n probes
*/
public void setnProbes(int nProbes) {
this.nProbes = nProbes;
}
}
package mas.blackbox;
import java.io.Serializable;
import java.util.ArrayList;
import mas.agents.Agent;
import mas.agents.messages.Message;
import mas.blackbox.constraints.Constraint;
// TODO: Auto-generated Javadoc
/**
* The Class BlackBoxAgent.
*/
public abstract class BlackBoxAgent extends Agent implements Serializable {
/** The targets. */
protected ArrayList<Agent> targets = new ArrayList<Agent>();
/** The criticity. */
/*For generator*/
protected double criticity;
/** The constraints. */
protected ArrayList<Constraint> constraints = new ArrayList<Constraint>();
/* (non-Javadoc)
* @see agents.Agent#computeAMessage(agents.messages.Message)
*/
@Override
public abstract void computeAMessage(Message m);
/**
* Gets the targets.
*
* @return the targets
*/
public ArrayList<Agent> getTargets() {
return targets;
}
/**
* Sets the targets.
*
* @param targets the new targets
*/
public void setTargets(ArrayList<Agent> targets) {
this.targets = targets;
}
/* (non-Javadoc)
* @see agents.Agent#readMessage()
*/
public void readMessage() {
// System.out.println("Play : " + this.getName());
super.readMessage();
fastPlay();
}
/**
* Gets the value.
*
* @return the value
*/
public abstract double getValue();
/**
* Fast play.
*/
public abstract void fastPlay();
/**
* Compute criticity.
*/
public void computeCriticity() {
criticity = 0;
for (Constraint c : constraints) {
if (!c.checkConstraint()) {
criticity += c.getCriticity();
}
}
}
/**
* Gets the worst constraint.
*
* @return the worst constraint
*/
public Constraint getWorstConstraint() {
Constraint constraint = null;
for (Constraint c : constraints) {
if (!c.checkConstraint() && (constraint == null || constraint.getCriticity() < c.getCriticity())) {
constraint = c;
}
}
return constraint;
}
/**
* Gets the criticity.
*
* @return the criticity
*/
public double getCriticity() {
computeCriticity();
return criticity;
}
/**
* Sets the criticity.
*
* @param criticity the new criticity
*/
public void setCriticity(double criticity) {
this.criticity = criticity;
}
/**
* Gets the constraints.
*
* @return the constraints
*/
public ArrayList<Constraint> getConstraints() {
return constraints;
}
/**
* Sets the constraints.
*
* @param constraints the new constraints
*/
public void setConstraints(ArrayList<Constraint> constraints) {
this.constraints = constraints;
}
/**
* Adds the constraint.
*
* @param c the c
*/
public void addConstraint(Constraint c) {
constraints.add(c);
}
}
package mas.blackbox;
import java.io.Serializable;
import mas.agents.Agent;
import mas.agents.messages.Message;
import mas.agents.messages.MessageType;
// TODO: Auto-generated Javadoc
/**
* The Class Input.
*/
public class Input extends BlackBoxAgent implements Serializable {
/** The func. */
private BBFunction func;
/** The value. */
private double value;
/** The next value. */
private double nextValue;
/* (non-Javadoc)
* @see agents.Agent#play()
*/
public void play() {
super.play();
}
/* (non-Javadoc)
* @see blackbox.BlackBoxAgent#fastPlay()
*/
public void fastPlay() {
value = nextValue;
for (Agent target : targets) {
sendMessage(new Message(value, MessageType.VALUE, this), target);
}
}
/**
* Gets the func.
*
* @return the func
*/
public BBFunction getFunc() {
return func;
}
/**
* Sets the func.
*
* @param func the new func
*/
public void setFunc(BBFunction func) {
this.func = func;
}
/* (non-Javadoc)
* @see blackbox.BlackBoxAgent#getValue()
*/
public double getValue() {
return value;
}
/**
* Sets the value.
*
* @param value the new value
*/
public void setValue(double value) {
this.value = value;
this.nextValue = value;
}
/* (non-Javadoc)
* @see blackbox.BlackBoxAgent#computeAMessage(agents.messages.Message)
*/
@Override
public void computeAMessage(Message m) {
if (m.getType() == MessageType.VALUE) {
value = (double) m.getContent();
}
}
/**
* Mult value.
*
* @param factor the factor
*/
public void multValue(double factor) {
value *= factor;
}
/**
* Gets the next value.
*
* @return the next value
*/
public double getNextValue() {
return nextValue;
}
/**
* Sets the next value.
*
* @param nextValue the new next value
*/
public void setNextValue(double nextValue) {
this.nextValue = nextValue;
}
}
package mas.blackbox;
import java.io.Serializable;
// TODO: Auto-generated Javadoc
/**
* The different functions allowed for the agent "Function" to use.
* The enum name is the name which must be write in the XML config file.
* @author nigon
*
*/
public enum MathFunction implements Serializable {
/** The plus. */
PLUS("+"),
/** The mult. */
MULT("*"),
/** The minus. */
MINUS("-"),
/** The divide. */
DIVIDE("/"),
/** The between. */
BETWEEN("<...<"),
/** The int between. */
INT_BETWEEN("int<...<"),
/** The or. */
OR("||"),
/** The and. */
AND("&&"),
/** The xor. */
XOR("xor"),
/** The is part of unit circle. */
IS_PART_OF_UNIT_CIRCLE("unit_circle"),
/** The euclide. */
EUCLIDE("euclide"),
/** The mountain car. */
MOUNTAIN_CAR("mountain"),
/** The cos plus. */
COS_PLUS("cos+");
/** The symbol. */
private final String symbol;
/**
* Instantiates a new math function.
*
* @param symbol the symbol
*/
private MathFunction(String symbol) {
this.symbol = symbol;
}
/**
* Compute.
*
* @param a the a
* @param b the b
* @return the double
*/
public double compute(double a, double b) {
switch (this) {
case PLUS:
return a + b;
case MINUS:
return a - b;
case DIVIDE:
return a / b;
case MULT:
return a * b;
case INT_BETWEEN:
return ((int)(Math.random() * ((Math.max(a,b) - Math.min(a,b)+2))+ Math.min(a, b) - 1));
case BETWEEN:
return Math.random() * (Math.max(a,b) - Math.min(a,b))+ Math.min(a, b);
case OR:
return (a >= 0 || b >= 0) ? 1.0 : -1.0;
case XOR:
return ((a >= 0 && b < 0) || (a < 0 && b >= 0)) ? 1.0 : -1.0;
case AND:
return (a >= 0 && b >= 0) ? 1.0 : -1.0;
case IS_PART_OF_UNIT_CIRCLE:
return (Math.sqrt((a*a) + (b*b)) <= 1 ? 1.0 : -1.0);
case EUCLIDE:
return (Math.sqrt((a*a) + (b*b)));
case MOUNTAIN_CAR:
return ((a*0.001) + (Math.cos(3*b) * -0.0025));
case COS_PLUS:
return (Math.cos(a) + b);
default:
return 0.0;
}
}
/**
* Gets the symbol.
*
* @return the symbol
*/
public String getSymbol() {
return symbol;
}
}
package mas.blackbox;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import mas.agents.messages.Message;
import mas.agents.messages.MessageType;
import mas.blackbox.constraints.ConstraintOutOneLinkIn;
// TODO: Auto-generated Javadoc
/**
* An output from the simulator.
*
*/
public class Output extends BlackBoxAgent implements Serializable {
/** The func. */
private BBFunction func;
/** The value. */
private double value;
/** The input. */
private Input input;
/** The port. */
private int port;
/** The socket. */
Socket socket;
/** The out. */
PrintWriter out;
/** The in. */
BufferedReader in;
/** The std in. */
BufferedReader stdIn;
/**
* Instantiates a new output.
*/
public Output() {
this.addConstraint(new ConstraintOutOneLinkIn(this));
}
/* (non-Javadoc)
* @see agents.Agent#play()
*/
public void play() {
super.play();
}
/* (non-Javadoc)
* @see blackbox.BlackBoxAgent#fastPlay()
*/
public void fastPlay() {
if (socket == null && port > 0) {
initSocket();
}
if (socket != null) {
try {
String s = in.readLine();
// System.out.println(s);
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number;
try {
String[] sp = s.split("##");
number = format.parse(sp[sp.length-1]);
if (sp.length > 1) {
System.out.println(sp[0]);
this.name = sp[0];
}
value = number.doubleValue();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (input != null) {
input.setNextValue(value);
}
}
/**
* Inits the socket.
*/
public void initSocket() {
System.out.println("Init socket for " + name);
try {
System.out.println("Trying to connect to port : " + port);
socket = new Socket(InetAddress.getByName(null), port); //Loopback host
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
stdIn = new BufferedReader(
new InputStreamReader(System.in));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/* (non-Javadoc)
* @see blackbox.BlackBoxAgent#computeAMessage(agents.messages.Message)
*/
@Override
public void computeAMessage(Message m) {
if (m.getType() == MessageType.VALUE) {
value = (double) m.getContent();
}
}
/**
* Gets the func.
*
* @return the func
*/
public BBFunction getFunc() {
return func;
}
/**
* Sets the func.
*
* @param func the new func
*/
public void setFunc(BBFunction func) {
this.func = func;
}
/* (non-Javadoc)
* @see blackbox.BlackBoxAgent#getValue()
*/
public double getValue() {
return value;
}
/**
* Sets the value.
*
* @param value the new value
*/
public void setValue(double value) {
this.value = value;
}
/**
* Gets the input.
*
* @return the input
*/
public Input getInput() {
return input;
}
/**
* Sets the input.
*
* @param input the new input
*/
public void setInput(Input input) {
this.input = input;
}
/**
* Gets the port.
*
* @return the port
*/
public int getPort() {
return port;
}
/**
* Sets the port.
*
* @param port the new port
*/
public void setPort(int port) {
this.port = port;
}
}
package mas.blackbox.constraints;
import java.io.Serializable;
import mas.blackbox.BlackBox;
// TODO: Auto-generated Javadoc
/**
* The Class Constraint.
*/
public abstract class Constraint implements Serializable {
/** The criticity. */
protected double criticity;
/**
* Gets the criticity.
*
* @return the criticity
*/
public double getCriticity() {
return criticity;
}
/**
* Sets the criticity.
*
* @param criticity the new criticity
*/
public void setCriticity(double criticity) {
this.criticity = criticity;
}
/**
* Check constraint.
*
* @return true, if successful
*/
public abstract boolean checkConstraint();
/**
* Solve constraint.
*
* @param bb the bb
* @return true, if successful
*/
public abstract boolean solveConstraint(BlackBox bb);
}
package mas.blackbox.constraints;
import java.io.Serializable;
import java.util.ArrayList;
import mas.agents.Agent;
import mas.blackbox.BBFunction;
import mas.blackbox.BlackBox;
import mas.blackbox.Input;
// TODO: Auto-generated Javadoc
/**
* The Class ConstraintConnectedToOneInput.
*/
public class ConstraintConnectedToOneInput extends Constraint implements Serializable{
/** The function. */
BBFunction function;
/**
* Instantiates a new constraint connected to one input.
*
* @param function the function
*/
public ConstraintConnectedToOneInput(BBFunction function) {
criticity = 2.0;
this.function = function;
}
/* (non-Javadoc)
* @see blackbox.constraints.Constraint#checkConstraint()
*/
@Override
public boolean checkConstraint() {
ArrayList<BBFunction> listedAgents = new ArrayList<BBFunction>();
return recCheckConstraint(function,listedAgents);
}
/**
* Rec check constraint.
*
* @param func the func
* @param listedFunction the listed function
* @return true, if successful
*/
private boolean recCheckConstraint(BBFunction func, ArrayList<BBFunction> listedFunction) {
Agent a = function.getAgentA();
Agent b = function.getAgentA();
listedFunction.add(func);
//TODO : ugly
if (a instanceof Input || b instanceof Input) {
return true;
}
if (!listedFunction.contains(a) && !listedFunction.contains(b)) {
return recCheckConstraint((BBFunction) a,listedFunction) || recCheckConstraint((BBFunction) b,listedFunction);
}
if (!listedFunction.contains(a) && listedFunction.contains(b)) {
return recCheckConstraint((BBFunction) a,listedFunction);
}
if (listedFunction.contains(a) && !listedFunction.contains(b)) {
return recCheckConstraint((BBFunction) b,listedFunction);
}
if (listedFunction.contains(a) && listedFunction.contains(b)) {
return false;
}
return false;
}
/* (non-Javadoc)
* @see blackbox.constraints.Constraint#solveConstraint(blackbox.BlackBox)
*/
@Override
public boolean solveConstraint(BlackBox bb) {
System.out.println("solve constraint input");
return true;
}
}
package mas.blackbox.constraints;
import java.io.Serializable;
import java.util.ArrayList;
import mas.agents.Agent;
import mas.blackbox.BBFunction;
import mas.blackbox.BlackBox;
import mas.blackbox.Input;
// TODO: Auto-generated Javadoc
/**
* The Class ConstraintConnectedToOneOutput.
*/
public class ConstraintConnectedToOneOutput extends Constraint implements Serializable{
/** The BB function. */
BBFunction BBFunction;
/**
* Instantiates a new constraint connected to one output.
*
* @param BBFunction the BB function
*/
public ConstraintConnectedToOneOutput(BBFunction BBFunction) {
criticity = 2.0;
this.BBFunction = BBFunction;
}
/* (non-Javadoc)
* @see blackbox.constraints.Constraint#checkConstraint()
*/
@Override
public boolean checkConstraint() {
ArrayList<BBFunction> listedAgents = new ArrayList<BBFunction>();
return recCheckConstraint(BBFunction,listedAgents);
}
/**
* Rec check constraint.
*
* @param func the func
* @param listedBBFunction the listed BB function
* @return true, if successful
*/
private boolean recCheckConstraint(BBFunction func, ArrayList<BBFunction> listedBBFunction) {
Agent a = BBFunction.getAgentA();
Agent b = BBFunction.getAgentA();
listedBBFunction.add(func);
//TODO : ugly
if (a instanceof Input || b instanceof Input) {
return true;
}
if (!listedBBFunction.contains(a) && !listedBBFunction.contains(b)) {
return recCheckConstraint((BBFunction) a,listedBBFunction) || recCheckConstraint((BBFunction) b,listedBBFunction);
}
if (!listedBBFunction.contains(a) && listedBBFunction.contains(b)) {
return recCheckConstraint((BBFunction) a,listedBBFunction);
}
if (listedBBFunction.contains(a) && !listedBBFunction.contains(b)) {
return recCheckConstraint((BBFunction) b,listedBBFunction);
}
if (listedBBFunction.contains(a) && listedBBFunction.contains(b)) {
return false;
}
return false;
}
/* (non-Javadoc)
* @see blackbox.constraints.Constraint#solveConstraint(blackbox.BlackBox)
*/
@Override
public boolean solveConstraint(BlackBox bb) {
System.out.println("solve constraint input");
return true;
}
}
package mas.blackbox.constraints;
import java.io.Serializable;
import java.util.ArrayList;
import mas.blackbox.BBFunction;
import mas.blackbox.BlackBox;
import mas.blackbox.BlackBoxAgent;
import mas.blackbox.Output;
// TODO: Auto-generated Javadoc
/**
* The Class ConstraintFuncOneLinkOut.
*/
public class ConstraintFuncOneLinkOut extends Constraint implements Serializable{
/** The function. */
BBFunction function;
/**
* Instantiates a new constraint func one link out.
*
* @param function the function
*/
public ConstraintFuncOneLinkOut(BBFunction function) {
criticity = 4.0;
this.function = function;
}
/* (non-Javadoc)
* @see blackbox.constraints.Constraint#checkConstraint()
*/
@Override
public boolean checkConstraint() {
return (!function.getTargets().isEmpty() && (function.getTargets().size() > 1 || function.getTargets().get(0) != function));
}
/* (non-Javadoc)
* @see blackbox.constraints.Constraint#solveConstraint(blackbox.BlackBox)
*/
@Override
public boolean solveConstraint(BlackBox bb) {
// System.out.println("int " + blackBox.getbBAofClasses(new Class<?>[] {Function.class}).size() );
ArrayList<BlackBoxAgent> targetsAgents = bb.getBBAofClasses(new Class<?>[] {Output.class , BBFunction.class});
for (BlackBoxAgent bba : targetsAgents) {
if (bba instanceof Output) {
if (((Output) bba).getFunc() == null) {
((Output) bba).setFunc(function);
function.getTargets().add(bba);
return true;
}
}
if (bba instanceof BBFunction) {
if (((BBFunction) bba).countFreeInputSlot() > 0 && !((BBFunction) bba).ownSpecificInput(function)) {
((BBFunction) bba).addInputAgent(function);
function.getTargets().add(bba);
return true;
}
}
}
return false;
}
}
package mas.blackbox.constraints;
import java.io.Serializable;
import java.util.ArrayList;
import mas.blackbox.BBFunction;
import mas.blackbox.BlackBox;
import mas.blackbox.BlackBoxAgent;
import mas.blackbox.Input;
// TODO: Auto-generated Javadoc
/**
* The Class ConstraintFuncTwoLinkIn.
*/
public class ConstraintFuncTwoLinkIn extends Constraint implements Serializable{
/** The function. */
BBFunction function;
/**
* Instantiates a new constraint func two link in.
*
* @param function the function
*/
public ConstraintFuncTwoLinkIn(BBFunction function) {
criticity = 5.0;
this.function = function;
}
/* (non-Javadoc)
* @see blackbox.constraints.Constraint#checkConstraint()
*/
@Override
public boolean checkConstraint() {
return function.getAgentA() != null && function.getAgentB() != null;
}
/* (non-Javadoc)
* @see blackbox.constraints.Constraint#solveConstraint(blackbox.BlackBox)
*/
@Override
public boolean solveConstraint(BlackBox bb) {
// System.out.println("int " + blackBox.getbBAofClasses(new Class<?>[] {Function.class}).size() );
ArrayList<BlackBoxAgent> targetsAgents = bb.getBBAofClasses(new Class<?>[] {Input.class});
for (BlackBoxAgent bba : targetsAgents) {
if (bba instanceof Input) {
if (bba.getTargets().isEmpty()) {
bba.getTargets().add(function);
function.addInputAgent(bba);
return true;
}
}
}
targetsAgents = bb.getBBAofClasses(new Class<?>[] {BBFunction.class});
for (BlackBoxAgent bba : targetsAgents) {
if (bba instanceof BBFunction) {
if (function.getTargets().isEmpty()) {
bba.getTargets().add(function);
function.addInputAgent(bba);
return true;
}
}
}
for (BlackBoxAgent bba : targetsAgents) {
if (bba instanceof BBFunction) {
if ((!function.isLoopingItself() || bba != function) && !function.ownSpecificInput(bba)) {
bba.getTargets().add(function);
function.addInputAgent(bba);
return true;
}
}
}
for (BlackBoxAgent bba : targetsAgents) {
if (bba instanceof Input) {
bba.getTargets().add(function);
function.addInputAgent(bba);
return true;
}
}
return false;
}
}
package mas.blackbox.constraints;
import java.io.Serializable;
import java.util.ArrayList;
import mas.blackbox.BBFunction;
import mas.blackbox.BlackBox;
import mas.blackbox.BlackBoxAgent;
import mas.blackbox.Output;
// TODO: Auto-generated Javadoc
/**
* The Class ConstraintOutOneLinkIn.
*/
public class ConstraintOutOneLinkIn extends Constraint implements Serializable{
/** The output. */
Output output;
/**
* Instantiates a new constraint out one link in.
*
* @param output the output
*/
public ConstraintOutOneLinkIn(Output output) {
criticity = 1.0;
this.output = output;
}
/* (non-Javadoc)
* @see blackbox.constraints.Constraint#checkConstraint()
*/
@Override
public boolean checkConstraint() {
return output.getFunc() != null;
}
/* (non-Javadoc)
* @see blackbox.constraints.Constraint#solveConstraint(blackbox.BlackBox)
*/
@Override
public boolean solveConstraint(BlackBox bb) {
// System.out.println("int " + blackBox.getbBAofClasses(new Class<?>[] {Function.class}).size() );
ArrayList<BlackBoxAgent> targetsAgents = bb.getBBAofClasses(new Class<?>[] {BBFunction.class});
for (BlackBoxAgent bba : targetsAgents) {
if (bba instanceof BBFunction) {
if (bba.getTargets().isEmpty()) {
bba.getTargets().add(output);
output.setFunc((BBFunction) bba);;
return true;
}
}
}
for (BlackBoxAgent bba : targetsAgents) {
if (bba instanceof BBFunction) {
if (!bba.getTargets().stream().anyMatch(a -> a instanceof Output)) {
System.out.println("output connect");
bba.getTargets().add(output);
output.setFunc((BBFunction) bba);;
return true;
}
}
}
return false;
}
}
package visualization.view.blackbox;
import java.util.HashMap;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import mas.kernel.World;
import mas.blackbox.BlackBox;
import mas.blackbox.BlackBoxAgent;
// TODO: Auto-generated Javadoc
/**
* The Class BlackBoxPanel.
*/
public class BlackBoxPanel extends JPanel{
/** The table model. */
DefaultTableModel tableModel;
/** The world. */
private World world;
/** The graph panel. */
GrapheBlackBoxPanel graphPanel;
/**
* Instantiates a new black box panel.
*
* @param world the world
*/
public BlackBoxPanel(World world) {
this.world = world;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
JSplitPane splitPane_1 = new JSplitPane();
add(splitPane_1);
graphPanel = new GrapheBlackBoxPanel();
splitPane_1.setLeftComponent(graphPanel);
String col[] = {"Type","Name","ID","Value"};
tableModel = new DefaultTableModel(col, 0);
update();
JTable table = new JTable(tableModel);
splitPane_1.setRightComponent(table);
}
/**
* Update.
*/
public void update(){
tableModel.setRowCount(0);
Object[] entete = {"TYPE","NAME","ID","VALUE"};
tableModel.addRow(entete);
//BlackBox bb = world.getBlackbox();
//HashMap<String, BlackBoxAgent> hashAgents = bb.getBlackBoxAgents();
// for (String s : hashAgents.keySet()) {
// BlackBoxAgent a = hashAgents.get(s);
// Object[] data = {
// a.getClass().getSimpleName(),
// a.getName(),
// a.getID(),
// a.getValue()
// };
// tableModel.addRow(data);
// }
graphPanel.update();
}
/**
* Gets the table model.
*
* @return the table model
*/
public DefaultTableModel getTableModel() {
return tableModel;
}
/**
* Sets the table model.
*
* @param tableModel the new table model
*/
public void setTableModel(DefaultTableModel tableModel) {
this.tableModel = tableModel;
}
/**
* Gets the world.
*
* @return the world
*/
public World getWorld() {
return world;
}
/**
* Sets the world.
*
* @param world the new world
*/
public void setWorld(World world) {
this.world = world;
}
/**
* Sets the black box.
*
* @param blackBox the new black box
*/
public void setBlackBox(BlackBox blackBox) {
graphPanel.setBlackBox(blackBox);
}
}
package visualization.view.blackbox;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputListener;
import mas.kernel.Config;
import org.graphstream.graph.Graph;
import org.graphstream.graph.implementations.SingleGraph;
import org.graphstream.ui.view.Viewer;
import org.graphstream.ui.view.ViewerListener;
import org.graphstream.ui.view.ViewerPipe;
import mas.agents.Agent;
import mas.blackbox.BBFunction;
import mas.blackbox.BlackBox;
import mas.blackbox.BlackBoxAgent;
import mas.blackbox.Input;
import mas.blackbox.MathFunction;
// TODO: Auto-generated Javadoc
/**
* The Class GrapheBlackBoxPanel.
*/
public class GrapheBlackBoxPanel extends JPanel implements MouseInputListener, ViewerListener{
/** The graph. */
Graph graph;
/** The viewer. */
Viewer viewer;
/** The black box. */
BlackBox blackBox;
/** The tool bar. */
/* ----ToolBar Components----*/
private JToolBar toolBar;
/** The button show value. */
private JButton buttonShowValue;
/** The button show default. */
private JButton buttonShowDefault;
/** The button show name. */
private JButton buttonShowName;
/** The view mode. */
private int viewMode = 0;
/** The pipe. */
/*Interaction with simulator*/
private ViewerPipe pipe;
/** The mouse event. */
private MouseEvent mouseEvent;
/** The right click. */
Boolean rightClick = false;
/**
* Instantiates a new graphe black box panel.
*/
public GrapheBlackBoxPanel() {
setLayout(new BorderLayout());
this.setMinimumSize(new Dimension(400,400));
toolBar = new JToolBar(null, JToolBar.VERTICAL);
buttonShowDefault = new JButton(Config.getIcon("tag--plus.png"));
buttonShowDefault.addActionListener(e -> {showDefault();});
toolBar.add(buttonShowDefault);
buttonShowValue = new JButton(Config.getIcon("tag--exclamation.png"));
buttonShowValue.addActionListener(e -> {showValue();});
toolBar.add(buttonShowValue);
buttonShowName = new JButton(Config.getIcon("tag.png"));
buttonShowName.addActionListener(e -> {showName();});
toolBar.add(buttonShowName);
toolBar.addSeparator();
//update();
}
/**
* Show value.
*/
public void showValue() {
viewMode = 1;
if (blackBox != null) {
for (String name : blackBox.getBlackBoxAgents().keySet()) {
BlackBoxAgent bba = blackBox.getBlackBoxAgents().get(name);
graph.getNode(bba.getName()).setAttribute("ui.label", bba.getValue());
}
}
}
/**
* Show default.
*/
public void showDefault() {
viewMode = 0;
if (blackBox != null) {
for (String name : blackBox.getBlackBoxAgents().keySet()) {
BlackBoxAgent bba = blackBox.getBlackBoxAgents().get(name);
graph.getNode(bba.getName()).setAttribute("ui.label", bba.getName() + " " + bba.getValue());
}
}
}
/**
* Show name.
*/
public void showName() {
viewMode = 2;
if (blackBox != null) {
for (String name : blackBox.getBlackBoxAgents().keySet()) {
BlackBoxAgent bba = blackBox.getBlackBoxAgents().get(name);
graph.getNode(bba.getName()).setAttribute("ui.label", bba.getName());
}
}
}
/**
* Sets the black box.
*
* @param blackBox the new black box
*/
public void setBlackBox(BlackBox blackBox) {
this.blackBox = blackBox;
createGraph();
}
/**
* Update.
*/
public void update () {
switch(viewMode) {
case 0 :
showDefault();
break;
case 1 :
showValue();
break;
case 2 :
showName();
break;
}
}
/**
* Creates the graph.
*/
private void createGraph() {
graph = new SingleGraph("BLACK BOX");
for (String name : blackBox.getBlackBoxAgents().keySet()) {
BlackBoxAgent bba = blackBox.getBlackBoxAgents().get(name);
//graph.addAttribute("ui.stylesheet", "url('file:"+System.getProperty("user.dir")+"/bin/styles/styleBlackBox.css')");
graph.addAttribute("ui.stylesheet", "url('" + this.getClass().getClassLoader().getResource("styleBlackBox.css") + "')");
/* graph.addAttribute("ui.stylesheet", "node { stroke-mode: plain;"
+ "fill-color: red;"
+ "shape: box;"
+ "stroke-color: yellow;"
+ " }");//text-mode
graph.addAttribute("ui.style", "shape: box;");*/
//graph.addAttribute("ui.stylesheet", "node { text-mode: normal; }");//text-mode
//graph.
graph.addNode(bba.getName());
graph.getNode(bba.getName()).addAttribute("ui.class", bba.getClass().getSimpleName());
graph.getNode(bba.getName()).addAttribute("ui.label", bba.getName());
// graph.getNode(bba.getName()).addAttribute("ui.fill-color", "red");
//graph.getNode(bba.getName()).;
//System.out.println(graph.getNode(bba.getName()).getLabe)());
}
//Draw edge
for (String name : blackBox.getBlackBoxAgents().keySet()) {
BlackBoxAgent bba = blackBox.getBlackBoxAgents().get(name);
for (Agent target : bba.getTargets()) {
graph.addEdge(bba.getName() + " " + target.getName(), bba.getName(), target.getName(), true);
}
}
viewer = new Viewer(graph, Viewer.ThreadingModel.GRAPH_IN_GUI_THREAD);
viewer.addDefaultView(false);
viewer.enableAutoLayout();
viewer.getDefaultView().addMouseListener(this);
pipe = viewer.newViewerPipe();
pipe.addViewerListener(this);
pipe.addSink(graph);
viewer.getDefaultView().setMinimumSize(new Dimension(400,400));
this.add(viewer.getDefaultView(),BorderLayout.CENTER);
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
*/
@Override
public void mouseClicked(MouseEvent e) {
mouseEvent = e;
if(SwingUtilities.isRightMouseButton(e)){
rightClick = true;
Robot bot;
try {
bot = new Robot();
int mask = InputEvent.BUTTON1_DOWN_MASK;
bot.mousePress(mask);
bot.mouseRelease(mask);
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
pipe.pump();
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
*/
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
*/
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
*/
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
*/
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
*/
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
*/
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.graphstream.ui.view.ViewerListener#buttonPushed(java.lang.String)
*/
@Override
public void buttonPushed(String id) {
System.out.println("node pushed : " + id);
if (rightClick) {
if (blackBox.getBlackBoxAgents().get(id) instanceof Input) {
popupInput(id);
} else if (blackBox.getBlackBoxAgents().get(id) instanceof BBFunction) {
popupFunction(id);
}
rightClick = false;
}
}
/* (non-Javadoc)
* @see org.graphstream.ui.view.ViewerListener#buttonReleased(java.lang.String)
*/
@Override
public void buttonReleased(String arg0) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.graphstream.ui.view.ViewerListener#viewClosed(java.lang.String)
*/
@Override
public void viewClosed(String arg0) {
// TODO Auto-generated method stub
}
/**
* Show a popup with options for function agent.
*
* @param id : the id of the agent
*/
public void popupFunction(String id){
JPopupMenu popup = new JPopupMenu("Function");
JMenu subMathFunc = new JMenu("Mathematical function");
popup.add(subMathFunc);
for (MathFunction mf : MathFunction.values()) {
JMenuItem item = new JMenuItem(mf.toString());
item.addActionListener(e -> {changeMathFunc(mf,id);});
item.setIcon(Config.getIcon("pencil.png"));
subMathFunc.add(item);
}
popup.show(this, this.getX() + mouseEvent.getX(), this.getY() + mouseEvent.getY());
}
/**
* Show a popup with options for input agent.
*
* @param id : the id of the agent
*/
public void popupInput(String id){
JPopupMenu popup = new JPopupMenu("Input");
JMenuItem itemX2 = new JMenuItem("x2");
itemX2.addActionListener(e -> {factorInput(2,id);});
itemX2.setIcon(Config.getIcon("pencil.png"));
popup.add(itemX2);
JMenuItem itemDiv2 = new JMenuItem("/2");
itemDiv2.addActionListener(e -> {factorInput(0.5,id);});
itemDiv2.setIcon(Config.getIcon("pencil.png"));
popup.add(itemDiv2);
popup.show(this, this.getX() + mouseEvent.getX(), this.getY() + mouseEvent.getY());
}
/**
* Factor input.
*
* @param factor the factor
* @param id the id
*/
private void factorInput(double factor, String id) {
((Input)blackBox.getBlackBoxAgents().get(id)).multValue(factor);
}
/**
* Change math func.
*
* @param mf the mf
* @param id the id
*/
private void changeMathFunc(MathFunction mf, String id) {
((BBFunction)blackBox.getBlackBoxAgents().get(id)).setFunc(mf);
}
}
......@@ -28,7 +28,6 @@ import visualization.observation.Observation;
import mas.agents.percept.Percept;
import mas.agents.context.Context;
import mas.agents.head.Head;
import mas.blackbox.BlackBox;
import visualization.graphView.TemporalGraph;
// TODO: Auto-generated Javadoc
......@@ -487,14 +486,7 @@ public class MainPanel extends JPanel{
}
/**
* Sets the black box.
*
* @param blackBox the new black box
*/
public void setBlackBox(BlackBox blackBox) {
if (!minimalDisplay) tabbedPanel.setBlackBox(blackBox);
}
/**
* Update.
......
......@@ -9,7 +9,6 @@ import javax.swing.JTabbedPane;
import mas.kernel.World;
import visualization.log.ConsolePanel;
import visualization.observation.Observation;
import visualization.view.blackbox.BlackBoxPanel;
import visualization.view.global.PanelChart;
import visualization.view.global.PanelChart2;
import visualization.view.global.PanelOneChart;
......@@ -18,7 +17,6 @@ import visualization.view.global.PanelExoVSEndo;
import visualization.view.system.nDim.PanelParallelCoordinates;
import visualization.view.system.twoDim.GrapheTwoDimPanelNCSMemories;
import visualization.view.system.twoDim.GrapheTwoDimPanelStandard;
import mas.blackbox.BlackBox;
import visualization.graphView.TemporalGraph;
// TODO: Auto-generated Javadoc
......@@ -123,14 +121,7 @@ public class MainTabbedPanel extends JTabbedPane{
world.getScheduler().setWaitForGUIUpdate(false);
}
/**
* Sets the black box.
*
* @param blackBox the new black box
*/
public void setBlackBox(BlackBox blackBox) {
//blackBoxPanel.setBlackBox(blackBox);
}
/**
* Update N dimension.
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment