repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
cst
cst-master/src/main/java/br/unicamp/cst/behavior/asbac/Relation.java
/** * **************************************************************************** * Copyright (c) 2018 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * R. G. Polizeli and R. R. Gudwin * **************************************************************************** */ package br.unicamp.cst.behavior.asbac; import java.util.LinkedList; import java.util.List; import java.util.Objects; /** * * @author rgpolizeli */ public class Relation { public String name; public LinkedList<Percept> percepts; public Relation(String name){ this.name = name; this.percepts = new LinkedList<>(); } public String getType(){ return this.name; } public void setType(String newType){ this.name = newType; } public List<Percept> getRelationPercepts(){ return this.percepts; } public boolean isPerceptInRelation(Percept targetPercept){ for (Percept p : this.getRelationPercepts()) { if (p.equals(targetPercept)) { return true; } } return false; } public void addPercept(Percept p){ this.percepts.add(p); } public void removePercept(Percept p){ this.percepts.remove(p); } public boolean isEquals(Relation targetRelation){ if (!this.getType().equals(targetRelation.getType())) { return false; } return this.getRelationPercepts().containsAll(targetRelation.getRelationPercepts()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Relation other = (Relation) obj; return this.isEquals(other); } @Override public int hashCode() { int hash = 5; hash = 79 * hash + Objects.hashCode(this.name); hash = 79 * hash + Objects.hashCode(this.percepts); return hash; } }
2,385
22.86
92
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/asbac/SynchronizationMethods.java
/** * **************************************************************************** * Copyright (c) 2018 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * R. G. Polizeli and R. R. Gudwin * **************************************************************************** */ package br.unicamp.cst.behavior.asbac; import br.unicamp.cst.core.entities.MemoryObject; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author rgpolizeli */ public class SynchronizationMethods { private static final Lock SYNCHRONIZER_LOCK = new ReentrantLock(); private static final Logger LOGGER = Logger.getLogger(SynchronizationMethods.class.getName()); public SynchronizationMethods() { } public static Lock getSynchronizerLock(){ return SYNCHRONIZER_LOCK; } public static void createLock(String lockName, MemoryObject synchronizerMO){ getSynchronizerLock().lock(); Map<String,MyLock> myLocks = (Map<String,MyLock>) synchronizerMO.getI(); try{ MyLock ml = new MyLock(); myLocks.put(lockName, ml); LOGGER.log(Level.INFO, "Created lock: {0}", lockName); } finally { getSynchronizerLock().unlock(); } } private static void destroyLock(String lockName, Map<String, MyLock> myLocks){ MyLock myLock = myLocks.get(lockName); if (myLock != null) { synchronized(myLock.lock){ myLocks.remove(lockName); LOGGER.log(Level.INFO, "Deleted lock: {0}", lockName); } } if (isUnlockTime(myLocks)) { unLockAll(myLocks); } } private static boolean isUnlockTime(Map<String, MyLock> myLocks){ for (Map.Entry<String, MyLock> entry : myLocks.entrySet()) { if (!entry.getValue().isLocked) { //if any lock is free return false; } } return true; //if all lock is locked } private static void unLockAll(Map<String, MyLock> myLocks){ for (Map.Entry<String, MyLock> entry : myLocks.entrySet()) { synchronized(entry.getValue().lock){ entry.getValue().unlock(); entry.getValue().lock.notify(); } } } public static void synchronize(String codeletName, MemoryObject synchronizerMO){ getSynchronizerLock().lock(); Map<String, MyLock> myLocks = (Map<String, MyLock>) synchronizerMO.getI(); MyLock myLock = myLocks.get(codeletName); myLock.lock(); if (isUnlockTime(myLocks)) { unLockAll(myLocks); getSynchronizerLock().unlock(); } else{ //wait to lock synchronized(myLock.lock){ try { getSynchronizerLock().unlock(); while(myLock.isLocked){ myLock.lock.wait(); } } catch (InterruptedException ex) { LOGGER.log(Level.SEVERE, null, ex); } } } } }
3,529
30.238938
98
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/bn/Behavior.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.bn; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.exceptions.CodeletActivationBoundsException; import br.unicamp.cst.memory.WorkingStorage; /** * This competence class extends Codelet. "A competence resemble the operators of a classical planning system. A competence module i can be described by a list of preconditions and expected effects."[Maes 1989] * * @author klaus * */ public abstract class Behavior extends Codelet { //Debug variables private boolean showActivationSpread = false; // Enable this to see the activation flow in the console private boolean showCoalitionLinks = false; // Enable this to see the coalition links in the console private boolean printNoActivationCases = false;//Enable this to see if there are any problems with absent preconditions private String name = ""; //Each behavior must have a name. If not given by the user, it will be the same as its running thread's one protected ArrayList<String> actionList = new ArrayList<String>();// Actions that are to be performed by actuators and which constitute this behavior protected JSONArray jsonActionList = new JSONArray(); protected ArrayList<Memory> preconList = new ArrayList<Memory>(); // ci list of preconditions that must be fulfilled before the competence module can become active protected ArrayList<Memory> addList = new ArrayList<Memory>(); // ai expected effects of this action in terms of an add list protected ArrayList<Memory> deleteList = new ArrayList<Memory>(); // di expected effects of this action in terms of a delete list //TODO I'm modifying MAES original model to encompass a "soft" precondition list. Is is "soft" in the sense that it is not a must have. // a soft precondition affects activation spread in the same way a traditional precondition does, but its absense does not prevent the behavior to be executed. protected ArrayList<Memory> softPreconList = new ArrayList<Memory>(); // ci list of preconditions that are desirable to be fulfilled before the competence module can become active // Alpha level of activation is the codelet's own A (activation level) [Hypothesis to be investigated] protected ArrayList<Behavior> allBehaviors = new ArrayList<Behavior>();//Pointers to all behaviors in the network. Basal ganglia should support this hypothesis. protected ArrayList<Behavior> coalition = new ArrayList<Behavior>(); //A subset of all behaviors, given by consciousness. protected Hashtable<Behavior, ArrayList<Memory>> predecessors = new Hashtable<Behavior, ArrayList<Memory>>(); protected Hashtable<Behavior, ArrayList<Memory>> successors = new Hashtable<Behavior, ArrayList<Memory>>(); protected Hashtable<Behavior, ArrayList<Memory>> conflicters = new Hashtable<Behavior, ArrayList<Memory>>(); private ArrayList<Memory> permanentGoals = new ArrayList<Memory>(); private ArrayList<Memory> onceOnlyGoals = new ArrayList<Memory>(); private ArrayList<Memory> protectedGoals = new ArrayList<Memory>(); private ArrayList<Memory> goals = new ArrayList<Memory>(); private ArrayList<Memory> worldState = new ArrayList<Memory>(); private ArrayList<Object> listOfWorldBeliefStates=new ArrayList<Object>(); private ArrayList<Object> listOfPreviousWorldBeliefStates=new ArrayList<Object>(); private GlobalVariables globalVariables; //Behavior network global variables private boolean executable; //Defines if this behavior is executable or not private boolean active; //Defines if this behavior is active at the moment private boolean firstTime; // Checks if this behaviour is trying to perform actions for the first time since it got active private double maxA=1; // maximum activation for normalization //TODO resourceList is a list of all the action buffers this behavior needs to complete its actions. private ArrayList<String> resourceList=new ArrayList<String>(); private boolean setToZeroWhenActivated=true; private double activationMA=0; private WorkingStorage ws; public Behavior(WorkingStorage ws,GlobalVariables globalVariables) { this.ws = ws; this.globalVariables = globalVariables; //All behaviors subscribe their input list to receive news from Working Storage about WORLD_STATE, and goals memory objects. int io=0; //Input list ws.registerCodelet(this, "WORLD_STATE", io); ws.registerCodelet(this, "ONCE_ONLY_GOAL", io); ws.registerCodelet(this, "PERMANENT_GOAL", io); ws.registerCodelet(this, "PERMANENT_GOAL", io); this.setExecutable(false); // Every competence starts as non-executable this.setActive(false); // Every competence starts as inactive try { setActivation(0); } catch (CodeletActivationBoundsException e) { e.printStackTrace(); }// Initial activation should be zero; this.setFirstTime(true); if(this.getName().equals("")||this.getName().equals(null)){ this.setName( this.getClass().getName()); //If the user did not set a name, lets use the name of the Class } Thread.currentThread().setName(this.getName());// If this behavior has a name, let's rename this thread's name } /** * Actions to be performed by the behavior net. Must be implemented by the user, or learned. */ public abstract void operation(); /** * This proc method runs the behavior network's cycle. And performs the actions described in operation() once this competence is activated. */ public void proc() { retrieveGoals(); // This should be done often because goals might change over time retrieveState(); // This should be done often because world state might change over time spreadActivation(); checkIfExecutable(); if (isActive()){ operation(); // operation this behavior should perform } } /** * * @return list of resources used by this behavior */ private ArrayList<String> getResourceList() {//TODO must develop this idea further return this.resourceList; } /** * @return the actionsSet */ public String getActionList()//TODO a simpler version of this might be interesting { // return actionList; try { JSONArray teste = new JSONArray(jsonActionList.toString()); } catch (JSONException e) { e.printStackTrace(); } return jsonActionList.toString(); } /** * retrieves the lists of world and self states from working storage through inputs */ private synchronized void retrieveState() { worldState.clear(); String moType; for (Memory mo : getInputs()) { if(mo!=null){ moType = mo.getName(); if (moType.equalsIgnoreCase("WORLD_STATE")) { worldState.add(mo); } } } // System.out.println("====> "+this.getId()+" worldState: "+worldState); } /** * Updates the links lists based on conscious codelets from the network * * "There is a successor link from competence module x to competence module y (x has y as successor) for every proposition p that is a member of the add list of x and also member of the precondition list of y (there can be more than one successor link between 2 competence modules)" * * "A predecessor link from module x to module y (x has y as predecessor) exists for every successor link from y to x." * * "There is a conflicter link from module x to module y (y conflicts with x) for every proposition p that is a member of the delete list of y and a member of the precondition linst of x" [Maes 1989] */ private void updateLinks()//TODO it would be best if we avoided accessing other codelet's inner states directly. How about doing all this using broadcast? { successors.clear(); predecessors.clear(); conflicters.clear(); // if(this.getId().contains("TV")){ // int a=4; // System.out.println(this.getId()); // // } ArrayList<Memory> intersection = new ArrayList<Memory>(); for (Behavior competence : coalition) { // if(competence.getId().contains("ROOM13")){ // int a=4; // System.out.println(competence.getId()); // // } if (impendingAccess(competence)) { try { if (competence != this) { //------ intersection = getIntersectionSet(this.getAddList(), competence.getListOfPreconditions()); if (!intersection.isEmpty()) { this.successors.put(competence, intersection); } intersection = getIntersectionSet(this.getAddList(), competence.getSoftPreconList()); if (!intersection.isEmpty()) { this.successors.put(competence, intersection); } //------ intersection = getIntersectionSet(this.getListOfPreconditions(), competence.getAddList()); if (!intersection.isEmpty()) { this.predecessors.put(competence, intersection); } intersection = getIntersectionSet(this.getSoftPreconList(), competence.getAddList()); if (!intersection.isEmpty()) { this.predecessors.put(competence, intersection); } //------ intersection = getIntersectionSet(competence.getListOfPreconditions(), this.getDeleteList()); // because we are looking for how this module messes up others preconditions, and thats why it must be inhibited by them if (!intersection.isEmpty()) { this.conflicters.put(competence, intersection); } intersection = getIntersectionSet(competence.getSoftPreconList(), this.getDeleteList()); // because we are looking for how this module messes up others preconditions, and thats why it must be inhibited by them if (!intersection.isEmpty()) { this.conflicters.put(competence, intersection); } } } finally { lock.unlock(); competence.lock.unlock(); } } } } /** * Retrieves the lists of goals from working storage */ private void retrieveGoals() { onceOnlyGoals.clear(); permanentGoals.clear(); protectedGoals.clear(); String moType; ArrayList<Memory> my_inputs=new ArrayList<Memory>(); my_inputs.addAll(getInputs()); for (Memory mo : my_inputs) { if(mo!=null){ moType = mo.getName(); if (moType.equalsIgnoreCase("ONCE_ONLY_GOAL")) { onceOnlyGoals.add(mo); } else if (moType.equalsIgnoreCase("PROTECTED_GOAL")) { protectedGoals.add(mo); } else if (moType.equalsIgnoreCase("PERMANENT_GOAL")) { permanentGoals.add(mo); } } } goals.clear(); goals.addAll(onceOnlyGoals); goals.addAll(protectedGoals); goals.addAll(permanentGoals); } public synchronized boolean changedWorldBeliefState() { ArrayList<Object> temp1= new ArrayList<Object>(); ArrayList<Object> temp2= new ArrayList<Object>(); temp1.addAll(listOfWorldBeliefStates); temp2.addAll(listOfPreviousWorldBeliefStates); return (!temp1.equals(temp2)); } /** * Checks if there is a current behavior proposition in working storage that is using the resources this behavior needs * @return if there is conflict of resources */ private boolean resourceConflict() {//TODO must develop this idea further boolean resourceConflict=false; ArrayList<Memory> allOfType=new ArrayList<Memory>(); if(ws!=null) allOfType.addAll(ws.getAllOfType("BEHAVIOR_PROPOSITION")); ArrayList<String> usedResources=new ArrayList<String>(); if(allOfType!=null){ for(Memory bp:allOfType){ try { JSONObject jsonBp=new JSONObject(bp.getI()); //System.out.println("=======> bp.getInfo(): "+bp.getInfo()); boolean performed=jsonBp.getBoolean("PERFORMED"); if(!performed){//otherwise it is not consuming those resources JSONArray resourceList=jsonBp.getJSONArray("RESOURCELIST"); for(int i=0;i<resourceList.length();i++){ usedResources.add(resourceList.getString(i)); } } } catch (JSONException e) {e.printStackTrace();} } } // System.out.println("%%% usedResources: "+usedResources); // System.out.println("%%% getResourceList: "+getResourceList()); int sizeBefore=usedResources.size(); usedResources.removeAll(this.getResourceList()); int sizeLater=usedResources.size(); if(sizeLater!=sizeBefore){ resourceConflict=true; // System.out.println("%%%%%%%%%%%%%%%%%%%%% There was a conflict here"); } return resourceConflict; } /** * A behavior module is executable at time t when all of its preconditions are observed to be true at time t. * */ private boolean checkIfExecutable() { listOfWorldBeliefStates = new ArrayList<Object>(); for(Memory mo:this.getInputsOfType("WORLD_STATE")){ listOfWorldBeliefStates.add(mo.getI()); // System.out.println("###########adding world state"); } ArrayList<Memory> tempPreconList=new ArrayList<Memory>(); //Comparison between two MOs is performed between their infos tempPreconList.addAll(preconList); for(Memory precon:preconList){ for(Object ws:listOfWorldBeliefStates){ if(precon.getI().equals(ws)){ tempPreconList.remove(precon); break; } } } if (tempPreconList.isEmpty()) { setExecutable(true); } else { setExecutable(false); } //TODO I should probably check for conflicts between behaviors here... return executable; } /** * 1-compute impact of state, goals and protected goals on the activation level of a module 2-compute the way the competence module activates and inhibits related modules through its successor links, predecessor links and conflicters 3- decay function ensures that the overall activation level remains constant */ private void spreadActivation() { if(!this.isActive()){ //If active, it should remain at zero double activation = 0; // TODO this can be optimized, I could get all this information with only one method (this would iterate only once through the coalition list double inputfromstate = inputFromState(); double inputfromgoals = inputFromGoals(); double takenawaybyprotectedgoals = takenAwayByProtectedGoals(); double spreadbw = spreadBw(); double spreadfw = spreadFw(); double takenaway = takenAway(); activation = inputfromstate + inputfromgoals - takenawaybyprotectedgoals + (spreadbw + spreadfw - takenaway); if(maxA<activation){//calculates maximum activation added for normalization maxA=activation; } if (!this.isActive()) { // activation = activation + this.getValue(); //TODO Without normalization activation=activation*(1-this.getActivation())/maxA+this.getActivation(); //With Normalization } //TODO I'm trying to migrate this decay property to BehaviorsWTA.java // decay();//TODO Decay process that scales the mean level of energy to pi // // activation=activation-globalVariables.getDecay(); //TODO Test with subtractive decay // if(globalVariables!=null) activation=activation*globalVariables.getDecay(); //TODO test with multiplicative decay if (activation < 0) { activation = 0; } try { this.setActivation(activation); } catch (CodeletActivationBoundsException e) { e.printStackTrace(); } }else{//should remain at zero [Maes 1989] try { this.setActivation(0); } catch (CodeletActivationBoundsException e) { e.printStackTrace(); } } } /** * Decay function. Hypothesis: each time activation is spread from/towards a module this same module inhibits/excites the activation of all other modules making the mean activation level constant. */ private void decay() { // TODO this could be optimized double activation = 0; if (!this.coalition.isEmpty()) { for (Behavior module : this.coalition) { if (impendingAccess(module)) { try { activation = activation + module.getActivation(); activation = activation / this.coalition.size(); } finally { lock.unlock(); module.lock.unlock(); } } } } } /** * @param executable * sets this competence as being executable */ public void setExecutable(boolean executable) { this.executable = executable; } /** * @return the executable */ public boolean isExecutable() { return executable; } /** * @param condition * condition to listOfPreconditions */ public void addPreconList(Memory condition) { this.preconList.add(condition); this.addInput(condition); } /** * @return deletes condition from listOfPreconditions */ public boolean delPreconList(Memory condition) { this.removesInput(condition); return preconList.remove(condition); } /** * @param condition * condition to listOfPreconditions */ public void addSoftPreconList(Memory condition) { this.softPreconList.add(condition); this.addInput(condition); } /** * @return deletes condition from listOfPreconditions */ public boolean delSoftPreconList(Memory condition) { this.removesInput(condition); return softPreconList.remove(condition); } /** * @param condition * condition to addList */ public void addAddList(Memory condition) { this.addList.add(condition); this.addOutput(condition); } /** * @return deletes condition from addList */ public boolean delAddList(Memory condition) { this.removesOutput(condition); return addList.remove(condition); } /** * @param condition * condition to deleteList */ public void addDelList(Memory condition) { this.addOutput(condition); this.deleteList.add(condition); } /** * @return deletes condition from deleteList */ public boolean delDelList(Memory condition) { this.removesOutput(condition); return deleteList.remove(condition); } /** * @param active * the active to set */ public void setActive(boolean active) { this.active = active; listOfPreviousWorldBeliefStates=listOfWorldBeliefStates; } /** * @return the active */ public boolean isActive() { return active; } /** * * @return list of preconditions */ public ArrayList<Memory> getListOfPreconditions() { return preconList; } /** * * @param listOfPreconditions * List of MemoryObjects with preconditions */ public void setListOfPreconditions(ArrayList<Memory> listOfPreconditions) { this.preconList = listOfPreconditions; } /** * * @return add list */ public ArrayList<Memory> getAddList() { return addList; } /** * * @param addList * sets the add list */ public void setAddList(ArrayList<Memory> addList) { this.addList = addList; } /** * * @return the delete list */ public ArrayList<Memory> getDeleteList() { return deleteList; } /** * * @param deleteList * sets the delete list */ public void setDeleteList(ArrayList<Memory> deleteList) { this.deleteList = deleteList; } /** * @return the coalition */ public ArrayList<Behavior> getCoalition() { return coalition; } /** * @param coalition * the coalition to set */ public void setCoalition(ArrayList<Behavior> coalition) { this.coalition = coalition; updateLinks(); // Isto soh deve ser feito quando a coalizao muda if(showCoalitionLinks){ System.out.println("************* " + getName() + "'s Links ************"); System.out.println("* successors ------"); Enumeration e = this.successors.keys(); while (e.hasMoreElements()) { Behavior module = (Behavior) e.nextElement(); if (impendingAccess(module)) { try { System.out.println("Name: " + module.getName() + " |Props: " + this.successors.get(module)); } finally { lock.unlock(); module.lock.unlock(); } } } System.out.println("* predecessors ----"); e = this.predecessors.keys(); while (e.hasMoreElements()) { Behavior module = (Behavior) e.nextElement(); if (impendingAccess(module)) { try { System.out.println(module.getName() + " |Props: " + this.predecessors.get(module)); } finally { lock.unlock(); module.lock.unlock(); } } } System.out.println("* conflicters -----"); e = this.conflicters.keys(); while (e.hasMoreElements()) { Behavior module = (Behavior) e.nextElement(); if (impendingAccess(module)) { try { System.out.println(module.getName() + " |Props: " + this.conflicters.get(module)); } finally { lock.unlock(); module.lock.unlock(); } } } System.out.println("************************************************"); } } /** * @return the successors */ public Hashtable<Behavior, ArrayList<Memory>> getSuccessors() { return successors; } /** * @param successors * the successors to set */ public void setSuccessors(Hashtable<Behavior, ArrayList<Memory>> successors) { this.successors = successors; } /** * @return the predecessors */ public Hashtable<Behavior, ArrayList<Memory>> getPredecessors() { return predecessors; } /** * @param predecessors * the predecessors to set */ public void setPredecessors(Hashtable<Behavior, ArrayList<Memory>> predecessors) { this.predecessors = predecessors; } /** * @return the conflicters */ public Hashtable<Behavior, ArrayList<Memory>> getConflicters() { return conflicters; } /** * @param conflicters * the conflicters to set */ public void setConflicters(Hashtable<Behavior, ArrayList<Memory>> conflicters) { this.conflicters = conflicters; } /** * @param name * the name of this competence */ public void setName(String name) { this.name = name; Thread.currentThread().setName(name); } /** * @return the name of this competence */ public String getName() { return name; // return Thread.currentThread().getId(); } /** * @return the amount of activation from the state */ public double inputFromState() { double activation = 0; ArrayList<Behavior> tempCodelets = new ArrayList<Behavior>(); ArrayList<Memory> THIS_softPrecon_and_ClassicPrecon=new ArrayList<Memory>(); THIS_softPrecon_and_ClassicPrecon.addAll(this.getListOfPreconditions()); THIS_softPrecon_and_ClassicPrecon.addAll(this.getSoftPreconList()); tempCodelets.addAll(this.getAllBehaviors()); if (!tempCodelets.isEmpty()) { ArrayList<Memory> intersection = getIntersectionSet(this.getWorldState(), THIS_softPrecon_and_ClassicPrecon); for (Memory j : intersection) { double sharpM = 0; for (Behavior module : tempCodelets) { if (impendingAccess(module)) { try { ArrayList<Memory> MODULE_softPrecon_and_ClassicPrecon=new ArrayList<Memory>(); MODULE_softPrecon_and_ClassicPrecon.addAll(module.getListOfPreconditions()); MODULE_softPrecon_and_ClassicPrecon.addAll(module.getSoftPreconList()); if (MODULE_softPrecon_and_ClassicPrecon.contains(j)) { sharpM = sharpM + 1; } } finally { lock.unlock(); module.lock.unlock(); } } } // What if sharpM or listOfPreconditions.size == zero? // sharpM could zero because j comes from the intersection of S and c, so if no preconditions from the module is found in world state, the intersection shall be zero // synchronized(listOfPreconditions){ if ((sharpM > 0) && (THIS_softPrecon_and_ClassicPrecon.size() > 0)) { double activationfromstate = globalVariables.getPhi() * (1 / sharpM) * (1 / (double) THIS_softPrecon_and_ClassicPrecon.size()); if (showActivationSpread) { System.out.println(this.getName() + " got " + activationfromstate + " energy from the world state"); } activation = activation + activationfromstate; } else { if(printNoActivationCases){System.out.println("No activation in the case [" + this.getName() + " getting energy from the world state]: either the number of satisfying modules is zero or there are no preconditions in this module.");} } // }//end synch } } // }//coalitionIsBusy=false; return activation; } /** * @return the allBehaviors */ public ArrayList<Behavior> getAllBehaviors() { return allBehaviors; } /** * @param allBehaviors the allBehaviors to set */ public void setAllBehaviors(ArrayList<Behavior> allBehaviors) { this.allBehaviors = allBehaviors; } /** * @return the amount of activation from goalsthis.coalition.lock(); */ public double inputFromGoals() { double activation = 0; ArrayList<Behavior> tempCodelets = new ArrayList<Behavior>(); //TODO Should we get this input from the coalition or from the full set of codelets? tempCodelets.addAll(this.getAllBehaviors()); if (!tempCodelets.isEmpty()) { ArrayList<Memory> intersection = getIntersectionSet(this.getGoals(), this.getAddList()); for (Memory j : intersection) { double sharpA = 0; for (Behavior module : tempCodelets) { if (impendingAccess(module)) { try { if (module.getAddList().contains(j)) { sharpA = sharpA + 1; } } finally { lock.unlock(); module.lock.unlock(); } } } // synchronized(this.addList){ if ((sharpA > 0) && (this.getAddList().size() > 0)) { double othermoduleActivation = globalVariables.getGamma() * ((1 / sharpA) * (1 / (double) this.getAddList().size())); if (showActivationSpread) { System.out.println(this.getName() + " receives " + othermoduleActivation + " energy from goal " + j); } activation = activation + othermoduleActivation; } else { if (showActivationSpread) { System.out.println("No activation from situation [" + this.getName() + " getting activation from goals]: either the number of satisfying modules is zero or there are no preconditions in this module."); } } // }//end synch } } // activation=activation*globalVariables.getGamma(); return activation; } /** * @return the amount of activation to be removed by the goals that are protected */ public double takenAwayByProtectedGoals() { double activation = 0; // synchronized(this.coalition){ if (!this.getCoalition().isEmpty()) { ArrayList<Memory> intersection = getIntersectionSet(this.getProtectedGoals(), this.getDeleteList()); for (Memory j : intersection) { double sharpU = 0; for (Behavior module : this.getCoalition()) { if (impendingAccess(module)) { try { if (module.getDeleteList().contains(j)) { sharpU = sharpU + 1; } } finally { lock.unlock(); module.lock.unlock(); } } } // synchronized(this.deleteList){ if ((sharpU > 0) && (this.getDeleteList().size() > 0)) { double takenEnergy = (1 / sharpU) * (1 / (double) this.getDeleteList().size()) * globalVariables.getDelta(); if (showActivationSpread) { System.out.println(this.getName() + " has " + takenEnergy + " taken away from it by protected goals."); } activation = activation + takenEnergy; } else { if (showActivationSpread) { System.out.println("No activation from situation [" + this.getName() + " having energy taken away by protected goals]: either the number of satisfying modules is zero or there are no preconditions in this module."); } } // }//end synch } } // }//end synch return activation; } /** * @return the amount of activation that is spread backwards from other modules in the direction of this module * * Note: this approach is slightly different from the one proposed at the article by [Maes 1989] since here we try to avoid meddling with another codelet's states. */ public double spreadBw() { // In this case x= other modules, y= this module double activation = 0; // synchronized(this.successors){ if (!this.getSuccessors().isEmpty()) { Enumeration e = this.getSuccessors().keys(); // iterate through Hashtable keys Enumeration while (e.hasMoreElements()) { Behavior module = (Behavior) e.nextElement(); if (impendingAccess(module)) { try { double amount = 0; if (!module.isExecutable()) {// A competence module x that is not executable spreads activation backward. ArrayList<Memory> intersection = new ArrayList<Memory>(); ArrayList<Memory> preconPlusSoftPrecon=new ArrayList<Memory>(); preconPlusSoftPrecon.addAll(module.getListOfPreconditions()); intersection.addAll(getIntersectionSet(preconPlusSoftPrecon, this.getAddList())); intersection.removeAll(worldState); for (Memory item : intersection) { amount = amount + ((1.0 / this.competencesWithPropInAdd(item)) * (1.0 / (double) this.getAddList().size())); } amount = amount * module.getActivation() * (globalVariables.getPhi() / globalVariables.getGamma()); if (showActivationSpread) { System.out.println(this.getName() + " receives " + amount + " backwarded energy from " + module.getName() + " [which has A= " + module.getActivation() + " ]"); } } // -------------------------- activation = activation + amount; } finally { lock.unlock(); module.lock.unlock(); } } } } return activation; } /** * @return the amount of activation that is spread forward from other modules in the direction of this module * * Note: this approach is slightly different from the one proposed at the article by [Maes 1989] since here we try to avoid meddling with another codelet's states. */ public double spreadFw() { // In this case x= other modules, y= this module double activation = 0; // synchronized(this.predecessors){ if (!this.getPredecessors().isEmpty()) { Enumeration e = this.getPredecessors().keys(); // iterate through Hashtable keys Enumeration while (e.hasMoreElements()) { Behavior module = (Behavior) e.nextElement(); if (impendingAccess(module)) { try { double amount = 0; if (module.isExecutable()) {// An executable competence module x spreads activation forward. ArrayList<Memory> intersection = new ArrayList<Memory>(); ArrayList<Memory> preconPlusSoftPrecon=new ArrayList<Memory>(); preconPlusSoftPrecon.addAll(this.getListOfPreconditions()); preconPlusSoftPrecon.addAll(this.getSoftPreconList()); intersection.addAll(getIntersectionSet(module.getDeleteList(), preconPlusSoftPrecon)); intersection.removeAll(worldState); for (Memory item : intersection) { amount = amount + ((1.0 / this.competencesWithPropInPrecon(item)) * (1.0 / (double) preconPlusSoftPrecon.size())); } amount = amount * module.getActivation() * (globalVariables.getPhi() / globalVariables.getGamma()); if (showActivationSpread) { System.out.println(this.getName() + " receives " + amount + " forwarded energy from " + module.getName() + " [which has A= " + module.getActivation() + " ]"); } } // ------------------------------------------------ activation = activation + amount; } finally { lock.unlock(); module.lock.unlock(); } } } } // }//end synch return activation; } /** * @return the amount of activation that is taken away from this module by other modules through conflict links * * Note: this approach is slightly different from the one proposed at the article by [Maes 1989] since here we try to avoid meddling with another codelet's states. Note: I am not using the "max" strategy described by maes */ public double takenAway() { // In this case x= other modules, y= this module double activation = 0; // synchronized(this.conflicters){ if (!this.getConflicters().isEmpty()) { Enumeration e = this.getConflicters().keys(); // iterate through Hashtable keys Enumeration while (e.hasMoreElements()) { Behavior module = (Behavior) e.nextElement(); if (impendingAccess(module)) { try { // --------------------------------- double amount = 0; ArrayList<Memory> intersection = new ArrayList<Memory>(); ArrayList<Memory> preconPlusSoftPrecon=new ArrayList<Memory>(); preconPlusSoftPrecon.addAll(this.getListOfPreconditions()); preconPlusSoftPrecon.addAll(this.getSoftPreconList()); intersection=getIntersectionSet(preconPlusSoftPrecon, module.getDeleteList()); intersection=getIntersectionSet(intersection, worldState); if (!((module.getActivation() < this.getActivation()) && (!intersection.isEmpty()))) { // this is the else case due to ! preconPlusSoftPrecon=new ArrayList<Memory>(); preconPlusSoftPrecon.addAll(module.getListOfPreconditions()); preconPlusSoftPrecon.addAll(module.getSoftPreconList()); intersection = getIntersectionSet(this.getDeleteList(), preconPlusSoftPrecon); intersection = getIntersectionSet(intersection, worldState); for (Memory item : intersection) { amount = amount + ((1.0 / this.competencesWithPropInDel(item)) * (1.0 / (double) this.getDeleteList().size())); } // amount = (b1.activation[0] * // (self.conf_energy / self.goal_energy) * // amount) amount = module.getActivation() * (globalVariables.getDelta() / globalVariables.getGamma()) * amount; ArrayList<Memory> modulos = this.getConflicters().get(module); double numberOfConflicters = 0; if (modulos != null) { numberOfConflicters = (double) modulos.size(); }// TODO Eu nao deveria precisar fazer este teste! double moduleActivation = module.getActivation(); double activationFromModule = (globalVariables.getDelta() / globalVariables.getGamma()) * numberOfConflicters * moduleActivation; if (showActivationSpread) { System.out.println(this.getName() + " has " + amount + " of its energy decreased by " + module.getName() + " [which has A= " + module.getActivation() + " ]"); } } // ------------------------------------ activation = activation + amount; } finally { lock.unlock(); module.lock.unlock(); } } } } return activation; } /** * * @param A * double value to be compared * @param B * @return the highest value */ private double max(double A, double B) { if (A > B) { return A; } else { return B; } } /** * Returns a list of PROPOSITION MOs constituting the intersection between A and B. * For this method to work, at least one of the lists must be of propositions * * @param A * list A * @param B * list B * @return the list with the intersection between A and B lists * */ public ArrayList<Memory> getIntersectionSet(ArrayList<Memory> A, ArrayList<Memory> B) {//TODO Should this comparison be performed as pattern matching? ArrayList<Memory> currentList = new ArrayList<Memory>(); ArrayList<Memory> intersection = new ArrayList<Memory>(); if((A.isEmpty()||B.isEmpty())||(A==null||B==null)){ return intersection; } // System.out.println(B); // System.out.println(B.get(0)); //Gives preference to returning PROPOSITIONs if(A.get(0).getName().equalsIgnoreCase("PROPOSITION")){ currentList.addAll(B); intersection.addAll(A); }else if((B.get(0).getName().equalsIgnoreCase("PROPOSITION"))){ currentList.addAll(A); intersection.addAll(B); }else{ // return null; //Should throw an exception? currentList.addAll(A); intersection.addAll(B); } for (int i = intersection.size() - 1; i > -1; --i) { Memory mo = intersection.get(i); if (!removeByInfo(currentList,mo.getI())) removeByInfo(intersection,mo.getI()); } return intersection; } public boolean removeByInfo(ArrayList<Memory> moList, Object target){ boolean removed=false; Memory mustRemove=null; for(Memory mo:moList){ if(mo.getI().equals(target)){ mustRemove=mo; break; } } if(mustRemove!=null){ moList.remove(mustRemove); removed=true; } return removed; } /** * @return the worldState */ public ArrayList<Memory> getWorldState() { return worldState; } /** * @param worldState * the worldState to set */ public void setWorldState(ArrayList<Memory> worldState) { this.worldState = worldState; } /** * @return the protectedGoals */ public ArrayList<Memory> getProtectedGoals() { return protectedGoals; } /** * @param protectedGoals * the protectedGoals to set */ public void setProtectedGoals(ArrayList<Memory> protectedGoals) { this.protectedGoals = protectedGoals; } /** * @return the permanentGoals */ public ArrayList<Memory> getPermanentGoals() { return permanentGoals; } /** * @param permanentGoals * the permanentGoals to set */ public void setPermanentGoals(ArrayList<Memory> permanentGoals) { this.permanentGoals = permanentGoals; } /** * @return the onceOnlyGoals */ public ArrayList<Memory> getOnceOnlyGoals() { return onceOnlyGoals; } /** * @param onceOnlyGoals * the onceOnlyGoals to set */ public void setOnceOnlyGoals(ArrayList<Memory> onceOnlyGoals) { this.onceOnlyGoals = onceOnlyGoals; } /** * @return the goals */ public ArrayList<Memory> getGoals() { return goals; } /** * @param goals * the goals to set */ public void setGoals(ArrayList<Memory> goals) { this.goals = goals; } /** * @return the globalVariables */ public GlobalVariables getGlobalVariables() { return globalVariables; } /** * @param globalVariables * the globalVariables to set */ public void setGlobalVariables(GlobalVariables globalVariables) { this.globalVariables = globalVariables; } /** * @return the firstTime */ public boolean isFirstTime() { return firstTime; } /** * @param firstTime * the firstTime to set */ public void setFirstTime(boolean firstTime) { this.firstTime = firstTime; } /** * @param actionsSet * the actionsSet to set * */ public void setActionList(ArrayList<String> actionsSet) { this.actionList = actionsSet; } /** * @param action * the action to be added to actionSet */ public void addAction(String action) { this.actionList.add(action); String pNumber; String[] actionDecomposition=action.split(" "); JSONObject jsonAction=new JSONObject(); try { if(!this.resourceList.contains(actionDecomposition[0])){ this.resourceList.add(actionDecomposition[0]); //Stores this resource in this behavior's resource list } jsonAction.put("RESOURCE", actionDecomposition[0]); jsonAction.put("ACTION", actionDecomposition[1]); for(int i=2;i<actionDecomposition.length;i++){ pNumber="P"+String.valueOf(i-1); jsonAction.put(pNumber, actionDecomposition[i]); } } catch (JSONException e) {e.printStackTrace();} this.jsonActionList.put(jsonAction); // System.out.println("---JSON ACTION: "+jsonAction); } /** * Clears this behavior's action list */ public void clearActionList(){ this.jsonActionList=new JSONArray(); this.actionList.clear(); } /** * Returns the number of competences in coalition with the given proposition in their precondition lists */ private double competencesWithPropInPrecon(Memory proposition) { double compWithProp = 0; for (Behavior comp : this.getCoalition()) { if (impendingAccess(comp)) { try { if (comp.getListOfPreconditions().contains(proposition)||comp.getSoftPreconList().contains(proposition)) { compWithProp = compWithProp + 1; } } finally { lock.unlock(); comp.lock.unlock(); } } } return compWithProp; } /** * Returns the list of competences from coalition with the given proposition in their add lists */ private double competencesWithPropInAdd(Memory proposition) { double compWithProp = 0; for (Behavior comp : this.getCoalition()) { if (impendingAccess(comp)) { try { if (comp.getAddList().contains(proposition)) { compWithProp = compWithProp + 1; } } finally { lock.unlock(); comp.lock.unlock(); } } } return compWithProp; } /** * Returns the list of competences from coalition with the given proposition in its del lists */ private double competencesWithPropInDel(Memory proposition) { double compWithProp = 0; for (Behavior comp : this.getCoalition()) { if (impendingAccess(comp)) { try { if (comp.getDeleteList().contains(proposition)) { compWithProp = compWithProp + 1; } } finally { lock.unlock(); comp.lock.unlock(); } } } return compWithProp; } /** * Sets the list of actions constituting this behavior * * @param actions * list of actions */ private void addAllActions(ArrayList<String> actions) { this.actionList = actions; } /** * Returns the list of actions constituting this behavior * * @return list of actions */ private List<String> getAllActions() { return this.actionList; } public void setBehaviors(ArrayList<Behavior> competences) { this.allBehaviors=competences; } /** * @return the setToZeroWhenActivated */ public boolean isSetToZeroWhenActivated() { return setToZeroWhenActivated; } /** * @param setToZeroWhenActivated the setToZeroWhenActivated to set */ public void setSetToZeroWhenActivated(boolean setToZeroWhenActivated) { this.setToZeroWhenActivated = setToZeroWhenActivated; } /** * Returns the moving average of the last n activations. * n must be previously defined, otherwise it will return the current activation (n=1) * @return the moving average of the last n activations */ public synchronized double getActivationMA(){ return activationMA; } /** * @return the softPreconList */ public ArrayList<Memory> getSoftPreconList() { return softPreconList; } /** * @param softPreconList the softPreconList to set */ public void setSoftPreconList(ArrayList<Memory> softPreconList) { this.softPreconList = softPreconList; } }
43,088
26.532907
311
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/bn/BehaviorNetwork.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.bn; import java.util.ArrayList; import java.util.Iterator; import br.unicamp.cst.core.entities.CodeRack; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.memory.WorkingStorage; /** * Implementation of a Behavior network as described in [Maes 1989] "How to do the Right Thing" * The behavior network controls an artificial agent, and is essentially a list of competence modules. * * @author klaus */ public class BehaviorNetwork { private ArrayList<Behavior> behaviors=new ArrayList<Behavior>(); //List of Competence codelets //TODO this list of all available competences should be given to the consciousness module so it can return a coalition list of relevant codelets private ArrayList<Behavior> coalition = new ArrayList<Behavior>(); //List of conscious Competence codelets //TODO the list of conscious codelets is a subset of all competences, and is formed by the coalition manager. This is the list passed to all consciouss codelets private boolean singleCodeletBN=false; //if set true, this behavior network starts a single thread to take care of executing all behaviors, instead of one thread for each one. private BehaviorsWTA kwta=null; private Codelet monitor=null; private CodeRack codeRack; private WorkingStorage ws; private GlobalVariables globalVariables; public BehaviorNetwork(CodeRack codeRack,WorkingStorage ws) { this.ws=ws; globalVariables = new GlobalVariables(); if(codeRack!=null) { this.codeRack = codeRack; kwta = (BehaviorsWTA) codeRack.insertCodelet(new BehaviorsWTA(globalVariables)); } } /** * Starts all competences threads */ public void startCodelets() { if(codeRack!=null) { if(!singleCodeletBN) { for(Codelet oneCompetence:this.behaviors) { oneCompetence.start(); } }else{ SingleThreadBHCodelet singleCodelet = new SingleThreadBHCodelet(this.behaviors); singleCodelet.setTimeStep(singleCodelet.getTimeStep()*this.behaviors.size()); // so the won't get more processing time than other codelets singleCodelet.start(); } }else { for(Codelet oneCompetence:this.behaviors) { oneCompetence.start();//TODO This should have no effect, should I remove it? } } } /** * Stops all competences threads */ public void stopCompetences() { for(Codelet oneCompetence:this.behaviors){ oneCompetence.stop(); } } /** * @param arrayList the consciousCompetences to set */ public void setCoalition(ArrayList<Behavior> arrayList) { this.coalition = arrayList; //TODO implement lock here? // Forwards the information of current coalition to all codelets Iterator itr = this.coalition.iterator(); while(itr.hasNext()) { Behavior competence = (Behavior) itr.next(); //TODO este cast pode ser desnecessário synchronized(competence){ competence.setCoalition(this.coalition); } } } /** * Passes to each behavior codelet the link to all the others */ public void setBehaviorsInsideCodelets() { //TODO implement lock here // Forwards the information of current coalition to all codelets Iterator itr = this.behaviors.iterator(); while(itr.hasNext()) { Behavior competence = (Behavior) itr.next(); //TODO este cast pode ser desnecessario synchronized(competence){ competence.setBehaviors(this.behaviors); } } } /** * @return the consciousCompetences */ public ArrayList<Behavior> getCoalition() { return coalition; } /** * @return the competences */ public ArrayList<Behavior> getBehaviors() { return behaviors; } /** * @param codelet the competences to set */ public void addCodelet(Codelet codelet) { //Every new godelet's input list gets registered at working storage for WORLD_STATE memory objects if(ws!=null) ws.registerCodelet(codelet, "WORLD_STATE",0); //TODO How about putting this inside Behavior.java? Behavior be = (Behavior)codelet; this.behaviors.add(be); kwta.addBehavior(be); setBehaviorsInsideCodelets(); } /** * @param codelet the competences to set */ public void removeCodelet(Codelet codelet) { if(ws!=null) ws.unregisterCodelet(codelet, "WORLD_STATE",0); //TODO How about putting this inside Behavior.java? Behavior be = (Behavior)codelet; this.behaviors.remove(be); kwta.removeBehavior(be); setBehaviorsInsideCodelets(); } /** * @return the singleCodeletBN */ public boolean isSingleCodeletBN() { return singleCodeletBN; } /** * @param singleCodeletBN the singleCodeletBN to set */ public void setSingleCodeletBN(boolean singleCodeletBN) { this.singleCodeletBN = singleCodeletBN; } /** * Defines whether or not if the behaviors in this BN must have their activations reset to zero after being activated. * @param val */ public void setBehaviorsToZeroWhenActivated(boolean val){ for(Behavior be: this.behaviors){ be.setSetToZeroWhenActivated(val); } } // The following code was commented due to use a graphics tool to show the state of the BehaviorNetwork. // This should be moved out from this class and be used within the cst-utils project // /** // * Creates a new graphic, showing all behaviors and its activations along time. And destroys any previous running graphics of this instance. // */ // public void showGraphics() // { // if(codeRack!=null) // { // if(monitor!=null) // { // codeRack.destroyCodelet(monitor); // } // monitor = codeRack.insertCodelet(new BHMonitor(this)); // monitor.start(); // } // } // // public void showGraphics(ArrayList<String> behaviorsIWantShownInGraphics) // { // if(codeRack!=null) // { // if(monitor!=null) // { // codeRack.destroyCodelet(monitor); // } // monitor = codeRack.insertCodelet(new BHMonitor(this,behaviorsIWantShownInGraphics,globalVariables)); // monitor.start(); // } // } // /** // * Plots a graph with all behaviors. // * Simple arrows denote activation connections // * whilst circled arrows illustrate inhibitive connections. // */ // public void plotBN() { // BNplot bnPlot = new BNplot(this.getBehaviors()); // // bnPlot.plot(); // // } // // /** // * Plots a graph with only the given behaviors. // * Simple arrows denote activation connections // * whilst circled arrows illustrate inhibitive connections. // */ // public void plotBN(ArrayList<String> behaviorsIWantShownInGraphics) { // ArrayList<Behavior> beIWannaShow=new ArrayList<Behavior>(); // for(Behavior be:this.getBehaviors()){ // if(behaviorsIWantShownInGraphics.contains(be.getName())){ // beIWannaShow.add(be); // } // } // // // BNplot bnPlot = new BNplot(beIWannaShow); // // bnPlot.plot(); // // } }
7,336
25.11032
176
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/bn/BehaviorsWTA.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.bn; import java.util.ArrayList; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import br.unicamp.cst.core.entities.Codelet; /** * This codelet implements a "winners take all" mechanism for the behavior network. * It takes a number of behaviors and make the one with the highest activation level ACTIVE. * @author Klaus * */ public class BehaviorsWTA extends Codelet { private ArrayList<Behavior> behaviorList = new ArrayList<Behavior>(); private ConcurrentHashMap<Codelet,Double> codeletsActivation = new ConcurrentHashMap<Codelet, Double>(); private ConcurrentHashMap<Codelet,Boolean> codeletsActive = new ConcurrentHashMap<Codelet, Boolean>(); private ArrayList<Behavior> behaviorsStillActive=new ArrayList<Behavior>(); private Behavior chosenBehavior=null; private GlobalVariables globalVariables; /** * Iterate over all behaviors. * If none of them are ACTIVE, choose the one with highest activation and which is executable * Make that one ACTIVE. * * Once it becomes active, its activation will drop to zero, but might remain active until it performs its job. * * I should only try to choose another one once they are all INACTIVE. * */ public BehaviorsWTA(GlobalVariables globalVariables) { this.globalVariables=globalVariables; } @Override public void accessMemoryObjects() { } @Override public void proc() { synchronized(this){ //Just in case: codeletsActivation.clear(); codeletsActive.clear(); ArrayList<String> tempListOfExecutableCodelets = new ArrayList<String>(); if(chosenBehavior==null){//If there are no active behavior codelet //GET A LIST OF CODELETS THAT ARE CANDIDATES FOR ACTIVATION boolean there_is_already_one_active=false; for (Behavior competence : behaviorList) { if (impendingAccess(competence)){ try { // //Using the loop to also perform activation decay // competence.setValue(competence.getValue()*globalVariables.getPi()); if(competence.isActive()){ there_is_already_one_active=true; }else{ if(behaviorsStillActive.contains(competence)){ behaviorsStillActive.remove(competence); } } if(competence.isExecutable()&&competence.getActivation()>=globalVariables.getThetaTemp()){ codeletsActivation.put(competence, competence.getActivation()); tempListOfExecutableCodelets.add(competence.getName());//Assumes each behavior has a particular name } } finally { lock.unlock(); competence.lock.unlock(); } } } //FINDS OUT WHICH ONE IS THE CODELET WITH THE HIGHEST ACTIVATION LEVEL if(there_is_already_one_active){ System.out.println("Error at KWTANetwork.java: More than one behavior active at the same time."); } double highestAct=Double.MIN_VALUE; for (Entry<Codelet, Double> o : codeletsActivation.entrySet()) { Behavior competence =(Behavior) o.getKey(); if (impendingAccess(competence)){ try { double activation=(Double) o.getValue(); if(activation>=highestAct){ chosenBehavior=competence; highestAct=activation; } } finally { lock.unlock(); competence.lock.unlock(); } } } //ACTIVATES EXECUTABLE CODELET WITH HIGHEST ACTIVATION LEVEL // System.out.println("I believe this guy should become active (A="+chosen_codelet.getValue()+"): "+chosen_codelet.getId()); if(chosenBehavior!=null){//otherwise, it means it could not find a suitable behavior for activation if (impendingAccess(chosenBehavior)){ try { chosenBehavior.setActive(true); } finally { lock.unlock(); chosenBehavior.lock.unlock(); } } // All thetatemps must be reset back to their original values globalVariables.setThetaTemp(globalVariables.getTheta()); }else{ // no active behavior yet globalVariables.decreaseThetaTemps(); // only in case no behavior is used } }else{//If there is already an active behavior codelet //Check if its world belief state has changed boolean mustSetNull=false; if (impendingAccess(chosenBehavior)){ try { if(chosenBehavior.changedWorldBeliefState()){ chosenBehavior.setActive(false); mustSetNull=true; } } finally { lock.unlock(); chosenBehavior.lock.unlock(); } } if(mustSetNull){ chosenBehavior=null; } } }//end synchronized }//end proc public void addBehavior(Behavior be){ this.behaviorList.add(be); } public void removeBehavior(Behavior be){ this.behaviorList.remove(be); } @Override public void calculateActivation() { // TODO Auto-generated method stub } } ////// CODE SANDBOX //synchronized(this){ // //Just in case: // codeletsActivation.clear(); // codeletsActive.clear(); // int count=0; // ArrayList<String> tempListOfExecutableCodelets = new ArrayList<String>(); // // // //GET A LIST OF CODELETS THAT ARE CANDIDATES FOR ACTIVATION // boolean there_is_already_one_active=false; // for (Behavior competence : behaviorList) // { // if (impendingAccess(competence)){ // try // { // if(competence.isActive()){ // there_is_already_one_active=true; // count++; // }else{ // if(behaviorsStillActive.contains(competence)){ // behaviorsStillActive.remove(competence); // } // } // // // //Core functionality // if(competence.isExecutable()&&competence.getValue()>=globalVariables.getThetaTemp()){ // codeletsActivation.put(competence, competence.getValue()); // // tempListOfExecutableCodelets.add(competence.getId());//Assumes each behavior has a particular name // } // ////TODO Where should I put this? //// private void checkIfShouldBecomeInactive() //// { //// if(this.isExecutable()){ //// if(this.isActive()){//reason if it should remain active //// //In principle, if it was chosen as the best behavioral answer to a given state, it shouldn't stop working until there was a change in state (unless we consider a stochastic effect). //// if(this.changedWorldBeliefState()){ //// //// this.setActive(false); //// }//else, remain active, (but keep its activation level down?) //// else{ //// if(setToZeroWhenActivated){ //// this.setValue(0);//TODO is this in accordance with [Maes 1989] ? //// } //// } //// } //// //// }else{//If not executable, it can't be active //// this.setActive(false); //// } //// //// //// } // //// changedWorldBeliefState() // // // } finally // { // lock.unlock(); // competence.lock.unlock(); // } // } // } // // // // // //FINDS OUT WHICH ONE IS THE CODELET WITH THE HIGHEST ACTIVATION LEVEL // if(count>1){ // System.out.println("Error at KWTANetwork.java: More than one behavior active at the same time."); // } // Behavior chosen_codelet=null; // // if(!there_is_already_one_active){//choose the executable one with highest activation // if(count==0){ // double highestAct=Double.MIN_VALUE; // for (Entry<Codelet, Double> o : codeletsActivation.entrySet()) { // Behavior competence =(Behavior) o.getKey(); // if (impendingAccess(competence)){ // try // { // double activation=(Double) o.getValue(); // if(activation>=highestAct){ // chosen_codelet=competence; // highestAct=activation; // } // } finally // { // lock.unlock(); // competence.lock.unlock(); // } // } // // } // // // //ACTIVATES EXECUTABLE CODELET WITH HIGHEST ACTIVATION LEVEL // if(chosen_codelet!=null){ // // System.out.println("I believe this guy should become active (A="+chosen_codelet.getValue()+"): "+chosen_codelet.getId()); // if (impendingAccess(chosen_codelet)){ // try // { // double previousActivation = chosen_codelet.getValue(); // double previousThetaTemp = globalVariables.getThetaTemp(); // boolean wasExecutable = chosen_codelet.isExecutable(); // boolean wasActive = chosen_codelet.isActive(); // // // // chosen_codelet.setActive(true); // chosen_codelet.setValue(0);// [Maes 1989] // // double nextActivation = chosen_codelet.getValue(); // boolean isActive = chosen_codelet.isActive(); // System.out.println(""); // // } finally // { // lock.unlock(); // chosen_codelet.lock.unlock(); // } // } // behaviorsStillActive.add(chosen_codelet); // // // All thetatemps must be reset back to their original values // globalVariables.setThetaTemp(globalVariables.getTheta()); // // } // } // // decreaseThetas(globalVariables.getThetaTempDecreaseRate()*Math.tanh((this.getTimeStep()/100))); // //// System.out.println("behaviorsStillActive: "); //// for(Behavior be: behaviorsStillActive){ //// System.out.println(be.getId()); //// } //// System.out.println("---"); // // // // //// System.out.println("WorldBeliefState: "); //// ArrayList<MemoryObject> wbs = new ArrayList<MemoryObject>(); //// wbs.addAll(ws.getAllOfType(MemoryObjectTypesCore.WORLD_STATE)); //// //// for(MemoryObject mo: wbs){ //// System.out.println(mo.getInfo()); //// } //// System.out.println("---"); // // // //// //TODO Testing decay //// //// for (Behavior competence : behaviorList) //// { //// if (impendingAccess(competence)){ //// try //// { //// double decay=0.01; //// double act=competence.getValue(); //// //// if(act>decay){ //// act=act-decay; //// competence.setValue(act); //// } //// } finally //// { //// lock.unlock(); //// competence.lock.unlock(); //// } //// } //// } //// //// //}
10,410
26.68883
193
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/bn/BgBComLayer.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.bn; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import org.json.JSONObject; import br.unicamp.cst.core.entities.MemoryObject; import br.unicamp.cst.core.entities.RawMemory; /** * This class is used as synchronized communication layer between raw action selection mechanism and all unconscious behaviors. * The motivation for its creation was making the process of avoiding deadlocks easier. * @author klaus * */ public class BgBComLayer { private ArrayList<MemoryObject> bgToBehaviors = new ArrayList<MemoryObject>(); private ArrayList<MemoryObject> behaviorsToBg = new ArrayList<MemoryObject>(); private boolean debugMode=false; private RawMemory rawMemory; public BgBComLayer(RawMemory rawMemory) { this.rawMemory = rawMemory; } /** * * Avoids cloning */ public Object clone() throws CloneNotSupportedException{ throw new CloneNotSupportedException(); } /** * This method adds a new behavior state to behaviorsToBg list in case the isn't already a similar one. * If it finds a memory object with the same type and information, it doesn't write it. * If it finds a similar MO (same type and same name) but with different information, it simply updates the information * NOTE: If the passed bs is not used, it should be removed from raw memory to save memory (would this be a problem?) * @param bs memory object to be added to behaviorsToBg */ public synchronized void writeBehaviorState(MemoryObject bs){ try { JSONObject bsInfo = new JSONObject(bs.getI()); MemoryObject oldMO=new MemoryObject(); boolean alreadyThere=false; boolean sameInfo=false; for(MemoryObject mo:this.behaviorsToBg){ try { JSONObject moInfo = new JSONObject(mo.getI()); if(moInfo.get("NAME").equals(bsInfo.get("NAME"))){ alreadyThere=true; oldMO=mo; if(mo.getI().equals(bs.getI())){ sameInfo=true; } break; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(alreadyThere && sameInfo) {// Remove MO from raw memory and discard it if(rawMemory!=null) rawMemory.destroyMemoryObject(bs); }else if(alreadyThere && !sameInfo){ //Update info from old MO and discard de unused new one oldMO.setI(bs.getI()); //TODO I might need to change this in the future in case we implement a memory decay based on time if(rawMemory!=null) rawMemory.destroyMemoryObject(bs); }else {//Simply add it to the list this.behaviorsToBg.add(bs); } } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if(debugMode==true){ showBgBContent(); } } /** * This method adds a new behavior state to bgToBehaviors list in case the isn't already a similar one. * If it finds a memory object with the same type and information, it doesn't write it. * If it finds a similar MO (same type and same name) but with different information, it simply updates the information * @param bgI memory object to be added to bgToBehaviors */ public synchronized void writeBGInstruction(MemoryObject bgI){ // try { // JSONObject bsInfo = new JSONObject(bgI.getInfo()); MemoryObject oldMO=new MemoryObject(); boolean alreadyThere=false; boolean sameInfo=false; for(MemoryObject mo:this.bgToBehaviors){ // try { // JSONObject moInfo = new JSONObject(mo.getInfo()); // if((mo.getName().equalsIgnoreCase(bgI.getName()))&&(mo.getI().equals(bgI.getI()))){ alreadyThere=true; oldMO=mo; if(mo.getI().equals(bgI.getI())){ sameInfo=true; } break; } // } catch (JSONException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } if(alreadyThere && sameInfo) {// Remove MO from raw memory and discard it if(rawMemory!=null) rawMemory.destroyMemoryObject(bgI); }else if(alreadyThere && !sameInfo) {//Update info from old MO and discard de unused new one oldMO.setI(bgI.getI()); //TODO I might need to change this in the future in case we implement a memory decay based on time if(rawMemory!=null) rawMemory.destroyMemoryObject(bgI); }else {//Simply add it to the list this.bgToBehaviors.add(bgI); } // } catch (JSONException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } if(debugMode==true){ showBgBContent(); } } /** * * @return the list of behavior states stored in this object */ public synchronized List<MemoryObject> readBehaviorStates(){ List<MemoryObject> behaviorStateList=new ArrayList<MemoryObject>(); for(MemoryObject mo:this.behaviorsToBg){ if(mo.getName().equalsIgnoreCase("BEHAVIOR_STATE")){ behaviorStateList.add(mo); } } return behaviorStateList; } /** * * @return the list of instructions from BG stored in this object */ public synchronized List<MemoryObject> readBGInstructions(){ List<MemoryObject> bGInstructionsList = new ArrayList<MemoryObject>(); // for(MemoryObject mo:this.bgToBehaviors){//TODO This might be unnecessary // if((mo.getType()==MemoryObjectTypesCore.BG_SHOULD_ACTIVATE)||(mo.getType()==MemoryObjectTypes.TEMP_THETA.ordinal())){ // bGInstructionsList.add(mo); // } // } return bGInstructionsList; } public synchronized void showBgBContent(){ System.out.println("------------------"); System.out.println("-> bgToBehaviors: "+bgToBehaviors); System.out.println("-> behaviorsToBg: "+behaviorsToBg); System.out.println("------------------"); } }
6,234
30.0199
127
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/bn/GlobalVariables.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.bn; /** * * @author klauslocal * */ public class GlobalVariables { //Global variables private volatile double theta; // Threshold for becoming active private volatile double thetaTemp; //Threshold for becoming active that starts as theta but gets reduced by a percentage in case no behavior is selected private volatile double pi; // mean level of activation private volatile double phi; //amount of activation energy a proposition that is observed to be true injects into the network private volatile double gamma;//amount of activation energy a goal injects into the network private volatile double delta; //amount of activation energy a protected goal takes away from the network private volatile double decay; //amount of energy that is naturally lost by the behavior at each iteration //Debug variables private volatile boolean worldStateInHashMap;//defines if we should use a single list for all objects in working storage (false) or a HashMap of lists (true) private double decreaseRate; //Fraction of decrease suffered by theta coming from each behavior codelet /** * Default Constructor */ public GlobalVariables() { //TODO how about automatically defining these variables with an optimization algorithm? //Initial states this.theta=1; this.thetaTemp=this.theta; this.pi=0.020; this.phi=0.05; this.gamma=0.2; this.delta=0.050; this.decay=1; //DebugVariables this.decreaseRate=0.01; this.worldStateInHashMap=true; } public synchronized boolean isWorldStateInHashMap() { return worldStateInHashMap; } public synchronized void setWorldStateInHashMap(boolean worldStateInHashMap) { this.worldStateInHashMap = worldStateInHashMap; } /** * * Avoids cloning */ public Object clone() throws CloneNotSupportedException{ throw new CloneNotSupportedException(); } /** * amount of activation energy a goal injects into the network * @return the gamma */ public synchronized double getGamma() { return gamma; } /** amount of activation energy a goal injects into the network * @param gamma the gamma to set */ public synchronized void setGamma(double gamma) { this.gamma = gamma; } /** * threshold for becoming active * * @return the theta */ public synchronized double getTheta() { return theta; } /** * threshold for becoming active * * @param theta the theta to set */ public synchronized void setTheta(double theta) { this.theta = theta; } /** * mean level of activation * @return the pi */ public synchronized double getPi() { return pi; } /** * mean level of activation * @param pi the pi to set */ public synchronized void setPi(double pi) { this.pi = pi; } /** * amount of activation energy a proposition that is observed to be true injects into the network * @return the phi */ public synchronized double getPhi() { return phi; } /** * amount of activation energy a proposition that is observed to be true injects into the network * @param phi the phi to set */ public synchronized void setPhi(double phi) { this.phi = phi; } /** * amount of activation energy a protected goal takes away from the network * @return the delta */ public synchronized double getDelta() { return delta; } /** * amount of activation energy a protected goal takes away from the network * @param delta the delta to set */ public synchronized void setDelta(double delta) { this.delta = delta; } /** * threshold for becoming active that starts as theta but gets reduced by a percentage in case no behavior is selected * @return the thetaTemp */ public synchronized double getThetaTemp() { return thetaTemp; } /** * threshold for becoming active that starts as theta but gets reduced by a percentage in case no behavior is selected * @param thetaTemp the thetaTemp to set */ public synchronized void setThetaTemp(double thetaTemp) { this.thetaTemp = thetaTemp; } /** * amount of energy that is naturally lost by the behavior at each iteration * * @return the decay */ public double getDecay() { return this.decay; } /** * amount of energy that is naturally lost by the behavior at each iteration * @param decay */ public void setDecay(double decay) { this.decay = decay; } /** * Fraction of decrease suffered by theta coming from each behavior codelet * @return the decrease rate */ public synchronized double getThetaTempDecreaseRate() { return this.decreaseRate; } /** * Fraction of decrease suffered by theta (temp theta) * @param decreaseRate the decreaseRate to set */ public synchronized void setThetaTempDecreaseRate(double decreaseRate) { this.decreaseRate = decreaseRate; } /** * Decreases the values of used thetas by multiplying them by a certain fraction in case no behaviour is used */ public synchronized void decreaseThetaTemps() { this.setThetaTemp(this.getThetaTemp()*this.getThetaTempDecreaseRate()); } }
5,567
27.121212
158
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/bn/SingleThreadBHCodelet.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.bn; import java.util.ArrayList; import br.unicamp.cst.core.entities.Codelet; /** * * Codelet that activates behaviors in a single-threaded behavior network * @author Klaus * */ public class SingleThreadBHCodelet extends Codelet{ private ArrayList<Behavior> behaviors; public SingleThreadBHCodelet(ArrayList<Behavior> behaviors){ this.behaviors=behaviors; } @Override public void proc() { for(Behavior be:behaviors){ be.proc(); } } @Override public void accessMemoryObjects() { // TODO Auto-generated method stub } @Override public void calculateActivation() { // TODO Auto-generated method stub } }
1,231
22.692308
82
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/glas/ActionSelectionCodelet.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.glas; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Random; import org.json.JSONArray; import org.json.JSONException; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.entities.RawMemory; import br.unicamp.cst.memory.WorkingStorage; /** * * Selects action based on solution tree retrieved from working storage. * @author klaus * */ public class ActionSelectionCodelet extends Codelet{ Memory SOLUTION_TREE_MO; //input (should be found in working storage) Memory ACTION_MO; //output Memory STIMULUS_MO; //input int[] empty_solution_tree={0, 1, 0, 1, 0, 1}; private GlasActionSelection sm; private Timestamp last_stimulus_time_stamp; private boolean first_run=true; private JSONArray current_solution_tree_jsonarray=new JSONArray(); private Memory NEW_STIM_MO; // private Memory NEW_EVENT_DETECTED_MO; private Memory NEW_ACTION_MO; private Memory NEW_REWARD_MO; private boolean enabled=true; private double exp_factor=0; //Exploratory factor private double solution_tree_fitness = Double.NEGATIVE_INFINITY; private boolean dynamicExplorationOn=false; private RawMemory rawMemory; private WorkingStorage ws; public ActionSelectionCodelet(RawMemory rawMemory,WorkingStorage ws) { this.rawMemory = rawMemory; this.ws=ws; if(ws!=null) { ws.registerCodelet(this,"SOLUTION_TREE", 0); ws.registerCodelet(this,"STIMULUS", 0); ws.putMemoryObject(ACTION_MO); ws.registerCodelet(this,"NEW_STIM", 0); ws.registerCodelet(this,"NEW_ACTION", 0); ws.registerCodelet(this,"NEW_REWARD", 0); // ws.registerCodelet(this,MemoryObjectTypesGlas.ACTION, 1); // ws.registerCodelet(this,MemoryObjectTypesGlas.NEW_EVENT_DETECTED, 0); } if(rawMemory!=null) ACTION_MO = rawMemory.createMemoryObject("ACTION", ""); for(int i=0; i<empty_solution_tree.length;i++){ current_solution_tree_jsonarray.put(empty_solution_tree[i]); } sm = new GlasActionSelection(empty_solution_tree); sm.reset(); } @Override public void accessMemoryObjects() { SOLUTION_TREE_MO=this.getInput("SOLUTION_TREE", 0); ArrayList<Memory> teste = ws!=null ? ws.getAllOfType("SOLUTION_TREE") : null; STIMULUS_MO=this.getInput("STIMULUS", 0); // System.out.println("(STIMULUS_MO.getInfo() (antes): "+STIMULUS_MO.getInfo()); // ACTION_MO=this.getOutput(MemoryObjectTypesGlas.ACTION, 0); // NEW_EVENT_DETECTED_MO = this.getInput(MemoryObjectTypesGlas.NEW_EVENT_DETECTED,0); int index=0; NEW_STIM_MO = this.getInput("NEW_STIM", index); NEW_ACTION_MO = this.getInput("NEW_ACTION", index); NEW_REWARD_MO = this.getInput("NEW_REWARD", index); } @Override public void calculateActivation() { // TODO Auto-generated method stub } @Override public void proc() { if(enabled){ //Update Solution Tree if needed Object new_solution_tree_string = SOLUTION_TREE_MO.getI(); if(!new_solution_tree_string.equals(this.current_solution_tree_jsonarray.toString())){ // System.out.println("Action Selection Found a new Solution Tree: "+new_solution_tree_string); JSONArray new_solution_tree_jsonarray; try { new_solution_tree_jsonarray = new JSONArray(new_solution_tree_string); int[] new_solution_tree_phenotype = new int[new_solution_tree_jsonarray.length()]; for(int i=0; i<new_solution_tree_phenotype.length;i++){ new_solution_tree_phenotype[i]=new_solution_tree_jsonarray.getInt(i); } current_solution_tree_jsonarray=new_solution_tree_jsonarray; sm = new GlasActionSelection(new_solution_tree_phenotype); } catch (JSONException e) { e.printStackTrace(); } solution_tree_fitness = SOLUTION_TREE_MO.getEvaluation(); // exp_factor=1-(1/(1+Math.exp(-solution_tree_fitness))); //1/(1+EXP(AB3*10)) if(dynamicExplorationOn){ exp_factor=(1/(1+Math.exp(10*solution_tree_fitness))); } } //Selects action based on stimulus boolean new_stim=(NEW_STIM_MO.getI().equals(String.valueOf(true))); boolean new_action=(NEW_ACTION_MO.getI().equals(String.valueOf(true))); boolean new_reward=(NEW_REWARD_MO.getI().equals(String.valueOf(true))); if(!STIMULUS_MO.getI().equals("") && new_stim && !new_action && !new_reward){ int[] stimulus = {Integer.valueOf((String)STIMULUS_MO.getI())}; int[] selected_action = sm.runStimuli(stimulus); //TODO Ugly solution //TODO Add an exploratory element here? Random rnd_exp = new Random(); if(rnd_exp.nextFloat()<=exp_factor){ int[] actions = sm.getActions(); selected_action[0]=actions[rnd_exp.nextInt(actions.length)]; } ACTION_MO.setI(Integer.toString(selected_action[0])); //TODO is [0] correct? // System.out.println("ACTION_MO.updateInfo("+selected_action[0]+")"); new_action=true; // System.out.println("new_action=true;"); } NEW_ACTION_MO.setI(String.valueOf(new_action)); }//end if(enabled) }// end proc() /** * @return the enabled */ public boolean isEnabled() { return enabled; } /** * @param enabled the enabled to set */ public void setEnabled(boolean enabled) { this.enabled = enabled; } // public int[] getGenotypeFromPhenotype(int[] phenotype) { // // // int nN=Math.round(phenotype.length/3)+1; // int[] genotype = new int[nN*3]; // // genotype[0]=0;//First nodes always zero // genotype[nN]=0;//First nodes always zero // genotype[2*nN]=0;//First nodes always zero // // int index = 0; // for(int i=1;i<nN;i++){ // genotype[i] = phenotype[index]; // index++; // } // index = nN-1; // for(int i=nN+1;i<2*nN;i++){ // genotype[i] = phenotype[index]; // index++; // } // index = 2*nN-2; // for(int i=2*nN+1;i<3*nN;i++){ // genotype[i] = phenotype[index]; // index++; // } // // return genotype; // } /** * @return the exp_factor */ public double getExp_factor() { return exp_factor; } /** * Probability (0-1) of getting a random action * @param ef the exp_factor to set */ public void setExp_factor(double ef) { if(ef<0.0){ this.exp_factor = 0.0; }else if(ef>1){ this.exp_factor = 1.0; }else{ this.exp_factor = ef; } } /** * @return the dynamicExplorationOn */ public boolean isDynamicExplorationOn() { return dynamicExplorationOn; } /** * @param dynamicExplorationOn the dynamicExplorationOn to set */ public void setDynamicExplorationOn(boolean dynamicExplorationOn) { this.dynamicExplorationOn = dynamicExplorationOn; } }
7,135
26.766537
101
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/glas/Cognit.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.glas; import br.unicamp.cst.core.entities.CodeRack; import br.unicamp.cst.core.entities.RawMemory; import br.unicamp.cst.learning.glas.LearnerCodelet; import br.unicamp.cst.memory.WorkingStorage; /** * Cognit is the implementation of GLAS - Gated Learning Action Selection - algorithm inside LibreCog cognitive architecture. * It is composed by three integrated codelets: * - ActionSelectionCodelet: Selects the most appropriate action based on sequence of events and a known solution tree * - SequenceBuilderCodelet: Builds a sequence of events in memory based on stimuli, selected action and received reward * - LearnerCodelet: Learns an optimized solution tree given a sequence of events * * @author klaus * */ public class Cognit { private ActionSelectionCodelet action_selection_codelet; private SequenceBuilderCodelet sequence_builder_codelet; private LearnerCodelet learner_codelet; private RawMemory rawMemory; private CodeRack codeRack; public Cognit(int nStimuli, int nActions,CodeRack codeRack,RawMemory rawMemory, WorkingStorage ws) { this.codeRack = codeRack; this.rawMemory = rawMemory; //GLAS Codelets action_selection_codelet = new ActionSelectionCodelet(rawMemory,ws); if(codeRack!=null) codeRack.insertCodelet(action_selection_codelet); sequence_builder_codelet = new SequenceBuilderCodelet(rawMemory,ws); if(codeRack!=null) codeRack.insertCodelet(sequence_builder_codelet); learner_codelet = new LearnerCodelet(nStimuli, nActions,rawMemory,ws); if(codeRack!=null) codeRack.insertCodelet(learner_codelet); } /** * @return the action_selection_codelet */ public ActionSelectionCodelet getActionSelectionCodelet() { return action_selection_codelet; } /** * @return the sequence_builder_codelet */ public SequenceBuilderCodelet getSequenceBuilderCodelet() { return sequence_builder_codelet; } /** * @return the learner_codelet */ public LearnerCodelet getLearnerCodelet() { return learner_codelet; } }
2,592
31.4125
125
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/glas/GlasActionSelection.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.glas; import java.util.ArrayList; /** * This class evaluates how nodes change given a solution tree and a sequence of stimuli. * This function implements a state machine with 4 sates. Each states * defines at which kind of node we are currently at. * * @author Klaus * */ public class GlasActionSelection { private int[] solution_tree_phenotype;//Phenotype /** * Chromossome (Phenotype) of the new StateMachine * @param solution_tree_phenotype */ public GlasActionSelection(int[] solution_tree_phenotype) { this.solution_tree_phenotype=solution_tree_phenotype; nNodes=(int)(solution_tree_phenotype.length/3); nodes_types=new int[nNodes]; updateNodesTypes(); } private int[] nodes_types; private int nNodes; public static int ROOT_NODE=0; public static int SEQUENCE_START_NODE=1; public static int INTERMEDIATE_NODE=2; public static int SEQUENCE_END_NODE=3; private int current_node_type=0; int[] structure; int[] contents; int[] actions; private int[] actions_history; private int[] nodes_history; private int current_node_minus_1=0; public void updateNodesTypes(){ structure=new int[nNodes]; for (int i=0; i<nNodes;i++){ structure[i]=solution_tree_phenotype[i]; } contents=new int[nNodes]; for (int i=0; i<nNodes;i++){ contents[i]=solution_tree_phenotype[i+nNodes]; } actions=new int[nNodes]; for (int i=0; i<nNodes;i++){ actions[i]=solution_tree_phenotype[i+2*nNodes]; } //--- Identify current node int max_node=0; for (int i=0; i<nNodes;i++){ if(structure[i]>max_node){ max_node=structure[i]; } } for (int i=1; i<=nNodes;i++){ if(structure[i-1]==0){ nodes_types[i-1]=ROOT_NODE; }else if(structure[i-1]==1){ nodes_types[i-1]=SEQUENCE_START_NODE; }else if (this.getChildren(structure,i).isEmpty()){// (i>max_node) { //TODO this criterium is wrong nodes_types[i-1]=SEQUENCE_END_NODE; }else{ nodes_types[i-1]=INTERMEDIATE_NODE; } } } private ArrayList<Integer> getChildren(int[] structure2, int i) { // TODO Auto-generated method stub ArrayList<Integer> children = new ArrayList<Integer>(); for(int n = 0; n<structure2.length;n++){ if(structure2[n]==i){ children.add(n+1); } } return children; } /** * @return the chromossome */ public int[] getChromossome() { return solution_tree_phenotype; } /** * @param chromossome the chromossome to set */ public void setChromossome(int[] chromossome) { this.solution_tree_phenotype = chromossome; } /** * @return the nodes_types */ public int[] getNodes_types() { return nodes_types; } /** * @param nodes_types the nodes_types to set */ public void setNodes_types(int[] nodes_types) { this.nodes_types = nodes_types; } /** * @return the current_node_type */ public int getCurrent_node_type() { return current_node_type; } /** * @param current_node_type the current_node_type to set */ public void setCurrent_node_type(int current_node_type) { this.current_node_type = current_node_type; } /** * This method implements a state machine with 4 sates. * Each state defines at which kind of node we are currently at. * */ public int[] runStimuli(int[] stimuli) { actions_history= new int[stimuli.length]; nodes_history=new int[stimuli.length]; // current_node_minus_1=0; //Initial node minus one (for array refferencing) for (int st=0; st<stimuli.length;st++){ int stim = stimuli[st]; if(isStimKnown(stim)){ //State machine if(nodes_types[current_node_minus_1]==ROOT_NODE){ // From here it can only go to sequence starter nodes //Check if stim is a viable SN node boolean viableSN=false; for(int i=0; i<nNodes;i++){ if((nodes_types[i]==SEQUENCE_START_NODE)&&(stim==contents[i])){ current_node_minus_1=i; viableSN=true; break; } } int debug1=0; debug1=1; }else if((nodes_types[current_node_minus_1]==SEQUENCE_START_NODE)||(nodes_types[current_node_minus_1]==INTERMEDIATE_NODE)){ // Can go up to an INTERMEDIATE NODE, a SEQUENCE_END_NODE or back to another SEQUENCE_START_NODE //Check if stim is a viable SN node (priority) boolean viableSN=false; for(int i=0; i<nNodes;i++){ if((nodes_types[i]==SEQUENCE_START_NODE)&&(stim==contents[i])){//TODO something weird here current_node_minus_1=i; viableSN=true; break; } } int debug1=0; debug1=1; if(!viableSN){ // // Check if it is next in the sequence of children // for(int i=0; i<nNodes;i++){ // if(structure[i]==current_node_minus_1+1){//found child // if(stim==contents[i]){// found match, move there // current_node_minus_1=i; // break; // } // } // } current_node_minus_1=moveToChildNodeIfHasStim(current_node_minus_1,stim); } debug1=1; }else if(nodes_types[current_node_minus_1]==SEQUENCE_END_NODE){ // Can only go back to a SN // This is a special case. Even if the stimuli is not an SN, it should // climb the tree back to the SN which originated this sequence. //Check if stim is a viable SN node (priority) boolean viableSN=false; for(int i=0; i<nNodes;i++){ if((nodes_types[i]==SEQUENCE_START_NODE)&&(stim==contents[i])){ current_node_minus_1=i; viableSN=true; break; } } if(!viableSN){ // Go back to original SN current_node_minus_1=goBackToOriginalSN(current_node_minus_1,stim); } //TODO Now, before moving on, we need to see if any of its children has stim current_node_minus_1=moveToChildNodeIfHasStim(current_node_minus_1,stim); }else{//should not happen try { throw new Exception("This should not happen. There is something wrong here..."); } catch (Exception e) { e.printStackTrace(); } } //Register current node nodes_history[st]=current_node_minus_1+1; //Adding one for the record actions_history[st]=actions[current_node_minus_1]; }else{ actions_history[st]=actions[0]; //ignores } }//End events loop return actions_history; } private int moveToChildNodeIfHasStim(int current_node_minus_1, int stim) { // Check if it is next in the sequence of children for(int i=0; i<nNodes;i++){ if(structure[i]==current_node_minus_1+1){//found child if(stim==contents[i]){// found match, move there if different if(stim!=contents[current_node_minus_1]){//TODO do I really need this condition ? current_node_minus_1=i; break; } } } } return current_node_minus_1; } public int goBackToOriginalSN(int current_node_minus_1, int stim) { int previousContent=contents[current_node_minus_1]; boolean not_a_start_node_yet=(structure[current_node_minus_1]>1); boolean current_node_content_is_not_stim = (contents[current_node_minus_1]!=stim); boolean previous_content_is_stim = (previousContent==stim); // while( not_a_start_node_yet && (current_node_content_is_not_stim || previous_content_is_stim) ){ //TODO: should it also stop if its child contains stim? while(not_a_start_node_yet){ current_node_minus_1=structure[current_node_minus_1]-1; not_a_start_node_yet=(structure[current_node_minus_1]>1); current_node_content_is_not_stim = (contents[current_node_minus_1]!=stim); } return current_node_minus_1; } private boolean isStimKnown(int stim) { boolean stimKnown=false; for (int i=0; i<nNodes;i++){ if(stim==contents[i]){ stimKnown=true; break; } } return stimKnown; } public void reset() { current_node_type=ROOT_NODE; current_node_minus_1=0; } /** * @return the actions_history */ public int[] getActions_history() { return actions_history; } /** * @param actions_history the actions_history to set */ public void setActions_history(int[] actions_history) { this.actions_history = actions_history; } /** * @return the nodes_history */ public int[] getNodes_history() { return nodes_history; } /** * @param nodes_history the nodes_history to set */ public void setNodes_history(int[] nodes_history) { this.nodes_history = nodes_history; } /** * @return the nNodes */ public int getnNodes() { return nNodes; } /** * @param nNodes the nNodes to set */ public void setnNodes(int nNodes) { this.nNodes = nNodes; } /** * @return the structure */ public int[] getStructure() { return structure; } /** * @param structure the structure to set */ public void setStructure(int[] structure) { this.structure = structure; } /** * @return the contents */ public int[] getContents() { return contents; } /** * @param contents the contents to set */ public void setContents(int[] contents) { this.contents = contents; } /** * @return the actions */ public int[] getActions() { return actions; } /** * @param actions the actions to set */ public void setActions(int[] actions) { this.actions = actions; } }
9,778
22.283333
158
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/glas/GlasEvent.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.glas; /** * @author Klaus Raizer * */ public class GlasEvent { private int stimulus; private int action; private double reward; public GlasEvent(int stimulus, int action, double reward) { this.stimulus=stimulus; this.action=action; this.reward=reward; } /** * @return the stimulus */ public int getStimulus() { return stimulus; } /** * @param stimulus the stimulus to set */ public void setStimulus(int stimulus) { this.stimulus = stimulus; } /** * @return the action */ public int getAction() { return action; } /** * @param action the action to set */ public void setAction(int action) { this.action = action; } /** * @return the reward */ public double getReward() { return reward; } /** * @param reward the reward to set */ public void setReward(double reward) { this.reward = reward; } }
1,453
18.917808
82
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/glas/GlasSequence.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.glas; import java.util.ArrayList; /** * @author Klaus Raizer * */ public class GlasSequence { private ArrayList<GlasEvent> events= new ArrayList<GlasEvent>(); public void clearAllEvents(){ events.clear(); } public void addEvent(GlasEvent event) { events.add(event); } public void removeEvent(int index){ events.remove(index); } /** * @return the events */ public ArrayList<GlasEvent> getEvents() { ArrayList<GlasEvent> newEvents= new ArrayList<GlasEvent>(); newEvents.addAll(events); return newEvents; } /** * @param events the events to set */ public void setEvents(ArrayList<GlasEvent> events) { this.events = events; } public void addAll(GlasSequence given_sequence) { ArrayList<GlasEvent> local_events = given_sequence.getEvents(); for(GlasEvent ev : local_events){ this.addEvent(ev); } } /** * Calculates the number of stimuli in this sequence. * The number of stimuli is estimated as being the largest integer number present in the current sequence list of stimuli, plus one * @return the number of stimuli in this sequence */ public int getNStimuli() { int nStimuli=0; for(int i = 0; i<this.getEvents().size();i++){ int stim = this.getEvents().get(i).getStimulus(); if(stim>nStimuli){ nStimuli=stim; } } nStimuli=nStimuli+1; return nStimuli; } /** * Calculates the number of actions in this sequence. * The number of actions is estimated as being the largest integer number present in the current sequence list of actions, plus one * @return the number of actions in this sequence */ public int getNActions() { int nActions=0; for(int i = 0; i<this.getEvents().size();i++){ int act = this.getEvents().get(i).getAction(); if(act>nActions){ nActions=act; } } nActions=nActions+1; return nActions; } }
2,430
23.069307
133
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/glas/GlasSequenceElements.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.glas; public enum GlasSequenceElements { SENSED_STIMULUS, EXPECTED_ACTION, REWARD_RECEIVED }
680
33.05
82
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/glas/Individual.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.glas; import java.util.ArrayList; import java.util.Random; /** * @author Klaus Raizer * */ public class Individual { private int nNodes; private int nStimuli; private int nActions; private int[] chromossome; private GlasActionSelection state_machine; private double nf=0; public Individual(int nNodes, int nStimuli, int nActions) { this.nNodes=nNodes; this.nStimuli=nStimuli; this.nActions=nActions; chromossome= new int[3*nNodes]; Random generator = new Random(); //Random contents for(int i=nNodes+1;i<2*nNodes;i++){ chromossome[i]=generator.nextInt(nStimuli); } chromossome[nNodes+1]=0; //unknown //Random actions for(int i=2*nNodes+1;i<3*nNodes;i++){ chromossome[i]=generator.nextInt(nActions); } //Random structure for(int node=1;node<nNodes;node++){ chromossome[node]=generator.nextInt(node)+1; } // %- Initial structures // treeStructure=sample_individual(1:nNodes); // randomStructure=repmat(treeStructure,N,1); // structureNum=randomStructure(:,1:nNodes); // shouldMutate=(ones(N,nNodes)); // shouldMutate(:,1)=zeros(N,1); %avoid mutating root node // for node=2:nNodes // mutation(:,node)=randi(node-1,N,1); // end // mutated_statesNum=mutation.*shouldMutate+structureNum.*not(shouldMutate); // randomStructure(:,1:nNodes)=mutated_statesNum; // %-------- this.state_machine=new GlasActionSelection(chromossome); } public int[] getChromossome() { return chromossome; } public void setChromossome(int[] chromossome) { this.chromossome = chromossome; this.state_machine=new GlasActionSelection(chromossome); } /** * Evaluates this individual's evaluation. The lower the better. * @param sequence * @return individual's evaluation */ public double getEvaluation(GlasSequence sequence){ double eval=Double.MAX_VALUE; double fitRewards=getFitness(sequence); if(fitRewards!=0){ //Eval = inverse fitness eval=1/fitRewards; }else{ eval=0; } return (eval); } /** * Evaluates this individual's fitness. The higher the better. * @param sequence * @return individual's fitness */ public double getFitness(GlasSequence sequence){ // double eval=Double.MAX_VALUE; ArrayList<GlasEvent> events = sequence.getEvents(); int[] stimuli=new int[events.size()]; int[] actions=new int[events.size()]; double[] rewards=new double[events.size()]; GlasEvent event = events.get(0); for (int ev=0;ev<events.size();ev++){ event = events.get(ev); stimuli[ev]=event.getStimulus(); actions[ev]=event.getAction(); rewards[ev]=event.getReward(); } state_machine.reset(); int[] selected_actions = state_machine.runStimuli(stimuli); // System.out.println(""); // System.out.print("selected_actions = ["); // for(int index=0; index<selected_actions.length;index++){ // System.out.print(selected_actions[index]+", "); // } // System.out.println("]"); //stimuliNum=sequence(1,:); //actionsNum=sequence(2,:); //rewards=sequence(3,:); //N=size(population,1); // //currentStateNum=1; %'Starting' //fitRewards=zeros(1,N); //% //%% Fitness due to rewards double fitRewards=0; for(int i=0; i<events.size();i++){ if(actions[i]==selected_actions[i]){//Otherwise, I just can't tell fitRewards=fitRewards+rewards[i]; } } // --- Bonus for visiting a smaller number of intermediate nodes //TODO Check if this is valid for all cases int[] nodes_history = state_machine.getNodes_history(); int[] nodes_types = state_machine.getNodes_types(); double bonus_int=0; for(int i=0; i<nodes_history.length;i++){ if(nodes_history[i]!=0){ if(nodes_types[nodes_history[i]-1]==state_machine.INTERMEDIATE_NODE){ bonus_int=bonus_int+1; } } } bonus_int=bonus_int/nodes_history.length; bonus_int=1-bonus_int; // -------------------------- // --- Bonus for having a smaller number of nodes --- // double bonus_smaller = 1.0/nNodes; double bonus_smaller = -nNodes; // ----------- // --- Bonus for more sequence starters --- double bonus_sn=0; for(int i=0; i<this.nNodes;i++){ if(this.chromossome[i]==1){ bonus_sn++; } } bonus_sn=bonus_sn/nNodes; // -------- double alpha=1; double beta=0; double gamma=1; double delta=1; fitRewards=fitRewards*alpha + bonus_int*beta + bonus_smaller*gamma + bonus_sn*delta; return fitRewards; } /** * Stores a normalized fitness value. * WARNING: As it is, it should only be used for debug purposes. * @param nf */ public void setNormalizedFitness(double nf) { this.nf=nf; } /** * Returns a normalized fitness value. * WARNING: As it is, it should only be used for debug purposes. * @return the normalized fitness nf */ public double getNormalizedFitness() { return nf; } }
5,443
22.982379
111
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/glas/Merger.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.glas; import java.util.ArrayList; import java.util.HashMap; /** * Merges sequences' branches of a given glas solution * @author klausr * */ public class Merger { private int nNodes=-1; public double[] merge(double[] unmerged_solution) { // TODO Implement merging algorithm here nNodes=Math.round(unmerged_solution.length/3); double[] temp_merged_solution= new double[unmerged_solution.length]; for(int i=0; i<temp_merged_solution.length;i++){ temp_merged_solution[i]=unmerged_solution[i]; } //START WHILE LOOP HERE int it_count=0; boolean merge_done=false; while(!merge_done){ merge_done=true; HashMap<Integer, Integer> nodes_contents = this.getNodesContents(temp_merged_solution); for(int parent_node=1; parent_node<temp_merged_solution.length;parent_node++){ ArrayList<Integer> children_nodes = this.getChildrenNodes(temp_merged_solution,parent_node); for(int child=0; child<children_nodes.size();child++){ int child_content=nodes_contents.get(children_nodes.get(child)); for(int sibling=child+1; sibling<children_nodes.size();sibling++){ int sibling_content = nodes_contents.get(children_nodes.get(sibling)); if(child_content==sibling_content){//Move sibling's children to child ArrayList<Integer> siblings_children = this.getChildrenNodes(temp_merged_solution, children_nodes.get(sibling)); for(Integer sibling_child: siblings_children){ temp_merged_solution[sibling_child-1]=children_nodes.get(child); } //Prune sibling away double[] temp2_merged_solution = new double[temp_merged_solution.length-3]; int count_p2=0; for(int p2=0;p2<nNodes;p2++){ if(p2!=children_nodes.get(sibling)-1){ temp2_merged_solution[count_p2]=temp_merged_solution[p2]; temp2_merged_solution[count_p2+(nNodes-1)]=temp_merged_solution[p2+nNodes]; temp2_merged_solution[count_p2+2*(nNodes-1)]=temp_merged_solution[p2+2*nNodes]; if(temp2_merged_solution[count_p2]>children_nodes.get(sibling)){ temp2_merged_solution[count_p2]--; } count_p2++; } } temp_merged_solution=temp2_merged_solution; merge_done=false; break; }//inside if } if(!merge_done){ break; } } if(!merge_done){ break; } }//Parent_node loop System.out.println("Iteration: "+it_count); it_count++; } return temp_merged_solution; } private HashMap<Integer,Integer> getNodesContents( double[] temp_merged_solution) { HashMap<Integer,Integer> nodes_contents = new HashMap<Integer,Integer>(); for(int i = nNodes;i<2*nNodes;i++){ nodes_contents.put(i-nNodes+1, (int)temp_merged_solution[i]); } return nodes_contents; } private ArrayList<Integer> getChildrenNodes(double[] temp_merged_solution, int parent_node) { ArrayList<Integer> children_nodes = new ArrayList<Integer>(); for(int i = 0;i<nNodes; i++){ if((int)temp_merged_solution[i]==parent_node){ children_nodes.add(i+1); } } return children_nodes; } }
3,693
25.963504
119
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/glas/Pruner.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.glas; import java.util.ArrayList; import java.util.Set; /** * Prunes a from a GLAS tree a list of nodes. * * @author Klaus * */ public class Pruner { private static int[] solution_tree; private static int[] structure; private static int[] stimuli; private static int[] actions; public Pruner(int[] solution_tree){ //TODO check if it is a valid tree this.solution_tree=solution_tree; int nNodes=solution_tree.length/3; this.structure = new int[nNodes]; this.stimuli = new int[nNodes]; this.actions = new int[nNodes]; for(int i=0; i<nNodes;i++){ structure[i]=solution_tree[i]; } int count=0; for(int i=nNodes; i<2*nNodes;i++){ stimuli[count]=solution_tree[i]; count++; } count=0; for(int i=2*nNodes; i<3*nNodes;i++){ actions[count]=solution_tree[i]; count++; } } /** * Returns a new tree, which is a pruned version of the original one. * * @param nodes_to_be_pruned List of nodes that should be pruned from the original tree * @return the pruned solution */ public int[] pruneNodes(Set<Integer> nodes_to_be_pruned){ //TODO check if the list of nodes to be pruned is valid //TODO update nodes_to_be_pruned with children //-------------- // System.out.println("nodes_to_be_pruned:"); // for(Integer inteiro : nodes_to_be_pruned){ // System.out.print(inteiro+", "); // } // System.out.println(""); //-------------- // System.out.println("Initial tree: "); // for(Integer inteiro : tree){ // System.out.print(inteiro+", "); // } // System.out.println(""); // int[] indexes = new int[tree.length]; // System.out.println("indexes: "); // for(int i = 0; i<tree.length;i++){ // indexes[i]=i+1; // System.out.print(indexes[i]+", "); // } // System.out.println(""); ArrayList<Integer> tree_arraylist= new ArrayList<Integer>(); ArrayList<Integer> nodes_numbers_arraylist= new ArrayList<Integer>(); for(int i=0; i<structure.length;i++){ if(!nodes_to_be_pruned.contains(i+1)){ tree_arraylist.add(structure[i]); nodes_numbers_arraylist.add(i+1); } } // //-------------- // System.out.println("tree_arraylist:"); // for(Integer inteiro : tree_arraylist){ // System.out.print(inteiro+", "); // } // System.out.println(""); // // System.out.println("nodes_numbers_arraylist:"); // for(Integer inteiro : nodes_numbers_arraylist){ // System.out.print(inteiro+", "); // } // System.out.println(""); // //-------------- for(int i = 0; i < nodes_numbers_arraylist.size()-1;i++){ int current_node_index=nodes_numbers_arraylist.get(i); int next_node_index = nodes_numbers_arraylist.get(i+1); if((current_node_index+1)!=next_node_index){ for(int j = i; j<nodes_numbers_arraylist.size();j++){ if(nodes_numbers_arraylist.get(j)==next_node_index){ // replace nodes_numbers_arraylist.set(j, current_node_index+1); } if(tree_arraylist.get(j)==next_node_index){ // replace tree_arraylist.set(j, current_node_index+1); } } } } // //-------------- // System.out.println("pruned tree_arraylist:"); // for(Integer inteiro : tree_arraylist){ // System.out.print(inteiro+", "); // } // System.out.println(""); // // System.out.println("pruned nodes_numbers_arraylist:"); // for(Integer inteiro : nodes_numbers_arraylist){ // System.out.print(inteiro+", "); // } // System.out.println(""); // //-------------- ArrayList<Integer> pruned_solution_array=new ArrayList<Integer>(); for(int i = 0; i<tree_arraylist.size();i++){ pruned_solution_array.add(tree_arraylist.get(i)); } for(int i = 0; i<this.stimuli.length;i++){ if(!nodes_to_be_pruned.contains(i+1)){ pruned_solution_array.add(this.stimuli[i]); } } for(int i = 0; i<this.actions.length;i++){ if(!nodes_to_be_pruned.contains(i+1)){ pruned_solution_array.add(this.actions[i]); } } int[] pruned_solution=new int[pruned_solution_array.size()]; for(int i = 0; i<pruned_solution_array.size();i++){ pruned_solution[i]=pruned_solution_array.get(i); } return pruned_solution; } }
4,723
22.979695
88
java
cst
cst-master/src/main/java/br/unicamp/cst/behavior/glas/SequenceBuilderCodelet.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.glas; import java.sql.Timestamp; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.entities.RawMemory; import br.unicamp.cst.memory.WorkingStorage; /** * This class records the sequence of events seen by the agent, * @author klaus * */ public class SequenceBuilderCodelet extends Codelet { private boolean enabled = true; private Memory STIMULUS_MO; private Memory ACTION_MO; private Memory PREVIOUS_REWARD_MO; //Reward for i=1 a,s pair private boolean first_run=true; private Timestamp previous_stimulus_time_stamp; private JSONArray sequence = new JSONArray(); private Memory EVENTS_SEQUENCE_MO; private int sensed_stimulus; private int expected_action; private double reward_received; private boolean printEvents=false; private Memory NEW_EVENT_DETECTED_MO; private Memory NEW_STIM_MO; private Memory NEW_ACTION_MO; private Memory NEW_REWARD_MO; private RawMemory rawMemory; public SequenceBuilderCodelet(RawMemory rawMemory,WorkingStorage ws) { this.rawMemory = rawMemory; if(ws!=null) { ws.registerCodelet(this,"SOLUTION_TREE", 0); ws.registerCodelet(this,"STIMULUS", 0); ws.registerCodelet(this,"ACTION", 0); ws.registerCodelet(this,"REWARD", 0); } if(rawMemory!=null) EVENTS_SEQUENCE_MO=rawMemory.createMemoryObject("EVENTS_SEQUENCE", ""); this.addOutput(EVENTS_SEQUENCE_MO); if(ws!=null) ws.putMemoryObject(EVENTS_SEQUENCE_MO); if(rawMemory!=null) NEW_EVENT_DETECTED_MO=rawMemory.createMemoryObject("NEW_EVENT_DETECTED", "FALSE"); this.addOutput(NEW_EVENT_DETECTED_MO); if(ws!=null) ws.putMemoryObject(NEW_EVENT_DETECTED_MO); if(rawMemory!=null) { NEW_STIM_MO = rawMemory.createMemoryObject("NEW_STIM", String.valueOf(false)); NEW_ACTION_MO = rawMemory.createMemoryObject("NEW_ACTION", String.valueOf(false)); NEW_REWARD_MO = rawMemory.createMemoryObject("NEW_REWARD", String.valueOf(false)); } this.addOutput(NEW_STIM_MO); this.addOutput(NEW_ACTION_MO); this.addOutput(NEW_REWARD_MO); if(ws!=null) { ws.putMemoryObject(NEW_STIM_MO); ws.putMemoryObject(NEW_ACTION_MO); ws.putMemoryObject(NEW_REWARD_MO); } if(rawMemory!=null) { STIMULUS_MO = rawMemory.createMemoryObject("STIMULUS", ""); PREVIOUS_REWARD_MO = rawMemory.createMemoryObject("REWARD", ""); //reward for i-1 s,a pair } this.addInput(STIMULUS_MO); this.addInput(PREVIOUS_REWARD_MO); if(ws!=null) { ws.putMemoryObject(STIMULUS_MO); ws.putMemoryObject(PREVIOUS_REWARD_MO); } } @Override public void accessMemoryObjects() { // STIMULUS_MO=this.getInput(MemoryObjectTypesGlas.STIMULUS, 0); ACTION_MO=this.getInput("ACTION", 0); // PREVIOUS_REWARD_MO=this.getInput(MemoryObjectTypesGlas.REWARD, 0); // int index=0; // NEW_STIM_MO = this.getOutput(MemoryObjectTypesGlas.NEW_STIM, index); // NEW_ACTION_MO = this.getOutput(MemoryObjectTypesGlas.NEW_ACTION, index); // NEW_REWARD_MO = this.getOutput(MemoryObjectTypesGlas.NEW_REWARD, index); } @Override public void calculateActivation() { // TODO Auto-generated method stub } @Override public void proc() { if(enabled){ boolean new_stim=(NEW_STIM_MO.getI().equals(String.valueOf(true))); boolean new_action=(NEW_ACTION_MO.getI().equals(String.valueOf(true))); boolean new_reward=(NEW_REWARD_MO.getI().equals(String.valueOf(true))); if(new_stim && new_action && new_reward){ //OK to snapshot an event! try{ sensed_stimulus=Integer.valueOf((String) STIMULUS_MO.getI()); }catch(NumberFormatException e){ sensed_stimulus=0; } try{ expected_action=Integer.valueOf((String) ACTION_MO.getI()); }catch(NumberFormatException e){ expected_action=0; } try{ reward_received=Double.valueOf((String) PREVIOUS_REWARD_MO.getI()); }catch(NumberFormatException e){ reward_received=0.0; } if(this.printEvents){ System.out.println("Event:"+sensed_stimulus+", "+expected_action+", "+reward_received); } JSONObject event; try { event = new JSONObject();//A new event each time event.put(GlasSequenceElements.SENSED_STIMULUS.toString(), sensed_stimulus); event.put(GlasSequenceElements.EXPECTED_ACTION.toString(), expected_action); event.put(GlasSequenceElements.REWARD_RECEIVED.toString(), reward_received); //-------------------- // int s = event.getInt(GlasSequenceElements.SENSED_STIMULUS.toString()); // int a = event.getInt(GlasSequenceElements.EXPECTED_ACTION.toString()); // double r = event.getInt(GlasSequenceElements.REWARD_RECEIVED.toString()); //---------------- sequence.put(event); } catch (JSONException e) { e.printStackTrace(); } EVENTS_SEQUENCE_MO.setI(sequence.toString()); //---------- NEW_STIM_MO.setI(String.valueOf(false)); NEW_ACTION_MO.setI(String.valueOf(false)); NEW_REWARD_MO.setI(String.valueOf(false)); }//if enable }// proc() } /** * Prints the whole sequence stored in memory */ public void printSequence() { System.out.println("------------------------------------"); try { JSONArray es = new JSONArray(EVENTS_SEQUENCE_MO.getI()); for(int i=0; i<es.length();i++){ JSONObject ev = es.getJSONObject(i); System.out.println(i+"(s,a,r)=("+ev.getInt(GlasSequenceElements.SENSED_STIMULUS.toString())+","+ev.getInt(GlasSequenceElements.EXPECTED_ACTION.toString())+","+ev.getInt(GlasSequenceElements.REWARD_RECEIVED.toString())+")"); } } catch (JSONException e) { } System.out.println("------------------------------------"); } /** * @return the printEvents */ public boolean isPrintEvents() { return printEvents; } /** * @param printEvents the printEvents to set */ public void setPrintEvents(boolean printEvents) { this.printEvents = printEvents; } /** * @return the enabled */ public boolean isEnabled() { return enabled; } /** * @param enabled the enabled to set */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * @return the EVENTS_SEQUENCE_MO */ public Memory getEVENTS_SEQUENCE_MO() { return EVENTS_SEQUENCE_MO; } /** * @param eVENTS_SEQUENCE_MO the eVENTS_SEQUENCE_MO to set */ public void setEVENTS_SEQUENCE_MO(Memory eVENTS_SEQUENCE_MO) { EVENTS_SEQUENCE_MO = eVENTS_SEQUENCE_MO; } }
7,071
26.305019
227
java
cst
cst-master/src/main/java/br/unicamp/cst/consciousness/SpotlightBroadcastController.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.consciousness; import java.util.ArrayList; import java.util.List; import br.unicamp.cst.core.entities.CodeRack; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.exceptions.CodeletActivationBoundsException; /** * A codelet-based implementation of the Global Workspace Theory, originally * formulated in [1988 Baars] Bernard J. Baars. A Cognitive Theory of * Consciousness. Cambridge University Press, 1988. * * @author A. L. O. Paraense * @see Codelet * */ public class SpotlightBroadcastController extends Codelet { private Codelet consciousCodelet; /** access to all codelets, so the broadcast can be made */ private CodeRack codeRack; private double thresholdActivation = 0.9d; /** * Creates a SpotlightBroadcastController. * * @param codeRack the codeRack containing all Codelets. */ public SpotlightBroadcastController(CodeRack codeRack) { this.setName("SpotlightBroadcastController"); this.codeRack = codeRack; consciousCodelet = null; this.timeStep = 300l; } /* * (non-Javadoc) * * @see br.unicamp.cogsys.core.entities.Codelet#accessMemoryObjects() */ @Override public void accessMemoryObjects() { } /* * (non-Javadoc) * * @see br.unicamp.cogsys.core.entities.Codelet#calculateActivation() */ @Override public void calculateActivation() { try { setActivation(0.0d); } catch (CodeletActivationBoundsException e) { e.printStackTrace(); } } /* * (non-Javadoc) * * @see br.unicamp.cogsys.core.entities.Codelet#proc() */ @Override public void proc() { if (consciousCodelet != null) { if (consciousCodelet.getActivation() < thresholdActivation) { consciousCodelet = null; } } if (codeRack != null) { // first, select the coalition with greater activation to gain // consciousness List<Codelet> allCodeletsList = codeRack.getAllCodelets(); if (allCodeletsList != null) { for (Codelet codelet : allCodeletsList) { if (consciousCodelet == null) { if (codelet.getActivation() > thresholdActivation) { consciousCodelet = codelet; } } else { if (codelet.getActivation() > consciousCodelet.getActivation()) { consciousCodelet = codelet; } } } // then, broadcast its information to all codelets if (consciousCodelet != null) { List<Memory> memoriesToBeBroadcasted = consciousCodelet.getOutputs(); if (memoriesToBeBroadcasted != null) { for (Codelet codelet : allCodeletsList) { if (!codelet.getName().equalsIgnoreCase(consciousCodelet.getName())) codelet.setBroadcast(memoriesToBeBroadcasted); else codelet.setBroadcast(new ArrayList<Memory>()); } } else { for (Codelet codelet : allCodeletsList) { codelet.setBroadcast(new ArrayList<Memory>()); } } } else { for (Codelet codelet : allCodeletsList) { codelet.setBroadcast(new ArrayList<Memory>()); } } } } } }
3,599
26.272727
82
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/CSTMessages.java
/******************************************************************************* * Copyright (c) 2016 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * E. M. Froes, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.core.entities; /** * This class represents CST's message inside the emotional system, consisting * of drive messages, goal messages and affordance messages. * * @author E. M. Froes * */ public class CSTMessages { // DRIVE MESSAGES. public static final String MSG_VAR_NAME_NULL = "Drive name is null."; public static final String MSG_VAR_RELEVANCE = "Drive relevance must be less equal than 1 and greater equal than 0."; public static final String MSG_VAR_PRIORITY_NULL = "Drive priority is null."; public static final String MSG_VAR_URGENT_ACTIVATION_RANGE = "Drive urgent activation must be less equal than 1 and greater equal than 0."; public static final String MSG_VAR_URGENT_ACTIVATION_THRESHOLD_RANGE = "Drive urgent activation threshold must be less equal than 1 and greater equal than 0."; public static final String MSG_VAR_LOWER_URGENT_ACTIVATION_THRESHOLD_RANGE = "Drive lower urgent activation threshold must be less equal than 1 and greater equal than 0."; public static final String MSG_VAR_HIGH_PRIORITY = "Drive high priority must be less equal than 1 and greater equal than 0."; // GOAL MESSAGES. public static final String MSG_VAR_EMOTIONAL_NAME_NULL = "EmotionalCodelet name is null"; public static final String MSG_VAR_EMOTIONAL_DRIVE_VOTES = "EmotionalCodelet drive votes is null or empty."; public static final String MSG_VAR_EMOTIONAL_INTERVENTION_THRESHOLD = "Intervention threshold must be less equal than 1 and greater equal than 0."; // AFFORDANCE MESSAGES. public static final String MSG_VAR_DETECTOR_OBJECT = "Detector object is null."; public static final String MSG_VAR_APPLY_OBJECT = "Apply object is null."; }
2,226
52.02381
172
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/Coalition.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.core.entities; import java.util.List; /** * A Coalition is a group of Codelets which are gathered in order to perform a * task by summing up their abilities or to form a specific context. * * In CST, two codelets belong to the same coalition when they share information * - pragmatically, when they write in and read from the same memory object. * * @author A. L. O. Paraense * @author K. Raizer */ public class Coalition { /** * List of all Codelets in this Coalition */ private List<Codelet> codeletsList; /** * This Coalition's activation */ private double activation; /** * Creates a Coalition. * * @param codeletsList * the coalition's codelet list. */ public Coalition(List<Codelet> codeletsList) { this.codeletsList = codeletsList; this.activation = calculateActivation(); } /** * Calculates the coalition activation. * * @return the coalition activation. */ public double calculateActivation() { double activation = 0.0; if (codeletsList != null && codeletsList.size() > 0) { for (Codelet codelet : codeletsList) { activation += codelet.getActivation(); } activation /= codeletsList.size(); } return activation; } /** * Gets the codelets list. * * @return the codeletsList */ public List<Codelet> getCodeletsList() { return codeletsList; } /** * Sets the codelets list. * * @param codeletsList * the codeletsList to set */ public void setCodeletsList(List<Codelet> codeletsList) { this.codeletsList = codeletsList; } /** * Gets the coalition activation. * * @return the activation */ public double getActivation() { return activation; } /** * Sets the coalitions activation. * * @param activation * the activation to set */ public void setActivation(double activation) { this.activation = activation; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { final int maxLen = 10; return "Coalition [activation=" + activation + ", " + (codeletsList != null ? "codeletsList=" + codeletsList.subList(0, Math.min(codeletsList.size(), maxLen)) : "") + "]"; } }
2,779
22.965517
99
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/CodeRack.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.core.entities; import java.util.ArrayList; import java.util.List; import br.unicamp.cst.core.exceptions.CodeletActivationBoundsException; /** * * Following Hofstadter and Mitchell * "The copycat project: A model of mental fluidity and analogy-making". Pool of * all alive codelets in the system. The whole arena in the Baars-Franklin * metaphor. * * @author A. L. O. Paraense * @author K. Raizer * */ public class CodeRack { /** * List of all alive codelets in the system */ private List<Codelet> allCodelets; /** * Creates a CodeRack. */ public CodeRack() { allCodelets = new ArrayList<Codelet>(); } /** * Gets the list of all Codelets. * * @return the allCodelets. */ public synchronized List<Codelet> getAllCodelets() { return allCodelets; } /** * Sets the list of all Codelets. * * @param allCodelets * the allCodelets to set */ public void setAllCodelets(List<Codelet> allCodelets) { this.allCodelets = allCodelets; } /** * Adds a new Codelet to the Coderack * * @param co * codelet to be added. */ public void addCodelet(Codelet co) { allCodelets.add(co); } /** * Creates a codelet and adds it to this coderack. * * @param co * codelet to be created. * @return the own codelet inserted, if it is needed to concatenate to * further methods calls. */ public Codelet insertCodelet(Codelet co) { addCodelet(co); return co; } /** * Creates a codelet and adds it to this coderack. * * @param activation * codelet's activation. * @param broadcast * list of memory objects which were broadcast lately (treated as * input memories). * @param inputs * list of input memories. * @param outputs * list o output memories. * @param co * codelet to be created. * @return the codelet created. */ public Codelet createCodelet(double activation, List<Memory> broadcast, List<Memory> inputs, List<Memory> outputs, Codelet co) { try { co.setActivation(activation); } catch (CodeletActivationBoundsException e) { e.printStackTrace(); } co.setBroadcast(broadcast); co.setInputs(inputs); co.setOutputs(outputs); addCodelet(co); return co; } /** * Removes a codelet from coderack. * * @param co * the codelet to be destroyed. */ public void destroyCodelet(Codelet co) { co.stop(); this.allCodelets.remove(co); } /** * Destroys all codelets. Stops CodeRack's thread. */ public void shutDown() { for (Codelet co : this.getAllCodelets()) { co.stop(); } this.allCodelets.clear(); } /** * Starts all codelets in coderack. */ public void start() { for (Codelet co : this.getAllCodelets()) { synchronized (co) { co.start(); } } } /** * Stops all codelets within CodeRack. */ public void stop() { for (Codelet co : this.getAllCodelets()) { co.stop(); } } }
3,563
21.275
115
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/Codelet.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.core.entities; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import br.unicamp.cst.core.exceptions.CodeletActivationBoundsException; import br.unicamp.cst.core.exceptions.CodeletThresholdBoundsException; import br.unicamp.cst.core.exceptions.MemoryObjectNotFoundException; import br.unicamp.cst.support.CodeletsProfiler; import br.unicamp.cst.support.CodeletsProfiler.FileFormat; import br.unicamp.cst.support.ExecutionTimeWriter; import br.unicamp.cst.support.ProfileInfo; import java.util.logging.Level; import java.util.logging.Logger; /** * The <b><i>Codelet</i></b> class, together with the <b><i>MemoryObject</i></b> * class and the <b><i>Mind</i></b> class is one of the most important classes * in the CST toolkit. According to the Baars-Franklin architecture, * consciousness is the emergence of a serial stream on top of a parallel set of * interacting devices. In the Baars-Franklin architectures, such devices are * called "codelets", which are small pieces of code specialized in performing * simple tasks. In a CST-built cognitive architecture, everything is either a * <b><i>Codelet</i></b> or a <b><i>MemoryObject</i></b>. Codelets are used to * implement every kind of processing in the architecture. * * Codelets have two kinds of inputs: standard inputs and broadcast inputs. * Standard inputs are used to convey access to MemoryObjects. Broadcast inputs * come from consciousness, and can also be used. Nevertheless, Standard inputs * are usually fixed (but can be changed through learning mechanisms), and * Broadcast inputs change all the time, due to the consciousness mechanism. * Codelets also have outputs. Outputs are used for the Codelets to write or * generate new MemoryObjects. Codelets also have an Activation level, which can * be used in some situations. * * @author A. L. O. Paraense * @author K. Raizer * @see Memory * @see Mind * @see Runnable */ public abstract class Codelet implements Runnable, MemoryObserver { /** * Activation level of the Codelet. Ranges from 0.0 to 1.0d. */ protected double activation = 0.0d; /** * Threshold of the codelet, which is used to decide if it runs or not. If * activation is equal or greater than activation, codelet runs * proc().Ranges from 0.0 to 1.0d. */ protected double threshold = 0.0d; /** * Input memories, the ones that are read. */ protected List<Memory> inputs = new ArrayList<Memory>(); /** * Output memories, the ones that are written. */ protected List<Memory> outputs = new ArrayList<Memory>(); /** * Input memories, the ones that were broadcasted. */ protected List<Memory> broadcast = new ArrayList<Memory>(); /** defines if proc() should be automatically called in a loop */ protected boolean loop = true; // /** defines if codelet is a memory observer (runs when memory input changes) */ protected boolean isMemoryObserver = false; // /** * If the proc() method is set to be called automatically in a loop, this * variable stores the time step for such a loop. A timeStep of value 0 * means that the proc() method should be called continuously, without * interval. */ protected long timeStep = 300l; // /** * A codelet is a priori enabled to run its proc(). However, if it tries to * read from a given output and fails, it becomes not able to do so. */ private boolean enabled = true; /** Must be zero for this codelet to be enabled */ private int enable_count = 0; /** Gives this codelet a name, mainly for debugging purposes */ protected String name = Thread.currentThread().getName(); /** The time for the last proc() execution for profiling purposes */ long laststarttime = 0l; /** This variable is a safe lock for multithread access */ public Lock lock = new ReentrantLock(); /** * This method is used in every Codelet to capture input, broadcast and * output MemoryObjects which shall be used in the proc() method. This * abstract method must be implemented by the user. Here, the user must get * the inputs and outputs it needs to perform proc. */ public abstract void accessMemoryObjects(); /** * This abstract method must be implemented by the user. Here, the user must * calculate the activation of the codelet before it does what it is * supposed to do in proc(); */ public abstract void calculateActivation(); /** * Main Codelet function, to be implemented in each subclass. */ public abstract void proc(); private Timer timer = new Timer(); /** * Option for profiling execution times */ private boolean isProfiling = false; /** * Information for profiling */ private List<ProfileInfo> profileInfo = new ArrayList<>(); /** * Codelet profiler */ private CodeletsProfiler codeletProfiler; /** * When first activated, the thread containing this codelet runs the proc() * method */ public synchronized void run() { try { this.timer.cancel(); // this will cancel the current task. if there // is no active task, nothing happens this.timer = new Timer(); timer.schedule(new CodeletTimerTask(), 0l); // first execution // should be immediate, // hence the 0l in delay // for scheduling } catch (Exception e) { e.printStackTrace(); } } /** * Starts this codelet execution. */ public synchronized void start() { Thread t = new Thread(this); t.start(); } /** * Tells this codelet to stop looping (stops running) */ public synchronized void stop() { this.setLoop(false); if (Codelet.this.codeletProfiler != null) { Codelet.this.codeletProfiler.finishProfile(Codelet.this); } } /** * Safe access to other Codelets through reentrant locks. * * @param accesing * the Codelet accessing. * @return true if is impeding access. */ public synchronized boolean impendingAccess(Codelet accesing) { Boolean myLock = false; Boolean yourLock = false; try { myLock = lock.tryLock(); yourLock = accesing.lock.tryLock(); } finally { if (!(myLock && yourLock)) { if (myLock) { lock.unlock(); } if (yourLock) { accesing.lock.unlock(); } } } return myLock && yourLock; } /** * Safe access to MemoryBuffers through reentrant locks * * @param accesing * the Memory Buffer accessing. * @return true if is impending Access. */ public synchronized boolean impendingAccessBuffer(MemoryBuffer accesing) { Boolean myLock = false; Boolean yourLock = false; try { myLock = lock.tryLock(); yourLock = accesing.lock.tryLock(); } finally { if (!(myLock && yourLock)) { if (myLock) { lock.unlock(); } if (yourLock) { accesing.lock.unlock(); } } } return myLock && yourLock; } /** * Gets if this Codelet is looping. * * @return the loop */ public synchronized boolean shouldLoop() { return loop; } /** * Sets this Codelet to loop. * * @param loop * the loop to set */ public synchronized void setLoop(boolean loop) { this.loop = loop; } /** * Gets the enable status. * * @return the enable state. */ public synchronized boolean getEnabled() { return enabled; } /** * Set the enable status. * * @param status the new enable status */ public synchronized void setEnabled(boolean status) { enabled = status; if (status == true) enable_count = 0; } /** * Gets this Codelet name. * * @return the name. */ public synchronized String getName() { return name; } /** * Sets this Codelet name. * * @param name * the name to set */ public synchronized void setName(String name) { this.name = name; } /** * Gets if this Codelet is looping. * * @return the loop */ public synchronized boolean isLoop() { return loop; } /** * Gets this Codelet activation. * * @return the activation */ public synchronized double getActivation() { return activation; } /** * Sets this codelet's activation. * * @param activation * the activation to set * @throws CodeletActivationBoundsException * exception triggered if an activation lower than 0 or bigger * than 1 is set */ public synchronized void setActivation(double activation) throws CodeletActivationBoundsException { if (activation > 1.0d) { this.activation = 1.0d; throw (new CodeletActivationBoundsException("Codelet activation set to value > 1.0")); } else if (activation < 0.0d) { this.activation = 0.0d; throw (new CodeletActivationBoundsException("Codelet activation set to value < 0.0")); } else { this.activation = activation; } } /** * Gets the input memories list. * * @return the inputs. */ public synchronized List<Memory> getInputs() { return inputs; } /** * Sets the input memories list. * * @param inputs * the inputs to set. */ public synchronized void setInputs(List<Memory> inputs) { this.inputs = inputs; } /** * Add one memory to the input list. * * @param input * one input to set. */ public synchronized void addInput(Memory input) { if (isMemoryObserver) { input.addMemoryObserver(this); } this.inputs.add(input); } /** * Add a list of memories to the input list. * * @param inputs * a list of inputs. */ public synchronized void addInputs(List<Memory> inputs) { if (isMemoryObserver) { for (Memory memory : inputs) { memory.addMemoryObserver(this); } } this.inputs.addAll(inputs); } /** * Add a memory to the output list. * * @param output * one output to set. */ public synchronized void addOutput(Memory output) { this.outputs.add(output); } /** * Removes a given memory from the output list. * * @param output * the memory to be removed from output. */ public synchronized void removesOutput(Memory output) { this.outputs.remove(output); } /** * Removes a given memory from the input list. * * @param input * the memory to be removed from input. */ public synchronized void removesInput(Memory input) { this.inputs.remove(input); } /** * Removes a given memory list from the output list. * * @param outputs * the list of memories to be removed from output. */ public synchronized void removeFromOutput(List<Memory> outputs) { this.outputs.removeAll(outputs); } /** * Removes a given list of memories from the input list. * * @param inputs * the list of memories to be removed from input. */ public synchronized void removeFromInput(List<Memory> inputs) { this.inputs.removeAll(inputs); } /** * Adds a list of memories to the output list. * * @param outputs * the list of memories to be added to the output. */ public synchronized void addOutputs(List<Memory> outputs) { this.outputs.addAll(outputs); } /** * Gets the list of output memories. * * @return the outputs. */ public synchronized List<Memory> getOutputs() { return outputs; } /** * Gets a list of output memories of a certain type. * * @param type * the type of memories to be fetched from the output. * @return the list of all memory objects in output of a given type. */ public synchronized ArrayList<Memory> getOutputsOfType(String type) { ArrayList<Memory> outputsOfType = new ArrayList<Memory>(); if (outputs != null && outputs.size() > 0) for (Memory mo : this.outputs) { if (mo.getName() != null && mo.getName().equalsIgnoreCase(type)) { outputsOfType.add(mo); } } return outputsOfType; } /** * Gets a list of input memories of a certain type. * * @param type * the type of memories to be retrieved. * @return the list of memory objects in input of a given type. */ public synchronized ArrayList<Memory> getInputsOfType(String type) { ArrayList<Memory> inputsOfType = new ArrayList<Memory>(); if (inputs != null && inputs.size() > 0) for (Memory mo : this.inputs) { if (mo.getName() != null && mo.getName().equalsIgnoreCase(type)) { inputsOfType.add(mo); } } return inputsOfType; } /** * Sets the list of output memories. * * @param outputs * the outputs to set. */ public synchronized void setOutputs(List<Memory> outputs) { this.outputs = outputs; } /** * Gets the list of broadcast memories. * * @return the broadcast. */ public synchronized List<Memory> getBroadcast() { return broadcast; } /** * Sets the list of broadcast memories. * * @param broadcast * the broadcast to set. */ public synchronized void setBroadcast(List<Memory> broadcast) { this.broadcast = broadcast; } /** * Returns a specific memory (with the given name) from the broadcast list * of the Codelet. * * @param name * the name of a memory to be retrieved at the broadcast list. * @return the list of memories in the broadcast list. */ public synchronized Memory getBroadcast(String name) { if (broadcast != null && broadcast.size() > 0) for (Memory mo : broadcast) { if (mo.getName() != null && mo.getName().equalsIgnoreCase(name)) return mo; } return null; } /** * Adds a memory to the broadcast list. * * @param b * one broadcast input to set. */ public synchronized void addBroadcast(Memory b) { if (isMemoryObserver) { b.addMemoryObserver(this); } this.broadcast.add(b); } /** * Adds a list of memories to the broadcast input list. * * @param broadcast * one input to set. */ public synchronized void addBroadcasts(List<Memory> broadcast) { if (isMemoryObserver) { for (Memory memory : broadcast) { memory.addMemoryObserver(this); } } this.broadcast.addAll(broadcast); } /** * Gets the Codelet's Java Thread name, for debugging purposes. * * @return The name of the thread running this Codelet. */ public synchronized String getThreadName() { return Thread.currentThread().getName(); } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public synchronized String toString() { final int maxLen = 10; return "Codelet [activation=" + activation + ", " + "name=" + name + ", " + (broadcast != null ? "broadcast=" + broadcast.subList(0, Math.min(broadcast.size(), maxLen)) + ", " : "") + (inputs != null ? "inputs=" + inputs.subList(0, Math.min(inputs.size(), maxLen)) + ", " : "") + (outputs != null ? "outputs=" + outputs.subList(0, Math.min(outputs.size(), maxLen)) : "") + "]"; } /** * This method returns an input memory from its input list. If it couldn't * find the given M, it sets this codelet as not able to perform proc(), and * keeps trying to find it. * * @param type * type of memory it needs. * @param index * position of memory in the sublist. * @return memory of type at position. */ public synchronized Memory getInput(String type, int index) { Memory inputMO = null; ArrayList<Memory> listMO = new ArrayList<Memory>(); if (inputs != null && inputs.size() > 0) for (Memory mo : inputs) { if (mo.getName() != null && mo.getName().equalsIgnoreCase(type)) { listMO.add(mo); } } if (listMO.size() >= index + 1) { inputMO = listMO.get(index); this.enabled = true; } else { this.enabled = false; // It must not run proc yet, for it still // needs to find this mo it wants enable_count++; } return inputMO; } /** * Gets a certain memory from the input list by its name. * * @param name * the name of the memory being searched. * @return the memory searched by name or null if not found. */ public synchronized Memory getInput(String name) { if (inputs != null && inputs.size() > 0) for (Memory mo : inputs) { if (mo.getName() != null && mo.getName().equalsIgnoreCase(name)) return mo; } return null; } /** * This method returns an output memory from its output list. If it couldn't * find the given M, it sets this codelet as not able to perform proc(), and * keeps trying to find it. * * @param type * type of memory it needs. * @param index * position of memory in the sublist. * @return memory of type at position. */ public synchronized Memory getOutput(String type, int index) { Memory outputMO = null; ArrayList<Memory> listMO = new ArrayList<Memory>(); if (outputs != null && outputs.size() > 0) for (Memory mo : outputs) { if (mo != null && type != null && mo.getName() != null && mo.getName().equalsIgnoreCase(type)) { listMO.add(mo); } } if (listMO.size() >= index + 1) { outputMO = listMO.get(index); this.enabled = true; } else { this.enabled = false; // It must not run proc yet, for it still // needs to find this mo it wants enable_count++; } return outputMO; } /** * Gets a Memory from the output list by its name. * * @param name * the name of the memory. * @return the memory with the name searched or null if not found. */ public synchronized Memory getOutput(String name) { if (outputs != null && outputs.size() > 0) for (Memory mo : outputs) { if (mo.getName() != null && mo.getName().equalsIgnoreCase(name)) return mo; } return null; } /** * Return a memory if its name is found at the broadcast list ... if more * than one memory with the same name, it return the one at the index * position. * * @param type * the name of the memory to be retrieved in the broadcast list. * @param index * the index to be considered while multiple equal names are * found within the broadcast list. * @return the memory. */ public synchronized Memory getBroadcast(String type, int index) { Memory broadcastMO = null; ArrayList<Memory> listMO = new ArrayList<Memory>(); if (broadcast != null && broadcast.size() > 0) { for (Memory mo : broadcast) { if (mo.getName() != null && mo.getName().equalsIgnoreCase(type)) { listMO.add(mo); } } } if (listMO.size() >= index + 1) { broadcastMO = listMO.get(index); } return broadcastMO; } /** * Gets the Codelet's threshold. * * @return the threshold. */ public synchronized double getThreshold() { return threshold; } /** * Sets the Codelet's threshold. * * @param threshold * the threshold to be set. * @throws CodeletThresholdBoundsException * the exception thrown if the threshold value is less than zero * or greater than 1. */ public synchronized void setThreshold(double threshold) throws CodeletThresholdBoundsException { if (threshold > 1.0d) { this.threshold = 1.0d; throw (new CodeletThresholdBoundsException("Codelet threshold set to value > 1.0")); } else if (threshold < 0.0d) { this.threshold = 0.0d; throw (new CodeletThresholdBoundsException("Codelet threshold set to value < 0.0")); } else { this.threshold = threshold; } } /** * Gets the Codelet' s timestep. * * @return the timeStep. */ public synchronized long getTimeStep() { return timeStep; } /** * Sets the Codelet's timestep. * * @param timeStep * the timeStep to set. */ public synchronized void setTimeStep(long timeStep) { this.timeStep = timeStep; } /** * Gets if this Codelet is profiling. * * @return the isProfiling. */ public synchronized boolean isProfiling() { return isProfiling; } /** * Sets if this Codelet is profiling. * * @param isProfiling * the isProfiling to set */ public synchronized void setProfiling(boolean isProfiling) { this.isProfiling = isProfiling; } /** * Sets this Codelet to be a memory observer. * * @param isMemoryObserver * the isMemoryObserver to set */ public synchronized void setIsMemoryObserver(boolean isMemoryObserver) { this.isMemoryObserver = isMemoryObserver; } public synchronized void setPublishSubscribe(boolean enable) { if (enable) { setIsMemoryObserver(true); for (Memory m : inputs) { m.addMemoryObserver(this); } } else { setIsMemoryObserver(false); for (Memory m : inputs) { m.removeMemoryObserver(this); } run(); } } /** * Sets Codelet Profiler * * @param filePath * path to create file * @param fileName * name file * @param mindIdentifier * mind identifier in file * @param queueSize * max queue size which a write in file must be done * @param intervalTimeMillis * max interval in millis which a write in file must be done * @param fileFormat * desired file format CSV or JSON * */ public void setCodeletProfiler(String filePath, String fileName, String mindIdentifier,Integer queueSize, Long intervalTimeMillis, FileFormat fileFormat) { if (intervalTimeMillis == null) { this.codeletProfiler = new CodeletsProfiler(filePath, fileName, mindIdentifier, queueSize, fileFormat); } else if (queueSize == null) { this.codeletProfiler = new CodeletsProfiler(filePath, fileName, mindIdentifier, intervalTimeMillis, fileFormat); } else { this.codeletProfiler = new CodeletsProfiler(filePath, fileName, mindIdentifier, queueSize, intervalTimeMillis, fileFormat); } } private void raiseException() throws MemoryObjectNotFoundException { throw new MemoryObjectNotFoundException("This Codelet could not find a memory object it needs: " + Codelet.this.name); } /** * runs when codelet is a memory observer and memory input changes */ @Override public void notifyCodelet() { long startTime = 0l; long endTime = 0l; long duration = 0l; try { if (isProfiling) startTime = System.currentTimeMillis(); accessMemoryObjects();// tries to connect to memory objects if (enable_count == 0) { calculateActivation(); if (activation >= threshold) proc(); } else { raiseException(); } enable_count = 0; } catch (MemoryObjectNotFoundException ex) { Logger.getLogger(Codelet.class.getName()).log(Level.SEVERE, ex.getMessage()); } finally { if (Codelet.this.codeletProfiler != null) { Codelet.this.codeletProfiler.profile(Codelet.this); } if (isProfiling) { endTime = System.currentTimeMillis(); duration = (endTime - startTime); ProfileInfo pi = new ProfileInfo(duration, startTime, laststarttime); profileInfo.add(pi); laststarttime = startTime; if (profileInfo.size() >= 50) { ExecutionTimeWriter executionTimeWriter = new ExecutionTimeWriter(); executionTimeWriter.setCodeletName(name); executionTimeWriter.setPath("profile/"); executionTimeWriter.setProfileInfo(profileInfo); Thread thread = new Thread(executionTimeWriter); thread.start(); profileInfo = new ArrayList<>(); } } } } private class CodeletTimerTask extends TimerTask { @Override public synchronized void run() { long startTime = 0l; long endTime = 0l; long duration = 0l; try { if (isProfiling) startTime = System.currentTimeMillis(); if (!isMemoryObserver) accessMemoryObjects();// tries to connect to memory objects if (enable_count == 0) { if (isMemoryObserver == false) { calculateActivation(); if (activation >= threshold) proc(); } } else { raiseException(); } enable_count = 0; } catch (MemoryObjectNotFoundException ex) { Logger.getLogger(Codelet.class.getName()).log(Level.SEVERE, ex.getMessage()); } finally { if (!isMemoryObserver && shouldLoop()) timer.schedule(new CodeletTimerTask(), timeStep); if (Codelet.this.codeletProfiler != null) { Codelet.this.codeletProfiler.profile(Codelet.this); } if (isProfiling) { endTime = System.currentTimeMillis(); duration = (endTime - startTime); ProfileInfo pi = new ProfileInfo(duration, startTime, laststarttime); profileInfo.add(pi); laststarttime = startTime; if (profileInfo.size() >= 50) { ExecutionTimeWriter executionTimeWriter = new ExecutionTimeWriter(); executionTimeWriter.setCodeletName(name); executionTimeWriter.setPath("profile/"); executionTimeWriter.setProfileInfo(profileInfo); Thread thread = new Thread(executionTimeWriter); thread.start(); profileInfo = new ArrayList<>(); } } } } } }
26,149
26.154725
156
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/CodeletContainer.java
package br.unicamp.cst.core.entities; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class CodeletContainer implements Memory { private HashMap<String, List<Memory>> mapInputs = new HashMap<String, List<Memory>>(); private HashMap<String, List<Memory>> mapOutputs = new HashMap<String, List<Memory>>(); private HashMap<String, List<Memory>> mapBroadcast = new HashMap<String, List<Memory>>(); /** * Output memories, the ones that are written. */ protected List<Memory> outputs = new ArrayList<Memory>(); /** * Input memories, the ones that were broadcasted. */ private List<Memory> broadcast = new ArrayList<Memory>(); /** * Input memories, the ones that are read. */ protected List<Memory> inputs = new ArrayList<Memory>(); private ArrayList<Codelet> codelets; /** * Type of the codelet container */ private String name; public CodeletContainer() { super(); this.codelets = new ArrayList<>(); } public CodeletContainer(ArrayList<Codelet> codelets, boolean isToStartCodelets) { super(); this.codelets = new ArrayList<Codelet>(); codelets.forEach((codelet) -> { this.addCodelet(codelet, isToStartCodelets); }); } /** * Gets this Codelet activation. * * @return the activation */ public synchronized double getActivation() { double maxActivation = 0.0d; for (Codelet codelet : codelets) { double codeletActivation = codelet.getActivation(); if (codeletActivation >= maxActivation) { maxActivation = codeletActivation; } } return maxActivation; } /** * Gets the input memories list. * * @return the inputs. */ public synchronized List<Memory> getInputs() { return inputs; } /** * Sets the input memories list. * * @param inputs * the inputs to set. */ public synchronized void setInputs(List<Memory> inputs) { for (Map.Entry<String, List<Memory>> set : this.mapInputs.entrySet()) { set.setValue(inputs); } this.inputs = inputs; } /** * Gets the list of broadcast memories. * * @return the broadcast. */ public synchronized List<Memory> getBroadcast() { return broadcast; } /** * Sets the list of broadcast memories. * * @param broadcast * the broadcast to set. */ public synchronized void setBroadcast(List<Memory> broadcast) { for (Map.Entry<String, List<Memory>> set : this.mapBroadcast.entrySet()) { set.setValue(broadcast); } this.broadcast = broadcast; } public void addCodelet(Codelet codelet, boolean isToStartCodelet) { List<Memory> addedInputs = new ArrayList<Memory>(codelet.inputs); //add the inputs from added codelet to the list of inputs from container which all of its codelets share inputs.addAll(addedInputs); codelet.setInputs(inputs); //keep track of each codelets inputs, so it can removed when needed mapInputs.put(codelet.name, addedInputs); //same logic from inputs List<Memory> addedBroadcasts = new ArrayList<Memory>(codelet.broadcast); broadcast.addAll(addedBroadcasts); codelet.setBroadcast(broadcast); mapBroadcast.put(codelet.name, addedBroadcasts); //same logic from inputs List<Memory> addedOutputs = new ArrayList<Memory>(codelet.outputs); outputs.addAll(addedOutputs); codelet.setOutputs(outputs); mapOutputs.put(codelet.name, addedOutputs); this.codelets.add(codelet); if (isToStartCodelet) { codelet.start(); } } public void removeCodelet(Codelet codelet) { this.codelets.remove(codelet); List<Memory> inputsToRemoveFromEachCodelet = mapInputs.get(codelet.name); inputs.removeAll(inputsToRemoveFromEachCodelet); mapInputs.remove(codelet.name); List<Memory> broadcastsToRemoveFromEachCodelet = mapBroadcast.get(codelet.name); broadcast.removeAll(broadcastsToRemoveFromEachCodelet); mapBroadcast.remove(codelet.name); List<Memory> outputsToRemoveFromEachCodelet = mapOutputs.get(codelet.name); outputs.removeAll(outputsToRemoveFromEachCodelet); mapOutputs.remove(codelet.name); this.codelets.remove(codelet); } @Override public Object getI() { Object I = null; double maxActivation = 0.0d; for (Codelet codelet : codelets) { double codeletActivation = codelet.getActivation(); if (codeletActivation >= maxActivation) { maxActivation = codeletActivation; I = codelet; } } return I; } @Override public int setI(Object info) { for (Codelet codelet : codelets) { for (Memory memoryInput : codelet.inputs) { memoryInput.setI(info); } } return -1; } /** * Gets the greatest evaluation of the codelet with the greatest activation * * @return the greatest evaluation of the memories in codelet with the greatest activation. */ @Override public synchronized Double getEvaluation() { Double maxInputEvaluation = 0.0d; Double maxBroadcastEvaluation = 0.0d; double maxActivation = 0.0d; Codelet codeletMaxActivation = null; for (Codelet codelet : codelets) { double codeletActivation = codelet.getActivation(); if (codeletActivation >= maxActivation) { maxActivation = codeletActivation; codeletMaxActivation = codelet; } } if (codeletMaxActivation != null) { for (Memory memory : codeletMaxActivation.inputs) { double memoryEval = memory.getEvaluation(); if (memoryEval >= maxInputEvaluation) maxInputEvaluation = memoryEval; } for (Memory memory : codeletMaxActivation.broadcast) { double memoryEval = memory.getEvaluation(); if (memoryEval >= maxBroadcastEvaluation) maxBroadcastEvaluation = memoryEval; } } return maxInputEvaluation > maxBroadcastEvaluation ? maxInputEvaluation : maxBroadcastEvaluation; } @Override public String getName() { return name; } @Override public void setType(String type) { this.name = type; } @Override public void setName(String name) { this.name = name; } @Override public synchronized void setEvaluation(Double eval) { for (Memory memory : inputs) { memory.setEvaluation(eval); } } @Override public Long getTimestamp() { Double maxInputEvaluation = 0.0d; Double maxBroadcastEvaluation = 0.0d; double maxActivation = 0.0d; Codelet codeletMaxActivation = null; Long timestampInput = null; Long timestampBroadcast = null; for (Codelet codelet : codelets) { double codeletActivation = codelet.getActivation(); if (codeletActivation >= maxActivation) { maxActivation = codeletActivation; codeletMaxActivation = codelet; } } if (codeletMaxActivation != null) { for (Memory memory : codeletMaxActivation.inputs) { double memoryEval = memory.getEvaluation(); if (memoryEval >= maxInputEvaluation) { maxInputEvaluation = memoryEval; timestampInput = memory.getTimestamp(); } } for (Memory memory : codeletMaxActivation.broadcast) { double memoryEval = memory.getEvaluation(); if (memoryEval >= maxBroadcastEvaluation) { maxBroadcastEvaluation = memoryEval; timestampBroadcast = memory.getTimestamp(); } } } return maxBroadcastEvaluation > maxInputEvaluation ? timestampBroadcast : timestampInput; } @Override public void addMemoryObserver(MemoryObserver memoryObserver) { for (Codelet codelet : codelets) { for (Memory memory : codelet.inputs) { memory.addMemoryObserver(memoryObserver); } for (Memory memory : codelet.broadcast) { memory.addMemoryObserver(memoryObserver); } } } @Override public void removeMemoryObserver(MemoryObserver memoryObserver) { for (Codelet codelet : codelets) { for (Memory memory : codelet.inputs) { memory.removeMemoryObserver(memoryObserver); } for (Memory memory : codelet.broadcast) { memory.removeMemoryObserver(memoryObserver); } } } public synchronized List<Memory> getOutputs() { return outputs; } /** * Sets the list of output memories. * * @param outputs * the outputs to set. */ public synchronized void setOutputs(List<Memory> outputs) { for (Map.Entry<String, List<Memory>> set : this.mapOutputs.entrySet()) { set.setValue(outputs); } this.outputs = outputs; } public List<Codelet> getAll() { return codelets; } public Codelet getCodelet(String name) { Codelet selectedCodelet = null; for (Codelet codelet : codelets) { if (codelet.name.equals(name)) { selectedCodelet = codelet; break; } } return selectedCodelet; } }
8,546
21.914209
106
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/DeadLockDetector.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.core.entities; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; /** * This codelet detects deadlocks in the system and warns the user about it. * * @author K. Raizer * */ public class DeadLockDetector implements Runnable { private int ddRefreshPeriod = 1000; private boolean shouldLoop = true; /** * Creates a DeadLockDetector. * * @param ddRefreshPeriod * the refresh period of detection. */ public DeadLockDetector(int ddRefreshPeriod) { this.ddRefreshPeriod = ddRefreshPeriod; } /** * Creates a DeadLockDetector. */ public DeadLockDetector() { } @Override public void run() { do { ThreadMXBean tmx = ManagementFactory.getThreadMXBean(); long[] ids = tmx.findDeadlockedThreads(); if (ids != null) { ThreadInfo[] infos = tmx.getThreadInfo(ids, true, true); System.out.println("The following threads are deadlocked: "); for (ThreadInfo ti : infos) { System.out.println(ti); } } try { Thread.currentThread().sleep(this.ddRefreshPeriod); } catch (InterruptedException e) { e.printStackTrace(); } } while (shouldLoop); } /** * Starts the DeadLockDetector. */ public void start() { this.shouldLoop = true; new Thread(this).start(); } /** * Stops the DeadLockDetector. */ public synchronized void stop() { this.shouldLoop = false; } /** * Gets the detector refresh period. * * @return the ddRefreshPeriod. */ public int getDdRefreshPeriod() { return ddRefreshPeriod; } /** * Sets the detector refresh period. * * @param ddRefreshPeriod * the ddRefreshPeriod to set. */ public void setDdRefreshPeriod(int ddRefreshPeriod) { this.ddRefreshPeriod = ddRefreshPeriod; } }
2,386
22.87
82
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/Memory.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.core.entities; /** * This class represents the interface for all kinds of memories that exist in * CST. In order to be recognized as a Memory, an entity must implement this * interface. Currently, there are to kinds of Memory: MemoryObject and * MemoryContainer. However, other forms of Memory might come up as CST * develops. * * @author A. L. O. Paraense * @see MemoryObject * @see MemoryContainer * */ public interface Memory { /** * Gets the info inside this memory. * * @return the info in memory. */ Object getI(); /** * Sets the info inside this Memory. * * @param info * the updated info to set in memory. * @return index of the memory inside the container or -1 if not a * container. */ int setI(Object info); /** * Gets the evaluation of this memory. * * @return the evaluation of this memory. */ Double getEvaluation(); /** * Gets the type of this memory. * * @return the type of the memory. */ String getName(); /** * Sets the type of this memory. * * @param type the value to be set as type. */ @Deprecated void setType(String type); /** * Sets the type of this memory. * * @param name the value to be set as name. */ void setName(String name); /** * Sets the evaluation of this memory. * * @param eval * the value to be set as evaluation. */ void setEvaluation(Double eval); /** * Gets the timestamp of this Memory. * * @return the timestamp of this Memory. */ public Long getTimestamp(); /** * Add a memory observer to its list * @param memoryObserver MemoryObserver to be added */ public void addMemoryObserver(MemoryObserver memoryObserver); /** * Remove a memory observer from its list * @param memoryObserver MemoryObserver to be removed */ public void removeMemoryObserver(MemoryObserver memoryObserver); }
2,520
23.475728
82
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/MemoryBuffer.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.core.entities; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * MemoryBuffer is a generic holder for memory objects. It may be used to * produce sensory buffers, action buffers or other very short term memory * structures. * * @author K. Raizer */ public class MemoryBuffer { /** A memory buffer is essentially a fifo list of MO */ private ArrayList<MemoryObject> memoryObjects; private int maxCapacity; /** Safe lock for multithread access */ public volatile Lock lock = new ReentrantLock(); private RawMemory rawMemory; /** * Safe access through reentrant locks. * * @param accessing * the accessing Codelet * @return true if it is impeding access */ public boolean impendingAccess(Codelet accessing) { Boolean myLock = false; Boolean yourLock = false; try { myLock = lock.tryLock(); yourLock = accessing.lock.tryLock(); } finally { if (!(myLock && yourLock)) { if (myLock) { lock.unlock(); } if (yourLock) { accessing.lock.unlock(); } } } return myLock && yourLock; } /** * Creates a MemoryBuffer. * * @param maxCapacity * maximum number of elements this buffer holds at a given time. * @param rawMemory * singleton instance of the system's raw memory. */ public MemoryBuffer(int maxCapacity, RawMemory rawMemory) { memoryObjects = new ArrayList<MemoryObject>(); this.maxCapacity = maxCapacity; this.rawMemory = rawMemory; } /** * Adds a list of memory objects. * * @param contents * list of Memory Objects to be added */ public synchronized void putList(List<MemoryObject> contents) { for (MemoryObject thisContent : contents) { if (memoryObjects.size() == maxCapacity) { memoryObjects.remove(0); // Gets rid of older content } memoryObjects.add(thisContent); } } /** * Adds one memory object. * * @param content * one memory object to be added. */ public synchronized void put(MemoryObject content) { if (memoryObjects.size() == maxCapacity) { if (rawMemory != null) rawMemory.destroyMemoryObject(memoryObjects.get(0));// Gets rid // of older // content // and // deletes // it from // raw // memory memoryObjects.remove(0); } memoryObjects.add(content); } /** * Returns the original list of memory objects in this buffer. * * @return the list of Memory objects inside Buffer. */ public synchronized List<MemoryObject> get() { return memoryObjects; } /** * Returns a copy of the list of memory objects in this buffer. * * @return the list of Memory objects inside Buffer. */ public synchronized ArrayList<MemoryObject> getAll() { ArrayList<MemoryObject> all = new ArrayList<MemoryObject>(); all.addAll(this.memoryObjects); return memoryObjects; } /** * Pops the first memory object that went into this list. * * @return the first memory object that went into this list. */ public synchronized MemoryObject pop() { MemoryObject mo = memoryObjects.get(0); memoryObjects.remove(0); return mo; } /** * Gets the size of the list of Memory objects inside Buffer. * * @return size of the list of Memory objects inside Buffer. */ public synchronized int size() { return memoryObjects.size(); } /** * Gets the most recent Memory Object of this type. * * @return the most recent Memory Object of this type. */ public synchronized MemoryObject getMostRecent() { MemoryObject mostRecent; if (memoryObjects.size() > 0) { mostRecent = memoryObjects.get(memoryObjects.size() - 1); } else { mostRecent = null; } return mostRecent; } /** * Gets the oldest MemoryObject in this list. * * @return the oldest MemoryObject in this list. */ public synchronized MemoryObject getOldest() { MemoryObject oldest; if (memoryObjects.size() > 0) { oldest = memoryObjects.get(0); } else { oldest = null; } return oldest; } /** * Removes this memory object from this buffer and eliminates it from raw * memory. * * @param mo * memory object to be removed. * @return result of of the removal process. */ public synchronized boolean remove(MemoryObject mo) { if (rawMemory != null) rawMemory.destroyMemoryObject(mo);// removes this mo form RawMemory return memoryObjects.remove(mo);// removes this mo from this buffer; } /** * Clears all memory objects from this buffer. */ public synchronized void clear() { if (rawMemory != null) for (int i = 0; i < memoryObjects.size(); i++) { rawMemory.destroyMemoryObject(memoryObjects.get(i)); } memoryObjects.clear(); } /** * Prints the status of the Buffer. */ public synchronized void printStatus() { System.out.println("###### Memory Buffer ########"); System.out.println("# Content: " + this.get()); System.out.println("# Size: " + this.get().size()); System.out.println("###############################"); } }
5,763
23.423729
82
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/MemoryContainer.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.core.entities; import java.util.ArrayList; import java.util.Optional; import java.util.Random; import java.util.function.BinaryOperator; import java.util.function.Predicate; import java.util.logging.Level; import java.util.logging.Logger; /** * This class represents a Memory Container. The Memory Container is responsible * for implementing an important element in the Dynamic Subsumption mechanism * used in CST. All the Memory Objects in a Container are of the same type, and * hold the same parameters. The only differences among them are that they were * generated by a different codelet, and they might have different evaluations. * An evaluation is an inner parameter from any Memory Object, which holds a * value (usually a real value between 0 and 1) that measures a relative * importance given by the codelet, and which is used by the Evaluation codelet * within the Container to decide which from all input Memory Objects will be * sent to the output. * * @author A. L. O. Paraense * @see Memory * @see MemoryObject */ public class MemoryContainer implements Memory { private volatile ArrayList<Memory> memories; /** * Type of the memory container */ private String name; public enum Policy {MAX, MIN, RANDOM_FLAT, RANDOM_PROPORTIONAL, ITERATE}; /** * Policy used for selecting a MemoryObject at the MemoryContainer */ private Policy policy; private Memory last; private int lasti=0; private Random rand = new Random(); /** * Creates a MemoryContainer. */ public MemoryContainer() { memories = new ArrayList<>(); policy = Policy.MAX; } /** * Creates a MemoryContainer. * * @param type the type of the memories inside the container. */ public MemoryContainer(String type) { memories = new ArrayList<>(); policy = Policy.MAX; this.name = type; } /** * Sets the type of the memories inside the container. * * @param name the type of the memories inside the container. */ @Deprecated public synchronized void setType(String name) { this.name = name; } /** * Sets the name of the container. * * @param name the type of the memories inside the container. */ public synchronized void setName(String name) { this.name = name; } /** * Gets the info of the memory which has the greatest evaluation. * * @return the info of the memory which has the greatest evaluation. */ private synchronized Object getIMax() { double maxEval = Double.NEGATIVE_INFINITY; Memory mlast = null; ArrayList<Memory> allmax = new ArrayList<>(); for (Memory memory : memories) { double memoryEval = memory.getEvaluation(); if (memoryEval > maxEval) { maxEval = memoryEval; mlast = memory; allmax = new ArrayList<>(); allmax.add(memory); } else if (memoryEval == maxEval) { allmax.add(memory); } } if (allmax.size() > 1) { int i = rand.nextInt(allmax.size()); last = allmax.get(i); return(last.getI()); } else { if (mlast == null) return null; last = mlast; return last.getI(); } } /** * Gets the info of the memory which has the smallest evaluation. * * @return the info of the memory which has the smallest evaluation. */ private synchronized Object getIMin() { double minEval = Double.MAX_VALUE; Memory mlast=null; ArrayList<Memory> allmin = new ArrayList<>(); for (Memory memory : memories) { double memoryEval = memory.getEvaluation(); if (memoryEval < minEval) { minEval = memoryEval; mlast = memory; allmin = new ArrayList<>(); allmin.add(memory); } else if (memoryEval == minEval) { allmin.add(memory); } } if (allmin.size() > 1) { int i = rand.nextInt(allmin.size()); last = allmin.get(i); return(last.getI()); } else { if (mlast == null) return null; last = mlast; return last.getI(); } } /** * Gets the info of a random memory from within the MemoryContainer. * * @return the info of a random memory within the MemoryContainer */ private synchronized Object getIRandomFlat() { int i = rand.nextInt(memories.size()); last = memories.get(i); return(last.getI()); } /** * Gets the info of a random memory from within the MemoryContainer. * * @return the info of a random memory within the MemoryContainer */ private synchronized Object getIRandomProportional() { if (memories.size() == 0) return null; double indexfrom[] = new double[memories.size()]; double indexto[] = new double[memories.size()]; int i = 0; for (Memory memory : memories) { if (i == 0) indexfrom[i] = 0; else indexfrom[i] = indexto[i-1]; double interval = memory.getEvaluation(); indexto[i] = indexfrom[i] + interval; i++; } double llast = indexto[i-1]; double wheel = rand.nextDouble(); if (llast*wheel == 0) return(getIRandomFlat()); for (int j=0;j<=memories.size();j++) if (indexfrom[j] < wheel*llast && wheel*llast < indexto[j]) { last = memories.get(j); return(last.getI()); } last = memories.get(0); return(last.getI()); } /** * Gets the info of a random memory from within the MemoryContainer. * * @return the info of a random memory within the MemoryContainer */ private synchronized Object getIIterate() { if (memories.size() > 0 && lasti < memories.size()) { last = memories.get(lasti); lasti++; if (lasti > memories.size()-1) lasti = 0; return (last.getI()); } Logger.getAnonymousLogger().log(Level.INFO,"This MemoryContainer still does not have any internal Memories ..."); return null; } /** * Gets the info of the memory according to the specified MemoryContainer policy * Available policies: * Policy.MAX * Policy.MIN * Policy.RANDOM_FLAT * Policy.RANDOM_PROPORTIONAL * Policy.ITERATE * * @return the info of the memory according to the specified MemoryContainer policy */ @Override public synchronized Object getI() { switch(policy) { case MAX: return getIMax(); case MIN: return getIMin(); case RANDOM_FLAT: return getIRandomFlat(); case RANDOM_PROPORTIONAL: return getIRandomProportional(); case ITERATE: return getIIterate(); default: return getIMax(); } } /** * Gets the last info returned while a getI() was issued * @return the info object last returned by a getI() */ public synchronized Object getLastI() { return last.getI(); } /** * Gets the last Memory from inside the container, while a getI() was issued * @return the last Memory accessed by a getI() */ public synchronized Memory getLast() { return last; } /** * Gets the info of the memory which has the index passed. * * @param index the index of the memory whose info is searched. * @return the info of the memory which has the index passe or null is not * found. */ public synchronized Object getI(int index) { if (index >= 0 && index < memories.size()) { return (memories.get(index).getI()); } else { Logger.getAnonymousLogger().log(Level.INFO, "Index for the {0}.getI(index) method greater than the number of MemoryObjects within the MemoryContainer -> {1}", new Object[]{getName(), index}); return (null); } } /** * Gets the info of the memory which has the name passed. * * @param name the name of the memory whose info is searched. * @return the info of the memory which has the name passed or null if it is not * found. */ public synchronized Object getI(String name) { for (Memory m : memories) { if (m.getName().equals(name)) return (m.getI()); } Logger.getAnonymousLogger().log(Level.INFO, "There is no Memory with the name {0} within the Container {1}", new Object[]{name, this.name}); return (null); } /** * Gets the info of the memory filtered by the predicate. * * @param predicate the predicate to be used to filter the stream. * @return the info of the memory or null if not found. */ public synchronized Object getI(Predicate<Memory> predicate) { Object object = null; if (memories != null && memories.size() > 0) { Optional<Memory> optional = memories.stream().filter(predicate).findFirst(); if (optional.isPresent()) {// Check whether optional has element you // are looking for Memory memory = optional.get();// get it from optional object = memory.getI(); } } return object; } /** * Gets the info of the memory reduced by the binary operator passed. * * @param accumulator the binary operator. * @return the info of the memory or null if not found. */ public synchronized Object getI(BinaryOperator<Memory> accumulator) { Object object = null; if (memories != null && memories.size() > 0) { Optional<Memory> optional = memories.stream().reduce(accumulator); if (optional.isPresent()) {// Check whether optional has element you // are looking for Memory memory = optional.get();// get it from optional object = memory.getI(); } } return object; } /** * MemoryContainer inserts the info as a new MemoryObject in its Memory list. */ @Override public synchronized int setI(Object info) { return setI(info, -1.0d); } /** * Creates a Memory Object with the info and the evaluation passed. * * @param info the info of the new Memory Object. * @param evaluation the evaluation of the new Memory Object. * @return the index of the new Memory Object. */ public synchronized int setI(Object info, Double evaluation) { MemoryObject mo = new MemoryObject(); mo.setI(info); if (evaluation != -1.0) mo.setEvaluation(evaluation); mo.setName(""); last = mo; memories.add(mo); return memories.indexOf(mo); } /** * Sets the info of the Memory with the index passed. * * @param info the information to be set in the * @param index the index of the memory inside the container. */ public synchronized void setI(Object info, int index) { if (memories != null && memories.size() > index) { Memory memory = memories.get(index); if (memory != null) { last = memory; if (memory instanceof MemoryObject) { memory.setI(info); } else if (memory instanceof MemoryContainer) { ((MemoryContainer) memory).setI(info, index); } } } } /** * Sets the info and the evaluation of the memory with the index passed inside * this container. * * @param info the information to be set in the. * @param index the index of the memory inside this container. * @param evaluation the evaluation to be set. */ public synchronized void setI(Object info, Double evaluation, int index) { if (memories != null && memories.size() > index) { Memory memory = memories.get(index); if (memory != null) { last = memory; if (memory instanceof MemoryObject) { memory.setI(info); memory.setEvaluation(evaluation); } else if (memory instanceof MemoryContainer) { ((MemoryContainer) memory).setI(info, evaluation, index); } } } } /** * Sets the info as the info and an evaluation passed to a Memory of the type * passed. * * @param info the info. * @param evaluation the evaluation to set. * @param type the type of the Memory * @return the index of the memory */ public synchronized int setI(Object info, double evaluation, String type) { int index = -1; if (memories != null) { boolean set = false; for (int i = 0; i < memories.size(); i++) { Memory memory = memories.get(i); if (memory != null && memory instanceof MemoryObject) { MemoryObject memoryObject = (MemoryObject) memory; if (memoryObject.getName().equalsIgnoreCase(type)) { memory.setI(info); memory.setEvaluation(evaluation); index = i; set = true; last = memory; break; } } } if (!set) { MemoryObject mo = new MemoryObject(); mo.setI(info); mo.setEvaluation(evaluation); mo.setName(type); last = mo; memories.add(mo); index = memories.indexOf(mo); } } return index; } /** * Gets the evaluation of the last memory accessed with getI * * @return the evaluation of the last memory accessed with getI. */ @Override public synchronized Double getEvaluation() { if (last != null) { return last.getEvaluation(); } else return null; } /** * Gets the evaluation of a specific Memory at the MemoryContainer * * @return the evaluation of a specific Memory at the MemoryContainer */ public synchronized Double getEvaluation(int index) { if (memories != null && memories.size() > index) { Memory memory = memories.get(index); if (memory != null) { return(memory.getEvaluation()); } } return null; } /** * Gets the type of the memory which has the greatest evaluation. * * @return the type of the memory which has the greatest evaluation. */ @Override public synchronized String getName() { return name; } /** * Sets the evaluation of the last memory accessed with getI or setI * * @param eval the evaluation to set. */ @Override public synchronized void setEvaluation(Double eval) { if (last != null && last instanceof Memory) { last.setEvaluation(eval); } else Logger.getAnonymousLogger().log(Level.INFO,"This MemoryContainer still does not have any internal Memories ..."); } /** * Sets the evaluation of the a specific memory from the MemoryContainer * * @param eval the evaluation to set. * @param index the index of the memory inside this container. */ public synchronized void setEvaluation(Double eval, int index) { if (memories != null && memories.size() > index) { Memory memory = memories.get(index); if (memory != null) { if (memory instanceof MemoryObject) { memory.setEvaluation(eval); } else if (memory instanceof MemoryContainer) { ((MemoryContainer) memory).setEvaluation(eval, index); } } } } /** * Adds a memory to this container. * * @param memory the memory to be added in this container * @return the index of the added memory */ public synchronized int add(Memory memory) { int index = -1; if (memory != null) { memories.add(memory); index = memories.indexOf(memory); } return index; } // /** // * Sets the Java String info as the info and an evaluation passed to a // * Memory of the type passed. // * // * @param info // * Java String info. // * @param evaluation // * the evaluation to set. // * @param type // * the type of the Memory // * @return the index of the memory // */ // public synchronized int setI(String info, double evaluation, String type) { // int index = -1; // if (memories != null) { // boolean set = false; // for (int i = 0; i < memories.size(); i++) { // Memory memory = memories.get(i); // if (memory != null && memory instanceof MemoryObject) { // MemoryObject memoryObject = (MemoryObject) memory; // if (memoryObject.getName().equalsIgnoreCase(type)) { // memory.setI(info); // memory.setEvaluation(evaluation); // index = i; // set = true; // break; // } // } // } // if (!set) { // MemoryObject mo = new MemoryObject(); // mo.setI(info); // mo.setEvaluation(evaluation); // mo.setType(type); // memories.add(mo); // index = memories.indexOf(mo); // } // } // return index; // } /** * Gets all the memories inside this container. * * @return all the memories inside this container. */ public synchronized ArrayList<Memory> getAllMemories() { return memories; } /** * Gets a specific memory from inside the container. * * @param i the specific memory to be returned * @return the specified memory */ public synchronized Memory get(int i) { if (i >= 0 && i < memories.size()) { return memories.get(i); } else return null; } /** * Gets the internal memory which has the name passed. * * @param name the name of the memory whose info is searched. * @return the memory which has the name passed or null if it is not found. */ public synchronized Memory getInternalMemory(String name) { for (Memory m : memories) { if (m.getName().equals(name)) return (m); } return (null); } /** * Get the TimeStamp of the last returned Memory. * * @return the timestamp in Long format */ public synchronized Long getTimestamp() { if (last != null) { return(last.getTimestamp()); } else { Logger.getAnonymousLogger().log(Level.INFO, "This MemoryContainer still does not have any internal Memories ..."); return null; } } /** * Get the TimeStamp of a specific index inside the MemoryContainer. * * @return the timestamp in Long format */ public synchronized Long getTimestamp(int index) { if (memories != null && memories.size() > index) { Memory memory = memories.get(index); if (memory != null) { return(memory.getTimestamp()); } } return(null); } /** * Adds a new MemoryObserver for the current Container * @param memoryObserver the observer to be added */ @Override public void addMemoryObserver(MemoryObserver memoryObserver) { for (Memory memory : memories) { memory.addMemoryObserver(memoryObserver); } } /** * Removes a MemoryObserver from the current Container list * @param memoryObserver the observer to be removed */ @Override public void removeMemoryObserver(MemoryObserver memoryObserver) { for (Memory memory : memories) { memory.removeMemoryObserver(memoryObserver); } } /** * Sets a new Policy for selecting an info with getI() * @param pol the new Policy to be used */ public void setPolicy(Policy pol) { policy = pol; } /** * Returns the current Policy being used for selecting an info, when a getI() is called * @return the current Policy actually in use */ public Policy getPolicy() { return policy; } }
20,951
29.017192
211
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/MemoryObject.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.core.entities; import java.io.Serializable; import java.util.HashSet; import java.util.Set; /** * A Memory Object is a generic information holder, acting as a sign or an * internal representation, which is responsible to store any auxiliary or * perennial information necessary for the cognitive architecture to perform its * behavior. Codelets and Memory Objects are intrinsically coupled to each * other, in the sense that Memory Objects hold the information necessary for * the Codelets to run, and are also the placeholders of any new information * generated by the codelet. The main property being hold by a Memory Object is * its Information (I). This information can be simply a number, or hold complex * structures like lists, trees, graphs or whole networks. In our computational * implementation, the information I is a generic Java Object, which can be used * to represent virtually anything. A Memory Object also has two extra kinds of * meta-information: a time stamp (T), which tags the Memory Object with a * marker indicating its last update, and an evaluation (E), which has many * different uses within CST. This evaluation is simply a number, which can be * used, e.g. as an appraisal factor in an emotional module, or simply as a * discriminator to differentiate among two or more Memory Objects of the same * type. These meta-information can be simply ignored by simpler codelets, or be * useful while implementing more sophisticated cognitive models. * * @author A. L. O. Paraense * @author K. Raizer */ public class MemoryObject implements Memory, Serializable { private static final long serialVersionUID = 1L; private Long idmemoryobject; /** * Date when the data was "created" in milliseconds */ private Long timestamp; /** * An evaluation of this memory object based on inner references */ private volatile Double evaluation; /** * Information contained in the memory object. */ private volatile Object I; /** * Type of the memory object */ private String name; /** * List of codetlets that observes memory */ private transient Set<MemoryObserver> memoryObservers; /** * Creates a MemoryObject. */ public MemoryObject() { evaluation = 0.0d; } /** * Gets the id of the Memory Object. * * @return the id of the Memory Object. */ public synchronized Long getIdmemoryobject() { return this.idmemoryobject; } /** * Sets the id of the Memory Object. * * @param idmemoryobject * the id of the Memory Object to set. */ public synchronized void setIdmemoryobject(Long idmemoryobject) { this.idmemoryobject = idmemoryobject; } /** * Gets the info of the Memory Object. * * @return the info of the Memory Object. */ public synchronized Object getI() { return this.I; } /** * Sets the info in memory object. * * @param info * the info in memory object to set. */ public synchronized int setI(Object info) { this.I = info; setTimestamp(System.currentTimeMillis()); notifyMemoryObservers(); return -1; } private synchronized void notifyMemoryObservers() { if (memoryObservers != null && !memoryObservers.isEmpty()) { for (MemoryObserver memoryObserver : memoryObservers) { memoryObserver.notifyCodelet(); } } } /** * This method is deprecated after v0.1. For the time being, it has been * kept only for backward compatibility. Use the {@link #setI(Object info) * setI} method instead. * * @deprecated use {@link #setI(Object info)} instead. * * @param info * the info in memory object to set. */ @Deprecated public synchronized void updateI(Object info) { setI(info); } /** * Gets the timestamp of this Memory Object. * * @return the timestamp of this Memory Object. */ public synchronized Long getTimestamp() { return this.timestamp; } /** * Sets the timestamp of this Memory Object. * * @param timestamp * the timestamp of this Memory Object. */ public synchronized void setTimestamp(Long timestamp) { this.timestamp = timestamp; } /** * Gets the type of the memory. * * @return the type */ public synchronized String getName() { return name; } /** * Sets the type of the memory. * * @param name * the type to set. */ @Deprecated public synchronized void setType(String name) { this.name = name; } /** * Sets the name of the memory. * * @param name * the type to set. */ public synchronized void setName(String name) { this.name = name; } /** * Gets the evaluation of the Memory Object. * * @return the evaluation of the Memory Object. */ public synchronized Double getEvaluation() { return evaluation; } /** * Sets the evaluation of the Memory Object. * * @param evaluation * the evaluation to set. */ public synchronized void setEvaluation(Double evaluation) { this.evaluation = evaluation; } @Override public String toString() { return "MemoryObject [idmemoryobject=" + idmemoryobject + ", timestamp=" + timestamp + ", evaluation=" + evaluation + ", I=" + I + ", name=" + name + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((I == null) ? 0 : I.hashCode()); result = prime * result + ((evaluation == null) ? 0 : evaluation.hashCode()); result = prime * result + ((idmemoryobject == null) ? 0 : idmemoryobject.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((timestamp == null) ? 0 : timestamp.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MemoryObject other = (MemoryObject) obj; if (I == null) { if (other.I != null) return false; } else if (!I.equals(other.I)) return false; if (evaluation == null) { if (other.evaluation != null) return false; } else if (!evaluation.equals(other.evaluation)) return false; if (idmemoryobject == null) { if (other.idmemoryobject != null) return false; } else if (!idmemoryobject.equals(other.idmemoryobject)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (timestamp == null) { if (other.timestamp != null) return false; } else if (!timestamp.equals(other.timestamp)) return false; return true; } /** * Add a memory observer to its list * @param memoryObserver the MemoryObserve to be added */ public void addMemoryObserver(MemoryObserver memoryObserver) { if (this.memoryObservers == null) { this.memoryObservers = new HashSet<MemoryObserver>(); } this.memoryObservers.add(memoryObserver); } /** * Remove a memory observer from its list * @param memoryObserver the MemoryObserve to be removed */ public void removeMemoryObserver(MemoryObserver memoryObserver) { if (this.memoryObservers != null) { this.memoryObservers.remove(memoryObserver); } } }
7,825
25.986207
104
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/MemoryObserver.java
/******************************************************************************* * Copyright (c) 2021 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * A. L. O. Paraense, ******************************************************************************/ package br.unicamp.cst.core.entities; public interface MemoryObserver { public void notifyCodelet(); }
600
32.388889
80
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/Mind.java
/********************************************************************************************** * Copyright (c) 2012-2017 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation **********************************************************************************************/ package br.unicamp.cst.core.entities; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; /** * This class represents the Mind of the agent, wrapping all the CST's core * entities. * * @author A. L. O. Paraense * @author E. M. Froes */ public class Mind { protected CodeRack codeRack; protected RawMemory rawMemory; protected ConcurrentHashMap<String,ArrayList> codeletGroups; protected ConcurrentHashMap<String,ArrayList> memoryGroups; /** * Creates the Mind. */ public Mind() { codeRack = new CodeRack(); rawMemory = new RawMemory(); codeletGroups = new ConcurrentHashMap(); memoryGroups = new ConcurrentHashMap(); } /** * Gets the CodeRack. * * @return the codeRack. */ public synchronized CodeRack getCodeRack() { return codeRack; } /** * Gets the RawMemory. * * @return the rawMemory. */ public synchronized RawMemory getRawMemory() { return rawMemory; } /** * Creates a Codelet Group * * @param groupName The Group name * */ public synchronized void createCodeletGroup(String groupName) { ArrayList<Codelet> group = new ArrayList<Codelet>(); codeletGroups.put(groupName,group); } /** * Creates a Memory Group * * @param groupName The Group name * */ public synchronized void createMemoryGroup(String groupName) { ArrayList<Codelet> group = new ArrayList<Codelet>(); memoryGroups.put(groupName,group); } /** * Returns the full HashMap which for every codelet group Name it is associated a list of codeletGroups * * @return the HashMap with all pairs (groupname,list of codeletGroups belonging to groupname) */ public ConcurrentHashMap<String,ArrayList> getCodeletGroups() { return(codeletGroups); } /** * Returns the full HashMap which for every memory group Name it is associated a list of codeletGroups * * @return the HashMap with all pairs (groupname,list of codeletGroups belonging to groupname) */ public ConcurrentHashMap<String,ArrayList> getMemoryGroups() { return(memoryGroups); } /** * Returns the number of registered codelet groups * * @return the number of registered groups */ public int getCodeletGroupsNumber() { return(codeletGroups.size()); } /** * Returns the number of registered memory groups * * @return the number of registered groups */ public int getMemoryGroupsNumber() { return(memoryGroups.size()); } /** * Creates a Memory Container inside the Mind of a given type. * * @param name * the type of the Memory Container to be created inside the * Mind. * @return the Memory Container created. */ public synchronized MemoryContainer createMemoryContainer(String name) { MemoryContainer mc = null; if (rawMemory != null) mc = rawMemory.createMemoryContainer(name); return mc; } /** * Creates a new MemoryObject and adds it to the Raw Memory, using provided * info and type. * * @param name * memory object name. * @param hostname * hostname of the REST server * @param port * port of the REST server * @return mo created MemoryObject. */ public synchronized RESTMemory createRESTMemory(String name, String hostname, int port) { RESTMemory mo = null; if (rawMemory != null) mo = rawMemory.createRESTMemory(name, hostname, port); return mo; } /** * Creates a new MemoryObject and adds it to the Raw Memory, using provided * type. * * @param name * memory object type. * @param port * port of the REST server * @return created MemoryObject. */ public synchronized RESTMemory createRESTMemory(String name, int port) { return createRESTMemory(name, "localhost", port); } /** * Creates a new MemoryObject and adds it to the Raw Memory, using provided * info and type. * * @param name * memory object name. * @param hostname * hostname of the REST server * @param port * port of the REST server * @return mo created MemoryObject. */ public synchronized RESTMemoryContainer createRESTMemoryContainer(String name, String hostname, int port) { RESTMemoryContainer mo = null; if (rawMemory != null) mo = rawMemory.createRESTMemoryContainer(name, hostname, port); return mo; } /** * Creates a new MemoryObject and adds it to the Raw Memory, using provided * type. * * @param name * memory object type. * @param port * port of the REST server * @return created MemoryObject. */ public synchronized RESTMemoryContainer createRESTMemoryContainer(String name, int port) { return createRESTMemoryContainer(name, "localhost", port); } /** * Creates a new MemoryObject and adds it to the Raw Memory, using provided * info and type. * * @param name * memory object name. * @param info * memory object info. * @return mo created MemoryObject. */ public synchronized MemoryObject createMemoryObject(String name, Object info) { MemoryObject mo = null; if (rawMemory != null) mo = rawMemory.createMemoryObject(name, info); return mo; } /** * Creates a new MemoryObject and adds it to the Raw Memory, using provided * type. * * @param name * memory object type. * @return created MemoryObject. */ public synchronized MemoryObject createMemoryObject(String name) { return createMemoryObject(name, null); } /** * Inserts the Codelet passed in the Mind's CodeRack. * * @param co * the Codelet passed * @return the Codelet. */ public Codelet insertCodelet(Codelet co) { if (codeRack != null) codeRack.addCodelet(co); return co; } /** * Inserts the Codelet passed in the Mind's CodeRack. * * @param co the Codelet to be inserted in the Mind * @param groupName the Codelet group name * @return the Codelet. */ public Codelet insertCodelet(Codelet co, String groupName) { insertCodelet(co); registerCodelet(co,groupName); return co; } /** * Register a Codelet within a group * * @param co the Codelet * @param groupName the group name */ public void registerCodelet(Codelet co, String groupName) { ArrayList<Codelet> groupList = codeletGroups.get(groupName); if (groupList != null) groupList.add(co); } /** * Register a Memory within a group * * @param m the Memory * @param groupName the group name */ public void registerMemory(Memory m, String groupName) { ArrayList<Memory> groupList = memoryGroups.get(groupName); if (groupList != null) groupList.add(m); } /** * Register a Memory within a group by name. * * @param m the Memory * @param groupName the group name */ public void registerMemory(String m, String groupName) { ArrayList<Memory> groupList = memoryGroups.get(groupName); RawMemory rm = getRawMemory(); if (groupList != null && rm != null) { List<Memory> all = rm.getAllOfType(m); for (Memory mem : all) { groupList.add(mem); } } } /** * Get a list of all Codelets belonging to a group * * @param groupName the group name to which the Codelets belong * @return A list of all codeletGroups belonging to the group indicated by groupName */ public ArrayList<Codelet> getCodeletGroupList(String groupName) { return(codeletGroups.get(groupName)); } /** * Get a list of all Memories belonging to a group * * @param groupName the group name to which the Memory belong * @return A list of all memoryGroups belonging to the group indicated by groupName */ public ArrayList<Memory> getMemoryGroupList(String groupName) { return(memoryGroups.get(groupName)); } /** * Starts all codeletGroups in coderack. */ public void start() { if (codeRack != null) codeRack.start(); } /** * Stops codeletGroups thread. */ public void shutDown() { if (codeRack != null) codeRack.shutDown(); } }
9,483
26.174785
111
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/Observer.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.core.entities; /** * @author Klaus Raizer * */ public interface Observer { public void update(String operation, String record); }
712
30
82
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/RESTMemory.java
package br.unicamp.cst.core.entities; import br.unicamp.cst.io.rest.MemoryJson; import br.unicamp.cst.support.InterfaceAdapter; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import express.Express; import express.middleware.CorsOptions; import express.middleware.Middleware; import java.util.HashSet; import java.util.Set; public class RESTMemory extends MemoryObject { long refresh = 0; // A refresh of 0 means that every call will generate a new probe in mind long lastaccess = 0; String lastmessage = ""; Memory internalMemory; public RESTMemory(int port) { this(port,false); } /** * * @param hostname hostname of the REST server * @param port the port to install the REST server */ public RESTMemory(String hostname, int port) { this(hostname, port,false); } /** * * @param port the port to install the REST server * @param pretty set this to true to generate pretty printing JSON in the REST server */ public RESTMemory(int port, boolean pretty) { this(port,pretty,"*"); } /** * @param hostname the hostname of the REST server * @param port the port to install the REST server * @param pretty set this to true to generate pretty printing JSON in the REST server */ public RESTMemory(String hostname, int port, boolean pretty) { this(hostname, port,pretty,"*", 0L); } /** * * @param port the port to install the REST server * @param pretty set this to true to generate pretty printing JSON in the REST server * @param origin a pattern for users allowed to access the server - use "*" to allow everyone */ public RESTMemory(int port, boolean pretty, String origin) { this("localhost", port,pretty,origin,0L); } /** * @param hostname the hostname of the REST server * @param port the port to install the REST server * @param pretty set this to true to generate pretty printing JSON in the REST server * @param origin a pattern for users allowed to access the server - use "*" to allow everyone * @param nrefresh the refresh period in milliseconds */ public RESTMemory(String hostname, int port, boolean pretty, String origin, long nrefresh) { refresh = nrefresh; Express app = new Express(hostname); Gson gson; if (pretty) gson = new GsonBuilder().registerTypeAdapter(Memory.class, new InterfaceAdapter<MemoryObject>()) .registerTypeAdapter(Memory.class, new InterfaceAdapter<MemoryContainer>()) .setPrettyPrinting().create(); else gson = new Gson(); CorsOptions corsOptions = new CorsOptions(); corsOptions.setOrigin(origin); app.use(Middleware.cors(corsOptions)); app.get("/", (req, res) -> { long currentaccess = System.currentTimeMillis(); long diff = currentaccess - lastaccess; if (diff > refresh) { MemoryJson myJson = new MemoryJson(this); lastmessage = gson.toJson(myJson); lastaccess = currentaccess; } res.send(lastmessage); }); app.post("/", (req, res) -> { // Will match every request which uses the 'POST' method and matches the /login' path long currentaccess = System.currentTimeMillis(); long diff = currentaccess - lastaccess; if (diff > refresh) { String I = req.getFormQuery("I"); double evaluation = Double.parseDouble(req.getFormQuery("evaluation")); // Process data this.setI(I); this.setEvaluation(evaluation); lastmessage = "I: " + I + ", Evaluation: " + evaluation; lastaccess = currentaccess; } res.send(lastmessage); }); app.listen(port); } }
4,003
34.75
108
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/RESTMemoryContainer.java
package br.unicamp.cst.core.entities; import br.unicamp.cst.io.rest.MemoryJson; import br.unicamp.cst.support.InterfaceAdapter; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import express.Express; import express.middleware.CorsOptions; import express.middleware.Middleware; public class RESTMemoryContainer extends MemoryContainer { long refresh = 0; // A refresh of 0 means that every call will generate a new probe in mind long lastaccess = 0; String lastmessage = ""; Memory internalMemory; public RESTMemoryContainer(int port) { this(port,false); } /** * * @param hostname hostname of the REST server * @param port the port to install the REST server */ public RESTMemoryContainer(String hostname, int port) { this(hostname, port,false); } /** * * @param port the port to install the REST server * @param pretty set this to true to generate pretty printing JSON in the REST server */ public RESTMemoryContainer(int port, boolean pretty) { this(port,pretty,"*"); } /** * @param hostname the hostname of the REST server * @param port the port to install the REST server * @param pretty set this to true to generate pretty printing JSON in the REST server */ public RESTMemoryContainer(String hostname, int port, boolean pretty) { this(hostname, port,pretty,"*", 0L); } /** * * @param port the port to install the REST server * @param pretty set this to true to generate pretty printing JSON in the REST server * @param origin a pattern for users allowed to access the server - use "*" to allow everyone */ public RESTMemoryContainer(int port, boolean pretty, String origin) { this("localhost", port,pretty,origin,0L); } /** * @param hostname the hostname of the REST server * @param port the port to install the REST server * @param pretty set this to true to generate pretty printing JSON in the REST server * @param origin a pattern for users allowed to access the server - use "*" to allow everyone * @param nrefresh the refresh period in milliseconds */ public RESTMemoryContainer(String hostname, int port, boolean pretty, String origin, long nrefresh) { refresh = nrefresh; Express app = new Express(hostname); Gson gson; if (pretty) gson = new GsonBuilder().registerTypeAdapter(Memory.class, new InterfaceAdapter<MemoryObject>()) .registerTypeAdapter(Memory.class, new InterfaceAdapter<MemoryContainer>()) .setPrettyPrinting().create(); else gson = new Gson(); CorsOptions corsOptions = new CorsOptions(); corsOptions.setOrigin(origin); app.use(Middleware.cors(corsOptions)); app.get("/", (req, res) -> { long currentaccess = System.currentTimeMillis(); long diff = currentaccess - lastaccess; if (diff > refresh) { MemoryJson myJson = new MemoryJson(this); lastmessage = gson.toJson(myJson); lastaccess = currentaccess; } res.send(lastmessage); }); app.post("/", (req, res) -> { // Will match every request which uses the 'POST' method and matches the /login' path long currentaccess = System.currentTimeMillis(); long diff = currentaccess - lastaccess; if (diff > refresh) { String I = req.getFormQuery("I"); double evaluation = Double.parseDouble(req.getFormQuery("evaluation")); // Process data this.setI(I); this.setEvaluation(evaluation); lastmessage = "I: " + I + ", Evaluation: " + evaluation; lastaccess = currentaccess; } res.send(lastmessage); }); app.listen(port); } }
4,020
35.889908
108
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/RawMemory.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.core.entities; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * * The Raw Memory contains all memories in the system. * * @author A. L. O. Paraense * @author K. Raizer * @see Memory * @see MemoryObject * @see MemoryContainer * */ public class RawMemory { /** * List of all memories in the system */ private List<Memory> allMemories; /** * Crates a Raw Memory. */ public RawMemory() { allMemories = Collections.synchronizedList(new ArrayList<Memory>()); } /** * Gets all memories inside the raw memory. * * @return the allMemoryObjects */ public synchronized List<Memory> getAllMemoryObjects() { synchronized (allMemories) { return allMemories; } } /** * Returns a list of all memories in raw memory of a given type * * @param type * of memory * @return list of Ms of a given type */ public synchronized List<Memory> getAllOfType(String type) { List<Memory> listOfType = new ArrayList<Memory>(); synchronized (allMemories) { for (Memory mo : this.allMemories) { if (mo.getName() != null){ if (mo.getName().equalsIgnoreCase(type)) { listOfType.add(mo); } } } } return listOfType; } /** * Sets the list of all memories inside raw memory. * * @param allMemories * the allMemoryObjects to set. */ public synchronized void setAllMemoryObjects(List<Memory> allMemories) { synchronized (this.allMemories) { this.allMemories = allMemories; } } /** * Print Raw Memory contents. */ public synchronized void printContent() { synchronized (allMemories) { for (Memory mo : allMemories) { System.out.println(mo.toString()); } } } /** * Adds a new Memory to the Raw Memory. * * @deprecated * @param mo * memory to be added. */ @Deprecated public synchronized void addMemoryObject(Memory mo) { synchronized (allMemories) { allMemories.add(mo); } } /** * Adds a new Memory to the Raw Memory. * * @param mo * memory to be added. */ public synchronized void addMemory(Memory mo) { synchronized (allMemories) { allMemories.add(mo); } } /** * Creates a memory container of the type passed. * * @param name * the type of the memory container passed. * @return the memory container created. */ public synchronized MemoryContainer createMemoryContainer(String name) { MemoryContainer mc = new MemoryContainer(name); this.addMemory(mc); return mc; } /** * Creates a new RestMemory and adds it to the Raw Memory, using provided * name, hostname and port . * * @param name * memory object type. * @param hostname * the hostname of the REST server * @param port * the port of the REST server * @return mo created MemoryObject. */ public synchronized RESTMemory createRESTMemory(String name, String hostname, int port) { // memory object to be added to rawmemory RESTMemory mo = new RESTMemory(hostname, port); //mo.setI(""); mo.setTimestamp(System.currentTimeMillis()); mo.setEvaluation(0.0d); mo.setName(name); // adding the new object to raw memory this.addMemory(mo); return mo; } /** * Creates a memory object of the type passed. * * @param name * the type of the memory object created. * @param port * the port of the REST server * @return the memory object created. */ public synchronized RESTMemory createRESTMemory(String name, int port) { return createRESTMemory(name, "localhost", port); } /** * Creates a new RestMemory and adds it to the Raw Memory, using provided * name, hostname and port . * * @param name * memory object type. * @param hostname * the hostname of the REST server * @param port * the port of the REST server * @return mo created MemoryObject. */ public synchronized RESTMemoryContainer createRESTMemoryContainer(String name, String hostname, int port) { // memory object to be added to rawmemory RESTMemoryContainer mo = new RESTMemoryContainer(hostname, port); //mo.setI(""); //mo.setTimestamp(System.currentTimeMillis()); mo.setEvaluation(0.0d); mo.setName(name); // adding the new object to raw memory this.addMemory(mo); return mo; } /** * Creates a memory object of the type passed. * * @param name * the type of the memory object created. * @param port * the port of the REST server * @return the memory object created. */ public synchronized RESTMemoryContainer createRESTMemoryContainer(String name, int port) { return createRESTMemoryContainer(name, "localhost", port); } /** * Creates a new MemoryObject and adds it to the Raw Memory, using provided * info and type. * * @param name * memory object type. * @param info * memory object info. * @return mo created MemoryObject. */ public synchronized MemoryObject createMemoryObject(String name, Object info) { // memory object to be added to rawmemory MemoryObject mo = new MemoryObject(); mo.setI(info); mo.setTimestamp(System.currentTimeMillis()); mo.setEvaluation(0.0d); mo.setName(name); // adding the new object to raw memory this.addMemory(mo); return mo; } /** * Creates a memory object of the type passed. * * @param name * the type of the memory object created. * @return the memory object created. */ public synchronized MemoryObject createMemoryObject(String name) { return createMemoryObject(name, ""); } /** * Destroys a given memory from raw memory * * @param mo * the memory to destroy. */ public synchronized void destroyMemoryObject(Memory mo) { synchronized (allMemories) { allMemories.remove(mo); } } /** * Gets the size of the raw memory. * * @return size of Raw Memory. */ public synchronized int size() { synchronized (allMemories) { return allMemories.size(); } } /** * Removes all memory objects from RawMemory. */ public void shutDown() { synchronized (allMemories) { allMemories = new ArrayList<Memory>(); } } }
6,768
22.422145
108
java
cst
cst-master/src/main/java/br/unicamp/cst/core/entities/Subject.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.core.entities; /** * @author Klaus Raizer * */ public interface Subject { /** * Registers a codelet's input or output list to receive notifications from working storage. * @param co Codelet * @param type Type of memory objects being observed * @param io Which list to register: 0 - input and 1 - output */ public void registerCodelet(Codelet co, String type, int io); /** * Removes a codelet's io from the subject registered list * @param co * @param type * @param io */ public void unregisterCodelet(Codelet co, String type, int io); public void notifyCodelets(); }
1,174
30.756757
94
java
cst
cst-master/src/main/java/br/unicamp/cst/core/exceptions/CodeletActivationBoundsException.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.core.exceptions; /** * This class represents a Java exception to be thrown when the codelet's * activation is set to more than 1.0 or less than 0.0. * * @author A. L. O. Paraense * @author K. Raizer * @see Exception * */ public class CodeletActivationBoundsException extends Exception { private static final long serialVersionUID = 6550752642966697942L; /** * Creates a CodeletActivationBoundsException. * * @param message * the exception message. */ public CodeletActivationBoundsException(String message) { super(message); } /** * Creates a CodeletActivationBoundsException. * * @param message * the exception message. * @param cause * the exception cause. */ public CodeletActivationBoundsException(String message, Throwable cause) { super(message, cause); } }
1,420
28
82
java
cst
cst-master/src/main/java/br/unicamp/cst/core/exceptions/CodeletThresholdBoundsException.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.core.exceptions; /** * This class represents a Java exception to be thrown when the codelet's * threshold is set to more than 1.0 or less than 0.0. * * @author A. L. O. Paraense * @author K. Raizer * @see Exception */ public class CodeletThresholdBoundsException extends Exception { private static final long serialVersionUID = 1L; /** * Creates a CodeletThresholdBoundsException. * * @param message * the exception message. */ public CodeletThresholdBoundsException(String message) { super(message); } /** * Creates a CodeletThresholdBoundsException. * * @param message * the exception message. * @param cause * the exception cause. */ public CodeletThresholdBoundsException(String message, Throwable cause) { super(message, cause); } }
1,393
28.041667
82
java
cst
cst-master/src/main/java/br/unicamp/cst/core/exceptions/MemoryObjectNotFoundException.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.core.exceptions; /** * This class represents a Java exception to be thrown when the access memory object * method is not capable of finding the corresponding memory object * * @author andre * */ public class MemoryObjectNotFoundException extends Exception { /** * */ private static final long serialVersionUID = -6845401281653737754L; /** * */ public MemoryObjectNotFoundException() { } /** * @param message the message */ public MemoryObjectNotFoundException(String message) { super(message); } /** * @param cause the cause of the exception */ public MemoryObjectNotFoundException(Throwable cause) { super(cause); } /** * @param message the message * @param cause the cause of the exception */ public MemoryObjectNotFoundException(String message, Throwable cause) { super(message, cause); } /** * @param message the message * @param cause the cause of the exception * @param enableSuppression if enable is to be supressed * @param writableStackTrace if there should be a writable StackTrace */ public MemoryObjectNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
1,837
26.432836
97
java
cst
cst-master/src/main/java/br/unicamp/cst/io/Actuator.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.io; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.memory.WorkingStorage; /** * The Actuator class is a Codelet which writes to working storage every memory object written to its input list. * If you remove a memory object from this actuator's input list, it will be removed from working storage as well (without deletion from raw memory). * @author Klaus * */ public abstract class Actuator extends Codelet { private WorkingStorage ws; public Actuator(WorkingStorage ws) { this.ws=ws; } @Override public void addInput(Memory mo) { this.getInputs().add(mo); if(ws!=null) ws.putMemoryObject(mo); } @Override public void removesInput(Memory mo) { this.getInputs().remove(mo); if(ws!=null) ws.removeFromWorkingStorageWithoutDelete(mo); } }
1,420
27.42
150
java
cst
cst-master/src/main/java/br/unicamp/cst/io/BodyProxy.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.io; import java.util.ArrayList; import br.unicamp.cst.core.entities.Codelet; /** * Body interface has two lists, a list of sensors and one of actuators. * It is a holder for sensor and actuator codelets. * * @author klaus * @author andre */ public class BodyProxy { private ArrayList<Codelet> listSensors; private ArrayList<Codelet> listActuators; public BodyProxy() { listSensors = new ArrayList<Codelet>(); listActuators = new ArrayList<Codelet>(); } public synchronized void startSenses() { for(Codelet sensor:listSensors) { sensor.start(); } } public synchronized void stopSenses() { for(Codelet sensor:listSensors) { sensor.stop(); } } public synchronized void startActuators() { for(Codelet actuator:listActuators) { actuator.start(); } } public synchronized void stopActuators() { for(Codelet actuator:listActuators) { actuator.stop(); } } public synchronized void addSensor(Codelet sensorAdded) { listSensors.add(sensorAdded); } public synchronized void addActuator(Codelet actuatorAdded) { listActuators.add(actuatorAdded); } public synchronized ArrayList<Codelet> getListSensors() { return listSensors; } public synchronized void setListSensors(ArrayList<Codelet> listSensors) { this.listSensors = listSensors; } public synchronized ArrayList<Codelet> getListActuators() { return listActuators; } public synchronized void setListActuators(ArrayList<Codelet> listActuators) { this.listActuators = listActuators; } }
2,119
20.414141
82
java
cst
cst-master/src/main/java/br/unicamp/cst/io/Sensor.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.io; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.memory.WorkingStorage; /** * The Sensor class is a Codelet which writes to working storage every memory object written to its output list. * If you remove a memory object from this sensor's output list, it will be removed from working storage as well (without deletion from raw memory). * @author Klaus * */ public abstract class Sensor extends Codelet { private WorkingStorage ws; public Sensor(WorkingStorage ws) { this.ws=ws; } @Override public synchronized void addOutput(Memory mo) { this.getOutputs().add(mo); if(ws!=null) ws.putMemoryObject(mo); } @Override public synchronized void removesOutput(Memory mo) { this.getOutputs().remove(mo); if(ws!=null) ws.removeFromWorkingStorageWithoutDelete(mo); } }
1,440
29.659574
149
java
cst
cst-master/src/main/java/br/unicamp/cst/io/SocketCom.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.io; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; /** * This class serves as a socket communication link for applications that * require network access to their world/creature * * @author klaus.raizer * */ public class SocketCom { private PrintWriter out; private BufferedReader in; private Socket socket; public SocketCom(){ } /** * Connect a socket to the given host and port. * @param host * @param port */ public void connect(String host, int port){ //Create socket connection try{ socket = new Socket(host, port); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( socket.getInputStream())); } catch (UnknownHostException e) { System.out.println("Unknown host: "+host); System.exit(1); } catch (IOException e) { System.out.println("No I/O"); System.exit(1); } } /** * Sends a string message through socket connection. * @param text */ public void sendMessage(String text){ out.println(text); } /** * Returns the last line in buffer. * Beware that calling this method with nothing in the buffer will * make the object wait for a new line to come about, most likelly * locking the thread. * @return the last line in the buffer */ public String receiveMessage(){ String textReceived=""; //Receive text from server try{ while (!in.ready()); do { String line = in.readLine(); textReceived=line; //Gets the last line in buffer }while(in.ready()); } catch (IOException e){ System.out.println("Read failed"); System.exit(1); } return textReceived; } public void close() { try { this.socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
2,514
22.287037
82
java
cst
cst-master/src/main/java/br/unicamp/cst/io/UDPClient.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.io; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; /** * UDP communication via socket. Client side. * * * @author Klaus * */ public class UDPClient { private String serverHostname; private int port; private DatagramSocket clientSocket; private InetAddress IPAddress; private int bufferSize; public UDPClient(String serverHostname, int port,int bufferSize){ this.serverHostname = serverHostname; this.bufferSize=bufferSize; this.port=port; try { clientSocket = new DatagramSocket(); try { IPAddress = InetAddress.getByName(serverHostname); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized void send(String sentence){ byte[] sendData = new byte[bufferSize]; sendData = sentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); try { clientSocket.send(sendPacket); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Receives information from server as an array of bytes * @return array with received bytes */ public synchronized byte[] receiveByteArray(){ byte[] receiveData = new byte[bufferSize]; //TODO Must be dynamic DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); try { clientSocket.receive(receivePacket); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // String sentence = new String(receivePacket.getData()); byte[] sentence = receivePacket.getData(); return sentence; } /** * Receives information from client as a String * @return string with the information from client */ public synchronized String receive(){ byte[] receiveData = new byte[bufferSize]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); String modifiedSentence=""; try { clientSocket.receive(receivePacket); modifiedSentence = new String(receivePacket.getData()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return modifiedSentence; } public synchronized void close(){ clientSocket.close(); } }
3,023
25.761062
94
java
cst
cst-master/src/main/java/br/unicamp/cst/io/UDPServer.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.io; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class UDPServer { private int port; private int bufferSize; private DatagramSocket serverSocket; public UDPServer(int port, int bufferSize){ this.bufferSize=bufferSize; this.port=port; try { this.serverSocket = new DatagramSocket(port); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Receives information from server as a String * @return a string with the information from server */ public synchronized String receive(){ // System.out.println("inside receive"); byte[] receiveData = new byte[bufferSize]; //TODO Must be dynamic DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); try { serverSocket.receive(receivePacket); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String sentence = new String(receivePacket.getData()); // System.out.println("exited received"); return sentence; } /** * Receives information from server as an array of bytes * @return information from server as an array of bytes */ public synchronized byte[] receiveByteArray(){ byte[] receiveData = new byte[bufferSize]; //TODO Must be dynamic DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); try { serverSocket.receive(receivePacket); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // String sentence = new String(receivePacket.getData()); byte[] sentence = receivePacket.getData(); return sentence; } }
2,298
28.101266
86
java
cst
cst-master/src/main/java/br/unicamp/cst/io/rest/CodeletJson.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation * **********************************************************************************************/ package br.unicamp.cst.io.rest; import br.unicamp.cst.core.entities.Codelet; import java.util.ArrayList; import java.util.List; public class CodeletJson { private double activation; private long timestamp; private String name; private String group; private List<MemoryJson> broadcast = new ArrayList<MemoryJson>(); private List<MemoryJson> inputs = new ArrayList<MemoryJson>(); private List<MemoryJson> outputs = new ArrayList<MemoryJson>(); public CodeletJson(Codelet cod) { this.activation = cod.getActivation(); this.timestamp = System.currentTimeMillis(); this.name = cod.getName(); for (int i = 0; i < cod.getBroadcast().size(); i++) { this.broadcast.add(new MemoryJson(cod.getBroadcast().get(i))); } for (int i = 0; i < cod.getInputs().size(); i++) { this.inputs.add(new MemoryJson(cod.getInputs().get(i))); } for (int i = 0; i < cod.getOutputs().size(); i++) { this.outputs.add(new MemoryJson(cod.getOutputs().get(i))); } } public CodeletJson(Codelet cod, String group) { this(cod); this.group = group; } public List<MemoryJson> getInputs() { return inputs; } public List<MemoryJson> getOutputs() { return outputs; } public List<MemoryJson> getBroadcast() { return broadcast; } public String getGroup() { return group; } public String getName() { return name; } }
2,124
30.716418
98
java
cst
cst-master/src/main/java/br/unicamp/cst/io/rest/HttpCodelet.java
package br.unicamp.cst.io.rest; import br.unicamp.cst.core.entities.Codelet; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; public abstract class HttpCodelet extends Codelet { public String sendPOST(String POST_URL, String POST_PARAMS, String method) throws IOException { URL obj = new URL(POST_URL); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); //"application/json" if(method != null){con.setRequestProperty("Content-Type", method);} //con.setRequestProperty("User-Agent", USER_AGENT); // For POST only - START con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write(POST_PARAMS.getBytes()); os.flush(); os.close(); // For POST only - END int responseCode = con.getResponseCode(); System.out.println("POST Response Code :: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { //success BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } return null; } public String sendGET(String GET_URL) throws IOException { String message = ""; URL obj = new URL(GET_URL); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); //con.setRequestProperty("User-Agent", USER_AGENT); int responseCode=0; responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // success BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); message = response.toString(); } return(message); } public String prepareParams(HashMap<String, String> params){ StringBuilder sbParams = new StringBuilder(); int i = 0; for (String key : params.keySet()) { try { if (i != 0){ sbParams.append("&"); } sbParams.append(key).append("=") .append(URLEncoder.encode(params.get(key), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } i++; } return sbParams.toString(); } }
2,966
29.90625
99
java
cst
cst-master/src/main/java/br/unicamp/cst/io/rest/MemoryContainerJson.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation * **********************************************************************************************/ package br.unicamp.cst.io.rest; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.entities.MemoryContainer; import java.util.ArrayList; import java.util.List; public class MemoryContainerJson { public Long timestamp; public volatile Double evaluation; public volatile Object I; public String name; public String group; public ArrayList<MemoryContainerJson> memories = new ArrayList<MemoryContainerJson>(); public MemoryContainerJson(Memory memo) { timestamp = memo.getTimestamp(); evaluation = memo.getEvaluation(); I = memo.getI(); name = memo.getName(); if (memo instanceof MemoryContainer) { MemoryContainer memoAux = (MemoryContainer) memo; List<Memory> memoList = memoAux.getAllMemories(); for (int i = 0; i < memoList.size(); i++) { this.memories.add(new MemoryContainerJson(memoList.get(i))); } } } public MemoryContainerJson(Memory memo, String group) { this(memo); this.group = group; } }
1,691
32.84
98
java
cst
cst-master/src/main/java/br/unicamp/cst/io/rest/MemoryJson.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation * **********************************************************************************************/ package br.unicamp.cst.io.rest; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.entities.MemoryContainer; import java.util.ArrayList; import java.util.List; public class MemoryJson { public Long timestamp; public volatile Double evaluation; public volatile Object I; public String name; public String group; public ArrayList<MemoryJson> memories; // = new ArrayList<MemoryJson>(); public MemoryJson(Memory memo) { timestamp = memo.getTimestamp(); evaluation = memo.getEvaluation(); I = memo.getI(); name = memo.getName(); if (memo instanceof MemoryContainer) { memories = new ArrayList<>(); MemoryContainer memoAux = (MemoryContainer) memo; List<Memory> memoList = memoAux.getAllMemories(); for (int i = 0; i < memoList.size(); i++) { this.memories.add(new MemoryJson(memoList.get(i))); } } } public MemoryJson(Memory memo, String group) { timestamp = memo.getTimestamp(); evaluation = memo.getEvaluation(); I = memo.getI(); name = memo.getName(); this.group = group; if (memo instanceof MemoryContainer) { memories = new ArrayList<>(); MemoryContainer memoAux = (MemoryContainer) memo; List<Memory> memoList = memoAux.getAllMemories(); for (int i = 0; i < memoList.size(); i++) { this.memories.add(new MemoryJson(memoList.get(i))); } } } }
2,163
34.47541
98
java
cst
cst-master/src/main/java/br/unicamp/cst/io/rest/MindJson.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation * **********************************************************************************************/ package br.unicamp.cst.io.rest; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.entities.Mind; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; public class MindJson { public List<MemoryJson> memories = new ArrayList<MemoryJson>(); public List<CodeletJson> codelets = new ArrayList<CodeletJson>(); public MindJson(Mind m) { if (m.getMemoryGroupsNumber() == 0) { List<Memory> mems = m.getRawMemory().getAllMemoryObjects(); for (int i = 0; i < mems.size(); i++) { this.memories.add(new MemoryJson(mems.get(i))); } } else { ConcurrentHashMap<String, ArrayList> mems = m.getMemoryGroups(); for (String key : mems.keySet()) { ArrayList<Memory> memoList = mems.get(key); for (int i = 0; i < memoList.size(); i++) { this.memories.add(new MemoryJson(memoList.get(i), key)); } } } if (m.getCodeletGroupsNumber() == 0) { List<Codelet> cods = m.getCodeRack().getAllCodelets(); for (int i = 0; i < cods.size(); i++) { this.codelets.add(new CodeletJson(cods.get(i))); } } else { ConcurrentHashMap<String, java.util.ArrayList> cods = m.getCodeletGroups(); for (String key : cods.keySet()) { ArrayList<Codelet> codList = cods.get(key); for (int i = 0; i < codList.size(); i++) { this.codelets.add(new CodeletJson(codList.get(i), key)); } } } } }
2,381
38.7
98
java
cst
cst-master/src/main/java/br/unicamp/cst/io/rest/RESTServer.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation * **********************************************************************************************/ package br.unicamp.cst.io.rest; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.entities.MemoryContainer; import br.unicamp.cst.core.entities.MemoryObject; import br.unicamp.cst.core.entities.Mind; import br.unicamp.cst.support.InterfaceAdapter; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import express.Express; import express.middleware.CorsOptions; import express.middleware.Middleware; /** * This is the main class for using REST to monitor inner activities from CST * It is used to provide a REST server to monitor whatever is happening within a CST mind * Depending on the constructor, the user can set the mind, the port to be used, if * the JSON describing the inner details of the mind should be rendered with pretty printing * and a way to limit the access of external users to the server * @author rgudwin */ public class RESTServer { long refresh = 0; // A refresh of 0 means that every call will generate a new probe in mind long lastaccess = 0; String lastmessage = ""; /** * * @param m the mind to observe * @param port the port to install the REST server */ public RESTServer(Mind m, int port) { this(m,port,false); } /** * * @param m the mind to observe * @param port the port to install the REST server * @param pretty set this to true to generate pretty printing JSON in the REST server */ public RESTServer(Mind m, int port, boolean pretty) { this(m,port,pretty,"*"); } /** * * @param m the mind to observe * @param port the port to install the REST server * @param pretty set this to true to generate pretty printing JSON in the REST server * @param origin a pattern for users allowed to access the server - use "*" to allow everyone */ public RESTServer(Mind m, int port, boolean pretty, String origin) { this(m,port,pretty,origin,0L); } /** * * @param m the mind to observe * @param port the port to install the REST server * @param pretty set this to true to generate pretty printing JSON in the REST server * @param origin a pattern for users allowed to access the server - use "*" to allow everyone * @param nrefresh the refresh period in milliseconds */ public RESTServer(Mind m, int port, boolean pretty, String origin, long nrefresh) { refresh = nrefresh; Express app = new Express(); Gson gson; if (pretty) gson = new GsonBuilder().registerTypeAdapter(Memory.class, new InterfaceAdapter<MemoryObject>()) .registerTypeAdapter(Memory.class, new InterfaceAdapter<MemoryContainer>()) .setPrettyPrinting().create(); else gson = new Gson(); CorsOptions corsOptions = new CorsOptions(); corsOptions.setOrigin(origin); app.use(Middleware.cors(corsOptions)); app.get("/", (req, res) -> { long currentaccess = System.currentTimeMillis(); long diff = currentaccess - lastaccess; if (diff > refresh) { MindJson myJson = new MindJson(m); lastmessage = gson.toJson(myJson); lastaccess = currentaccess; } res.send(lastmessage); }); app.listen(port); } }
4,027
38.106796
108
java
cst
cst-master/src/main/java/br/unicamp/cst/language/NameGenerator.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.language; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * * @author suelen */ public class NameGenerator { private static List<String> listNames = new ArrayList<String>(); static int rand(int Str, int End) { return (int) Math.ceil(Math.random() * (End - Str + 1)) - 1 + Str; } public String generateWord() { String newW = ""; String vowels = "aeiou"; boolean find = false; int numberOfSyllables = rand(2, 4); do { Random ra = new Random(); for (int x = 0; x < numberOfSyllables; x++) { int valor = 0; do { valor = (97 + ra.nextInt(122 - 97)); } while (vowels.contains(String.valueOf((char) valor))); newW = newW + String.valueOf((char) valor); newW = newW + String.valueOf(vowels.charAt(ra.nextInt(vowels.length()))); } find = checkName(newW); } while (find == true); //System.out.println("A palavra gerada eh: " + newW); listNames.add(newW); return newW; } public boolean checkName(String name) { boolean find = false; for (int i = 0; i < listNames.size(); i++) { if (name.equals(listNames.get(i))) { find = true; } } return find; } }
1,995
24.922078
89
java
cst
cst-master/src/main/java/br/unicamp/cst/learning/QLearning.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation * E. M. Froes - documentation ******************************************************************************/ package br.unicamp.cst.learning; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import java.util.Random; import org.json.JSONException; import org.json.JSONObject; /** * The update equation for TD Q-learning is: * Q(s,a)= Q(s,a) + alpha * (r(s) + gamma * Max(s', all actions) - Q(s,a)) * * which is calculated whenever action a is executed in state s leading to state s'. * acting randomly on some fraction of steps, where the fraction decreases over time, * we can dispense with keeping statistics about taken actions. * * [1] Ganapathy 2009 "Utilization of Webots and the Khepera II as a Platform for Neural Q-Learning Controllers" * [2] http://people.revoledu.com/kardi/tutorial/ReinforcementLearning/Q-Learning-Matlab.htm * [3] Norvig * @author klaus * */ public class QLearning { private boolean showDebugMessages=false; private ArrayList<String> statesList; private ArrayList<String> actionsList; private String fileName="QTable.txt"; private HashMap<String, HashMap<String,Double>> Q; private double e=0.1; //Probability of choosing the best action instead of a random one private double alpha=0.5; //Here, alpha is the learning rate parameter private double gamma=0.9; //discount factor private double b=0.95; // probability of random action choice deciding for the previous action instead of randomly choosing one from the action list // private int statesCount,actionsCount; private String s="",a="",sl="",al=""; private double reward=0; private Random r=new Random(); /** * Default Constructor. */ public QLearning(){ statesList=new ArrayList<String>(); actionsList=new ArrayList<String>(); Q = new HashMap<String, HashMap<String,Double>>(); // Q learning } /** * This method set Q value with parameters Qval, state and action. * @param Qval * @param state * @param action */ public void setQ(double Qval, String state, String action){ HashMap<String,Double> tempS=this.Q.get(state); if(tempS!=null){ //This state already exists, So I have to check if it already contains this action if(tempS.get(action)!=null){ //the action already exists, So I just update it to the new one tempS.put(action, Qval); } else{ if(!actionsList.contains(action)){//TODO something wicked here. I shouldn't need to perform this test... actionsList.add(action); } tempS.put(action, Qval); } }else{ //this state doesn't exist yet, so I must create it and populate it with nActions-1 valued 0 and one action valued Qval HashMap<String,Double> tempNew= new HashMap<String,Double>(); tempNew.put(action, Qval); statesList.add(state); this.Q.put(state, tempNew); } } /** * Returns the utility value Q related to the given state/action pair * @param state * @param action * @return the Q utility value related to the given state/action pair */ public double getQ(String state,String action){ double dQ=0; if(!(Q.get(state)==null || Q.get(state).get(action)==null)){ dQ=Q.get(state).get(action); } return dQ; } /** * Returns the maximum Q value for sl. * @param sl * @return Q Value */ public double maxQsl(String sl){ double maxQinSl=0; String maxAl=""; double val=0; if(this.Q.get(sl)!=null){ HashMap<String,Double> tempSl=this.Q.get(sl); ArrayList<String> tempA=new ArrayList<String>(); tempA.addAll(this.actionsList); // Finds out the action with maximum value for sl Iterator<Entry<String, Double>> it = tempSl.entrySet().iterator(); while (it.hasNext()) { Entry<String, Double> pairs = it.next(); val= pairs.getValue(); tempA.remove(pairs.getKey()); if(val>maxQinSl){ maxAl=pairs.getKey(); maxQinSl=val; } } if(!tempA.isEmpty() && maxQinSl<0){maxQinSl=0;} //Assigning 0 to unknown state/action pair } return maxQinSl; } /** * This methods is responsible for update the state. * @param stateIWas state I was previously * @param actionIDid action I did while at the previous state * @param rewardIGot reward I got after moving from previous state to the present one */ public void update(String stateIWas,String actionIDid, double rewardIGot) { //which is calculated whenever action a is executed in state s leading to state s' this.sl=stateIWas; this.al=actionIDid; if(!a.equals("")&& !s.equals("")){ // if(!s.equals(sl)){//Updates only if state changes, is this correct? double Qas=this.getQ(s, a); double MaxQ=this.maxQsl(this.sl); double newQ= Qas + alpha * (rewardIGot + gamma * MaxQ - Qas); //TODO not sure if its reward or rewardIGot this.setQ(newQ, s, a); // System.out.println("== Update ============"); // System.out.println("a: "+a+" s: "+s+" al: "+al+" sl: "+sl+" Qas: "+Qas+" MaxQ: "+MaxQ+" newQ: "+newQ); // System.out.println("======================"); // this.printQ(); // } } a=this.al; s=this.sl; reward=rewardIGot; } /** * This print Q values. */ public void printQ() { System.out.println("------ Printed Q -------"); Iterator<Entry<String, HashMap<String, Double>>> itS = this.Q.entrySet().iterator(); while (itS.hasNext()) { Entry<String, HashMap<String, Double>> pairs = itS.next(); HashMap<String,Double> tempA = pairs.getValue(); Iterator<Entry<String, Double>> itA = tempA.entrySet().iterator(); double val=0; System.out.print("State("+pairs.getKey()+") actions: "); while(itA.hasNext()){ Entry<String, Double> pairsA = itA.next(); val=pairsA.getValue(); System.out.print("["+pairsA.getKey()+": "+val+"] "); } System.out.println(""); } System.out.println("----------------------------"); } /** * Store Q values to file using JSON structure. */ public void storeQ(){ String textQ=""; // JSONArray actionValueArray=new JSONArray(); JSONObject actionValuePair = new JSONObject(); JSONObject actionsStatePair = new JSONObject(); // JSONArray statesArray= new JSONArray(); try { Iterator<Entry<String, HashMap<String, Double>>> itS = this.Q.entrySet().iterator(); while (itS.hasNext()) { Entry<String, HashMap<String, Double>> pairs = itS.next(); HashMap<String,Double> tempA = pairs.getValue(); Iterator<Entry<String, Double>> itA = tempA.entrySet().iterator(); double val=0; // System.out.print("State("+pairs.getKey()+") actions: "); actionValuePair=new JSONObject(); while(itA.hasNext()){ Entry<String, Double> pairsA = itA.next(); val=pairsA.getValue(); actionValuePair.put(pairsA.getKey(), val); } // System.out.println(actionsStatePair+" "+pairs.getKey()+" "+actionValuePair); actionsStatePair.put(pairs.getKey(),actionValuePair); } } catch (JSONException e) {e.printStackTrace();} //use buffering Writer output; try { output = new BufferedWriter(new FileWriter(fileName)); try { //FileWriter always assumes default encoding is OK! output.write( actionsStatePair.toString() ); } finally { output.close(); } } catch (IOException e) {e.printStackTrace();} // System.out.println("------ Stored Q -------"); // System.out.println("Q: "+actionsStatePair.toString()); // System.out.println("----------------------------"); } /** * Recover Q values from file in JSON structure. */ public void recoverQ(){ //...checks on aFile are elided StringBuilder contents = new StringBuilder(); try { //use buffering, reading one line at a time //FileReader always assumes default encoding is OK! BufferedReader input = new BufferedReader(new FileReader(fileName)); try { String line = null; //not declared within while loop /* * readLine is a bit quirky : * it returns the content of a line MINUS the newline. * it returns null only for the END of the stream. * it returns an empty String if two newlines appear in a row. */ while (( line = input.readLine()) != null){ contents.append(line); //contents.append(System.getProperty("line.separator")); } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } // actionValuePair.put(pairsA.getKey(), val); // } // System.out.println("contents: "+contents.toString()); JSONObject actionsStatePairs; try { actionsStatePairs = new JSONObject(contents.toString()); // System.out.println("actionsStatePairs.toString(): "+actionsStatePairs.toString()); Iterator itS = actionsStatePairs.keys(); while (itS.hasNext()) { String state=itS.next().toString(); // System.out.println("itS.next(): "+state); JSONObject pairAS = (JSONObject) actionsStatePairs.get(state); Iterator itA = pairAS.keys(); while(itA.hasNext()){ String action=itA.next().toString(); double value = pairAS.getDouble(action); this.setQ(value, state, action); } } } catch (JSONException e1) { e1.printStackTrace(); } } /** * Clear Q values. */ public void clearQ(){ this.Q.clear(); } /** * Gets alpha value. * @return alpha value */ public double getAlpha() { return alpha; } /** * Sets the learning rate parameter alpha. * Should be between 0 and 1 * @param alpha */ public void setAlpha(double alpha) { this.alpha = alpha; } /** * Gets gamma value. * @return the gamma value */ public double getGamma() { return gamma; } /** * Sets the discount factor. * Should be between 0 and 1. * @param gamma */ public void setGamma(double gamma) { this.gamma = gamma; } /** * Selects the best action for this state with probability "e", * and a random one with probability (1-e) * If a given state has no record of one or more actions, it will consider them as valued 0. * @param state * * @return selectedAction */ public String getAction(String state){//TODO should improve this. It should consider all non explored actions as being equally 0 for all purposes // System.out.println("Inside get action"); String selectedAction=null; if(r.nextDouble()<=e){ //TODO Use boltzmann distribution here? // if(ql.getAction(stringState)!=null){ // action=ql.getAction(stringState);// //----- if(this.Q.get(state)!=null){ ArrayList<String> actionsLeft=new ArrayList<String>(); actionsLeft.addAll(this.actionsList); HashMap<String, Double> actionsQ = this.Q.get(state); double bestQval=-Double.POSITIVE_INFINITY; Iterator<Entry<String, Double>> it = actionsQ.entrySet().iterator(); while(it.hasNext()){ Entry<String,Double> pairs = it.next(); double qVal = pairs.getValue(); String qAct=pairs.getKey(); if(qVal>bestQval){ bestQval=qVal; selectedAction=qAct; } actionsLeft.remove(qAct); } if((bestQval<0)&&(actionsLeft.size()>0)){ //this means we should randomly choose from the other actions; selectedAction=selectRandomAction(actionsLeft); } if(showDebugMessages){System.out.println("Selected the best available action.");} }else{ // System.out.println("Inside else null"); // selectedAction=null; selectedAction=selectRandomAction(actionsList); if(showDebugMessages){System.out.println("Selected a random action because there was no available suggestion.");} } // }else{ // action=selectRandomAction(); // } }else{ if(showDebugMessages){System.out.println("Naturally selected a random action.");} selectedAction=selectRandomAction(actionsList); } return selectedAction; } /** * Gets states list. * @return the statesList */ public ArrayList<String> getStatesList() { return statesList; } /** * Sets action list. * @param statesList the statesList to set */ public void setStatesList(ArrayList<String> statesList) { this.statesList = statesList; } /** * Gets the action list. * @return the actionsList */ public ArrayList<String> getActionsList() { return actionsList; } /** * This sets action list. * @param actionsList the actionsList to set */ public void setActionsList(ArrayList<String> actionsList) { this.actionsList=new ArrayList<String>(); this.actionsList.addAll(actionsList); } /** * Gets E value. * @return e */ public double getE() { return e; } /** * Sets the chances of getting the best possible action. * With e=0.9 for instance, there is a .9 chance of getting the best action for the given state, and .1 probability of getting a random action. * * @param e the e to set */ public void setE(double e) { this.e = e; } /** * Gets all actions from state. * @param state * @return actons */ public String getAllActionsFromState(String state){ String actions=""; if(this.Q.get(state)!=null){ HashMap<String, Double> actionsH=this.Q.get(state); Iterator<Entry<String, Double>> it = actionsH.entrySet().iterator(); while(it.hasNext()){ Entry<String, Double> pairs = it.next(); double qVal = (Double) pairs.getValue(); String act = (String) pairs.getKey(); actions=actions+"{"+act+":"+qVal+"} "; } }else{ actions="{}"; } return actions; } /** * Select randomically a action. * @param localActionsList * @return actionR */ private String selectRandomAction(ArrayList<String> localActionsList) { String actionR=this.a; double pseudoRandomNumber=r.nextDouble(); if((pseudoRandomNumber>=b)||actionR==null||actionR.equals("")){ int actionI=r.nextInt(localActionsList.size()); actionR=localActionsList.get(actionI); } // System.out.println("INSIDE RANDOM: "+actionR); return actionR;//TODO should I use boltzman distribution? /* * Simulating a Pareto random variable. The Pareto distribution is often used to model * insurance claims damages, financial option holding times, and Internet traffic activity. * The probability that a Pareto random variable with parameter a is less than x is * F(x) = 1 - (1 + x)-a for x >= 0. To generate a random deviate from the distribution, * use the inverse function method: output (1-U)-1/a - 1, where U is a uniform random number between 0 and 1. */ } /** * This method "maxwellBoltzmann()" returns a pseudo-random value from a Maxwell-Boltzmann distribution * with parameter sigma. Take the sum of the squares of three gaussian random variables * with mean 0, and standard deviation sigma, and return the square root. * double e = random.nextGaussian(); // Gaussian with mean 0 and stddev = 1 * * @return sum */ public double maxwellBoltzmann(){ double sum=0; sum=sum+Math.pow(r.nextGaussian(),2); sum=sum+Math.pow(r.nextGaussian(),2); sum=sum+Math.pow(r.nextGaussian(),2); sum=Math.sqrt(sum); return sum; } /** * Gets B value. * @return the b */ public double getB() { return b; } /** * Sets B value. * @param b the b to set */ public void setB(double b) { this.b = b; } /** * Gets S value. * @return the s */ public String getS() { return s; } /** * Sets S value. * @param s the s to set */ public void setS(String s) { this.s = s; } /** * Gets A value. * @return the a */ public String getA() { return a; } /** * Sets A value. * @param a the a to set */ public void setA(String a) { this.a = a; } /** * Gets SL value. * @return the sl */ public String getSl() { return sl; } /** * Sets SL value. * @param sl the sl to set */ public void setSl(String sl) { this.sl = sl; } /** * Gets the AL value. * @return the al */ public String getAl() { return al; } /** * Sets AL value. * @param al the al to set */ public void setAl(String al) { this.al = al; } /** * Gets all Q values. * @return the Q value */ public HashMap getAllQ() { return this.Q; } }
17,428
25.528158
149
java
cst
cst-master/src/main/java/br/unicamp/cst/learning/Simple2dRLearn.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation * E. M. Froes - documentation ******************************************************************************/ package br.unicamp.cst.learning; import java.util.Random; import javax.lang.model.element.NestingKind; /** * This class is used to perform a simple reinforcement learning with multiple state dimensions. * * It is composed by a multidimensional Q table with all dimensions but the last meaning states, and with the last dimension meaning actions. * * For instance, with a 2d state space we would have: * * Q(s1,s2,a) = Q(s1,s2,a) + R * * Where R is the reward for performing action a at states s1 and s2. * * Important: This method does not account for state transitions like Q-Learning or SARSA do. * * @author Klaus * */ public class Simple2dRLearn { double[][][] Q = null; int Na=0; //number of actions int Ns=0; //number of states Random rnd = new Random(); /** * Default Constructor. * @param Ns * @param Na */ public Simple2dRLearn(int Ns,int Na){ this.Na=Na; //number of actions this.Ns=Ns; //number of states this.Q = new double[Ns][Ns][Na]; //All set as zero from the start } /** * Updates Q table of values * * @param s1 previous state * @param s2 current state * @param a chosen action * @param r reward for performing action a in state s1/s2, should be between -1 and 1 */ public void update(int s1,int s2, int a, double r){ if(r<=1 && r>=-1){ if(s1>=Ns || s2>=Ns || a>=Na){ if(s1>=Ns || s2>=Ns){ // System.out.println("State "+s+" doesn't exist."); throw new Error("State [s1="+s1+", s2="+s2+"] doesn't exist."); } if(a>=Na){ throw new Error("Action "+a+" doesn't exist."); } }else{ Q[s1][s2][a]=Q[s1][s2][a]+r; //Must scale for each state double new_value = Q[s1][s2][a]; double min=0; double max=1; if(new_value>1){ max=new_value; } if(new_value<0){ min=new_value; } if((max-min)!=0){ for(int ac=0;ac<Na;ac++){ Q[s1][s2][ac]=(Q[s1][s2][ac]-min)/(max-min); } }else{ for(int ac=0;ac<Na;ac++){ Q[s1][s2][ac]=(Q[s1][s2][ac]-min); } } } }else{ throw new Error("Reward value out of range. It should be between -1 and 1"); } } /** * Add action. */ public void addAction(){ int newNa = this.Na+1; double[][][] new_Q = new double[Ns][Ns][newNa]; for(int s1=0;s1<Ns;s1++){ for(int s2=0;s2<Ns;s2++){ for(int ac=0;ac<Na;ac++){ new_Q[s1][s2][ac]=Q[s1][s2][ac]; } } } this.Na=newNa; Q=new_Q; } /** * Add state. */ public void addState(){ int newNs = this.Ns+1; double[][][] new_Q = new double[newNs][newNs][Na]; for(int s1=0;s1<Ns;s1++){ for(int s2=0;s2<Ns;s2++){ for(int ac=0;ac<Na;ac++){ new_Q[s1][s2][ac]=Q[s1][s2][ac]; } } } this.Ns=newNs; Q=new_Q; } /** * Print Q values. */ public void printQ(){ System.out.println("--- Q table ---"); for(int ac=0;ac<Na;ac++){ System.out.println("------ Action "+ac+" ---"); for(int s1=0;s1<Ns;s1++){ for(int s2=0;s2<Ns;s2++){ System.out.print(Q[s1][s2][ac]+" "); } System.out.println(""); } } System.out.println("---------------"); } /** * Gets the best action for state s. * If there is a tie between best actions, it chooses randomly between them. * @param s1 first * @param s2 second * @return best action for state s */ public int getBestAction(int s1, int s2){ int best_a=-1; if((s1<Ns && s1>=0)&& (s2<Ns && s2>=0)){ double best_value=Double.NEGATIVE_INFINITY; for(int act=0;act<Na;act++){ if(Q[s1][s2][act]>best_value){ best_value=Q[s1][s2][act]; best_a=act; } if(Q[s1][s2][act]==best_value){ if(rnd.nextBoolean()){ best_value=Q[s1][s2][act]; best_a=act; } } } }else{ throw new Error("State [s1: "+s1+" and s2: "+s2+"] doesn't exist."); } return best_a; } /** * Returns the best chosen action and its value in Q. * NOTE: Remember that best_action should probably be cast to int for use outside this class. * @param s1 * @param s2 * @return a double array {best_action, best_value} */ public double[] getBestActionAndValue(int s1, int s2) { double best_a=-1; double best_value=Double.NEGATIVE_INFINITY; if((s1<Ns && s1>=0)&& (s2<Ns && s2>=0)){ for(int act=0;act<Na;act++){ if(Q[s1][s2][act]>best_value){ best_value=Q[s1][s2][act]; best_a=act; } if(Q[s1][s2][act]==best_value){ if(rnd.nextBoolean()){ best_value=Q[s1][s2][act]; best_a=act; } } } }else{ throw new Error("State [s1: "+s1+" and s2: "+s2+"] doesn't exist."); } double[] best={best_a,best_value}; return best; } /** * Gets Q value. * @return the q */ public double[][][] getQ() { return Q; } /** * Sets Q value. * @param q the q to set */ public void setQ(double[][][] q) { this.Ns=q.length; this.Na=q[0][0].length; Q = q; } /** * Gets NA value. * @return the na */ public int getNa() { return Na; } /** * Sets NA value. * @param na the na to set */ public void setNa(int na) { Na = na; } /** * Gets NS value. * @return the ns */ public int getNs() { return Ns; } /** * Sets NS value. * @param ns the ns to set */ public void setNs(int ns) { Ns = ns; } /** * Verify if is empty. * @return true or false */ public boolean isEmpty(){ boolean empty=(this.Na==0 || this.Ns==0); return empty; } }
6,267
20.539519
142
java
cst
cst-master/src/main/java/br/unicamp/cst/learning/SimpleRLearn.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation * E. M. Froes - documentation ******************************************************************************/ package br.unicamp.cst.learning; import java.util.Random; /** * This class is used to perform a simple reinforcement learning. * * It is composed by a Q table with rows meaning states and columns meaning actions. * * For row s and column a, we have: * * Q(s,a) = Q(s,a) + R * * Where R is the reward for performing action a at state s. * * Important: This method does not account for state transitions like Q-Learning or SARSA do. * * @author Klaus * */ public class SimpleRLearn { double[][] Q = null; int Na=0; //number of actions int Ns=0; //number of states Random rnd = new Random(); /** * Default Constructor. * @param Ns * @param Na */ public SimpleRLearn(int Ns,int Na){ this.Na=Na; //number of actions this.Ns=Ns; //number of states this.Q = new double[Ns][Na]; //All set as zero from the start } /** * Updates Q table of values. * @param s current state * @param a chosen action * @param r reward for performing action a in state s, should be between -1 and 1 */ public void update(int s, int a, double r){ if(r<=1 && r>=-1){ if(s>=Ns && a>=Na){ //TODO shouldn't be || ? if(s>=Ns){ //System.out.println("State "+s+" doesn't exist."); throw new Error("State "+s+" doesn't exist."); } if(a>=Na){ throw new Error("Action "+a+" doesn't exist."); } }else{ Q[s][a]=Q[s][a]+r; //Must normalize for each state double new_value = Q[s][a]; double min=0; double max=1; if(new_value>1){ max=new_value; } if(new_value<0){ min=new_value; } if((max-min)!=0){ for(int ac=0;ac<Na;ac++){ Q[s][ac]=(Q[s][ac]-min)/(max-min); } }else{ for(int ac=0;ac<Na;ac++){ Q[s][ac]=(Q[s][ac]-min); } } } }else{ throw new Error("Reward value out of range. It should be between -1 and 1"); } } /** * Add action. */ public void addAction(){ int newNa = this.Na+1; double[][] new_Q = new double[Ns][newNa]; for(int st=0;st<Ns;st++){ for(int ac=0;ac<Na;ac++){ new_Q[st][ac]=Q[st][ac]; } } this.Na=newNa; Q=new_Q; } /** * Add state. */ public void addState(){ int newNs = this.Ns+1; double[][] new_Q = new double[newNs][Na]; for(int st=0;st<Ns;st++){ for(int ac=0;ac<Na;ac++){ new_Q[st][ac]=Q[st][ac]; } } this.Ns=newNs; Q=new_Q; } /** * Print Q value. */ public void printQ(){ System.out.println("--- Q table ---"); for(int st=0;st<Ns;st++){ for(int ac=0;ac<Na;ac++){ System.out.print(Q[st][ac]+" "); } System.out.println(""); } System.out.println("---------------"); } /** * Gets the best action for state s. * If there is a tie between best actions, it chooses randomly between them. * @param s input state * @return best action for state s */ public int getBestAction(int s){ int best_a=-1; if(s<Ns){ double best_value=Double.NEGATIVE_INFINITY; for(int act=0;act<Na;act++){ if(Q[s][act]>best_value){ best_value=Q[s][act]; best_a=act; } if(Q[s][act]==best_value){ if(rnd.nextBoolean()){ best_value=Q[s][act]; best_a=act; } } } }else{ throw new Error("State "+s+" doesn't exist."); } return best_a; } /** * Gets Q value. * @return the q */ public double[][] getQ() { return Q; } /** * Sets Q value. * @param q the q to set */ public void setQ(double[][] q) { Q = q; } /** * Gets NA value. * @return the na */ public int getNa() { return Na; } /** * Sets NA value. * @param na the na to set */ public void setNa(int na) { Na = na; } /** * Gets NS value. * @return the ns */ public int getNs() { return Ns; } /** * Gets NS value. * @param ns the ns to set */ public void setNs(int ns) { Ns = ns; } /** * Verify if is empty. * @return true or false */ public boolean isEmpty(){ boolean empty=(this.Na==0 || this.Ns==0); return empty; } }
4,809
18.794239
96
java
cst
cst-master/src/main/java/br/unicamp/cst/learning/glas/GlasLearner.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.learning.glas; import org.opt4j.core.Individual; import org.opt4j.core.genotype.IntegerGenotype; import org.opt4j.core.optimizer.Archive; import org.opt4j.core.start.Opt4JTask; import org.opt4j.optimizers.sa.SimulatedAnnealingModule; import org.opt4j.viewer.ViewerModule; import br.unicamp.cst.behavior.glas.GlasSequence; /** * Tries to find correct vector of integers * @author Klaus * */ public class GlasLearner { boolean show_gui=false; int nNodes = 7; //int nNodes = 7; int nActions = 3; int nStimuli = 7; int solutionSize=3*(nNodes-1); GlasSequence mySequence = null; double[] maxPositions =null; double[] minPositions = null; // PARAMETERS String filename = "experiment_glas.txt"; int nExperiment_events=1; int max_number_reRuns=500; //int max_number_reRuns=500; int nParticles = 100; //int nParticles = 1000; int neighborhoodSize=5; //int neighborhoodSize=5; double neighborhoodIncrement=2; //double neighborhoodIncrement=2; double inertia=0.75; //double inertia=0.75; double maxMinVelocity=20; //maxMinVelocity=20; int numberOfIterations = 100; //int numberOfIterations = 100; int nReRuns = 30; double best_found_fit=Double.NEGATIVE_INFINITY; int[] best_found_solution = new int[solutionSize]; double[] history_fit= new double[max_number_reRuns]; // static int[] known_final_solution={1, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 1, 1, 1, 1, 2, 2}; public GlasLearner(int nNodes, int nStimuli, int nActions) { // TODO Auto-generated constructor stub this.nNodes=nNodes; this.nStimuli=nStimuli; this.nActions=nActions; this.solutionSize=3*(nNodes-1); best_found_solution = new int[solutionSize]; } public void learnSequence(GlasSequence mySequence) { this.mySequence=mySequence; long initial_time = System.nanoTime(); best_found_fit=Double.NEGATIVE_INFINITY; for(int reRun=0;reRun<nReRuns;reRun++){ // DifferentialEvolutionModule opt_algorithm = new DifferentialEvolutionModule(); // DifferentialEvolution is restricted to class org.opt4j.core.genotype.DoubleGenotype // opt_algorithm.setGenerations(500); // opt_algorithm.setAlpha(100); // EvolutionaryAlgorithmModule opt_algorithm = new EvolutionaryAlgorithmModule(); // opt_algorithm.setGenerations(10000); //number of generations. // opt_algorithm.setAlpha(50); //population size alpha. // // opt_algorithm.setMu(25); //25 number of parents mu. // opt_algorithm.setCrossoverRate(0.5); //0.95 crossover rate. // // opt_algorithm.setLambda(25); //25 number of children lambda. // MOPSOModule opt_algorithm = new MOPSOModule(); //MOPSO is restricted to class org.opt4j.core.genotype.DoubleGenotype // opt_algorithm.setIterations(500); // Number of iterations // opt_algorithm.setParticles(500); // Number of particles //// opt_algorithm.setPerturbation(90); //SA is the best one so far SimulatedAnnealingModule opt_algorithm = new SimulatedAnnealingModule(); opt_algorithm.setIterations(1000000); //opt_algorithm.setIterations(1000000); // RandomSearchModule opt_algorithm = new RandomSearchModule(); // opt_algorithm.setIterations(2000); // opt_algorithm.setBatchsize(100); GlasOptModule gom = new GlasOptModule(); gom.setnNodes(nNodes); gom.setnActions(nActions); gom.setnStimuli(nStimuli); gom.setSequence(mySequence);//TODO could I get nActions and nStimuli from sequence instead? Opt4JTask task = new Opt4JTask(false); if(show_gui){ ViewerModule viewer = new ViewerModule(); viewer.setCloseOnStop(false); task.init(opt_algorithm,gom,viewer); } task.init(opt_algorithm,gom); int[] found_solution = new int[this.solutionSize]; double found_solution_first_eval=0; try { // System.out.println("Antes: task.execute();"); task.execute(); // System.out.println("Depois: task.execute();"); Archive archive = task.getInstance(Archive.class); // System.out.println("Archive size: "+archive.size()); for (Individual individual : archive) { IntegerGenotype gen = (IntegerGenotype) individual.getGenotype(); double[] found_solution_eval = individual.getObjectives().array(); found_solution_first_eval=found_solution_eval[0]; // System.out.println("Found solution: "); // System.out.print("[ "); // System.out.print(reRun+" "); for(int g = 0; g<gen.size();g++){ found_solution[g]=(int) Math.round(gen.get(g)); // System.out.print(found_solution[g]+" "); } // System.out.println("]"); // for(int fits=0; fits<found_solution_eval.length;fits++){ // System.out.print(found_solution_eval[fits]+" "); // } // System.out.print(" "+found_solution_eval[1]); break; } // System.out.print("Solution evaluation: "); // System.out.println(found_solution_first_eval); // System.out.println(""); } catch (Exception e) { e.printStackTrace(); } finally { task.close(); } // System.out.println("-----------------"); //Recording best found solution if((-found_solution_first_eval)>this.best_found_fit){ //the more negative the better best_found_fit=(-found_solution_first_eval); for(int s=0; s<found_solution.length;s++){ best_found_solution[s]=found_solution[s]; } } }//end rerun loop long end_time = System.nanoTime(); // // System.out.println("initial_time: "+initial_time); // // System.out.println("end_time: "+end_time); double elapsed_time = (end_time-initial_time); // elapsed_time=elapsed_time/1000000000; // elapsed_time=elapsed_time/60; // // System.out.println("Elapsed time: "+elapsed_time+" minutes"); } /** * @return the max_number_reRuns */ public int getMax_number_reRuns() { return max_number_reRuns; } /** * @param max_number_reRuns the max_number_reRuns to set */ public void setMax_number_reRuns(int max_number_reRuns) { this.max_number_reRuns = max_number_reRuns; } /** * @return the nParticles */ public int getnParticles() { return nParticles; } /** * @param nParticles the nParticles to set */ public void setnParticles(int nParticles) { this.nParticles = nParticles; } /** * @return the best_found_fit */ public double getBest_found_fit() { return best_found_fit; } /** * @param best_found_fit the best_found_fit to set */ public void setBest_found_fit(double best_found_fit) { this.best_found_fit = best_found_fit; } /** * @return the best_found_solution */ public int[] getBest_found_solution() { return best_found_solution; } /** * @param best_found_solution the best_found_solution to set */ public void setBest_found_solution(int[] best_found_solution) { this.best_found_solution = best_found_solution; } /** * @return the history_fit */ public double[] getHistory_fit() { return history_fit; } /** * @param history_fit the history_fit to set */ public void setHistory_fit(double[] history_fit) { this.history_fit = history_fit; } public boolean isShow_gui() { return show_gui; } public void setShow_gui(boolean show_gui) { this.show_gui = show_gui; } /** * @return the nReRuns */ public int getnReRuns() { return nReRuns; } /** * @param nReRuns the nReRuns to set */ public void setnReRuns(int nReRuns) { this.nReRuns = nReRuns; } }
8,045
24.542857
173
java
cst
cst-master/src/main/java/br/unicamp/cst/learning/glas/GlasOptCreator.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.learning.glas; import org.opt4j.core.genotype.IntegerGenotype; import org.opt4j.core.problem.Creator; import com.google.inject.Inject; /** * */ /** * @author Klaus * */ public class GlasOptCreator implements Creator<IntegerGenotype> { // private int nNodes=7; // Random random = new Random(); GlasOptProblem problem; @Inject public GlasOptCreator(GlasOptProblem problem) { this.problem = problem; } public IntegerGenotype create() { IntegerGenotype genotype = problem.getGlasGenotype(); return genotype; } }
1,144
21.9
82
java
cst
cst-master/src/main/java/br/unicamp/cst/learning/glas/GlasOptDecoder.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.learning.glas; import org.opt4j.core.genotype.IntegerGenotype; import org.opt4j.core.problem.Decoder; /** * */ /** * Turns genotype into phenotype * * @author Klaus * */ public class GlasOptDecoder implements Decoder<IntegerGenotype, int[]> { @Override public int[] decode(IntegerGenotype genotype) { int nNodes=Math.round(genotype.size()/3)+1; int[] phenotype = new int[nNodes*3]; phenotype[0]=0;//First nodes always zero phenotype[nNodes]=0;//First nodes always zero phenotype[2*nNodes]=0;//First nodes always zero int index = 0; for(int i=1;i<nNodes;i++){ // tempChromossome[i] = (int) Math.round(phenotype[index]); // is rounding here ok? phenotype[i] = genotype.get(index); index++; } index = nNodes-1; for(int i=nNodes+1;i<2*nNodes;i++){ // tempChromossome[i] = (int) Math.round(phenotype[index]); // is rounding here ok? phenotype[i] = genotype.get(index); index++; } index = 2*nNodes-2; for(int i=2*nNodes+1;i<3*nNodes;i++){ // tempChromossome[i] = (int) Math.round(phenotype[index]); // is rounding here ok? phenotype[i] = genotype.get(index); index++; } return phenotype; } }
1,758
26.484375
85
java
cst
cst-master/src/main/java/br/unicamp/cst/learning/glas/GlasOptEvaluator.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.learning.glas; import java.util.ArrayList; import org.opt4j.core.Objective.Sign; import org.opt4j.core.Objectives; import org.opt4j.core.problem.Evaluator; import com.google.inject.Inject; import com.google.inject.Provider; import br.unicamp.cst.behavior.glas.GlasSequence; import br.unicamp.cst.behavior.glas.Individual; /** * http://kaskavalci.com/?p=231 */ /** * @author Klaus * */ public class GlasOptEvaluator implements Evaluator<int[]> { // static int[] known_final_solution_genotype={ 1, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 1, 1, 1, 1, 2, 2}; static int[] known_final_solution_phenotype={0, 1, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6, 0, 1, 1, 1, 1, 2, 2}; Provider<GlasSequence> provided_sequence; private GlasSequence sequence; double best_eval; private int nStimuli; private int nActions; @Inject public GlasOptEvaluator( Provider<GlasSequence> provided_sequence) { this.provided_sequence= provided_sequence; sequence = provided_sequence.get(); //Now you can access the elements! best_eval=Double.NEGATIVE_INFINITY; //For maximization nStimuli = sequence.getNStimuli(); nActions = sequence.getNActions(); } @Override public Objectives evaluate(int[] phenotype) { int nNodes=Math.round(phenotype.length/3)+1; Individual indi =new Individual(nNodes, nStimuli, nActions); indi.setChromossome(phenotype); double current_eval=indi.getFitness(sequence); if(current_eval>best_eval){ //For maximization best_eval=current_eval; } // System.out.println(current_eval); // --- Return evaluation --- Objectives objectives = new Objectives(); objectives.add("reward", Sign.MAX, current_eval); // objectives.add("scaled_tree_depth", Sign.MIN, scaled_tree_depth_penalty); // System.out.println(current_eval); return objectives; } private int getTreeDepth(int[] my_tree){ //TODO should I move this to Individual? int nNodes=Math.round(my_tree.length/3)+1; //Find leaves ArrayList<Integer> leaves = new ArrayList<Integer>(); for(int n=1;n<=nNodes;n++){ boolean isLeaf=true; for(int i=1; i<nNodes;i++){ if(my_tree[i]==n){ isLeaf=false; } } if(isLeaf){ leaves.add(n); } } //For each leaf, trace back to root int deepest=0; for(int l=0;l<leaves.size();l++){ int current_node=leaves.get(l); int depth=0; while(current_node>0) { current_node=my_tree[current_node-1]; depth++; } if(depth>deepest){ deepest=depth; } } return deepest; } }
3,120
21.292857
115
java
cst
cst-master/src/main/java/br/unicamp/cst/learning/glas/GlasOptModule.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.learning.glas; import org.opt4j.core.problem.ProblemModule; import org.opt4j.core.start.Constant; import com.google.inject.Provides; import br.unicamp.cst.behavior.glas.GlasSequence; /** * http://kaskavalci.com/?p=231 */ /** * @author Klaus * */ public class GlasOptModule extends ProblemModule { @Constant(value = "nNodes") int nNodes = 7; @Constant(value = "nStimuli") int nStimuli = 7; @Constant(value = "nActions") int nActions = 7; @Provides GlasSequence getSequence() { return sequence; } protected void config() { bindProblem(GlasOptCreator.class, GlasOptDecoder.class, GlasOptEvaluator.class); } public void setSequence(GlasSequence sequence) { this.sequence = sequence; } protected GlasSequence sequence; public int getnNodes() { return nNodes; } public void setnNodes(int nNodes) { this.nNodes = nNodes; } /** * @return the nStimuli */ public int getnStimuli() { return nStimuli; } /** * @param nStimuli the nStimuli to set */ public void setnStimuli(int nStimuli) { this.nStimuli = nStimuli; } /** * @return the nActions */ public int getnActions() { return nActions; } /** * @param nActions the nActions to set */ public void setnActions(int nActions) { this.nActions = nActions; } }
1,866
19.293478
82
java
cst
cst-master/src/main/java/br/unicamp/cst/learning/glas/GlasOptProblem.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.learning.glas; import java.util.Random; import org.opt4j.core.genotype.IntegerBounds; import org.opt4j.core.genotype.IntegerGenotype; import org.opt4j.core.start.Constant; import com.google.inject.Inject; public class GlasOptProblem { // DoubleGenotype genotype; IntegerGenotype genotype; private int nNodes; // private DoubleBounds dbs; private IntegerBounds dbs; private int nStimuli; private int nActions; private int solutionSize; @Inject public GlasOptProblem(@Constant(value = "nNodes") int nNodes, @Constant(value = "nStimuli") int nStimuli, @Constant(value = "nActions") int nActions) { this.nNodes=nNodes; // this.nStimuli=nStimuli; this.nActions=nActions; this.solutionSize=3*(nNodes-1); // int[] lower={1,1,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0}; // int[] upper={1,2,3,4,5,6, 6,6,6,6,6,6, 2,2,2,2,2,2}; int[] lower= new int[solutionSize]; int[] upper= new int[solutionSize]; // DEFINING MAX AND MIN RANGE FOR OPTIMIZATION int index=0; for(int i = 1; i<nNodes;i++){ upper[index]=i; lower[index]=1;//TODO should be 1 index++; } for(int i = 1; i<nNodes;i++){ upper[index]=nStimuli-1; lower[index]=0; index++; } for(int i = 1; i<nNodes;i++){ upper[index]=nActions-1; lower[index]=0; index++; } dbs = new IntegerBounds(lower, upper); } public IntegerGenotype getGlasGenotype() { boolean problem=false; // genotype = new DoubleGenotype(dbs); genotype = new IntegerGenotype(dbs); for(int index = 0; index< genotype.size();index++){ if(Double.isNaN(genotype.get(index))){ problem =true; } } genotype.init(new Random(), (nNodes-1)*3); for(int index = 0; index< genotype.size();index++){ if(Double.isNaN(genotype.get(index))){ problem =true; } } return genotype; } }
2,383
23.080808
152
java
cst
cst-master/src/main/java/br/unicamp/cst/learning/glas/LearnerCodelet.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.learning.glas; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import br.unicamp.cst.behavior.glas.GlasEvent; import br.unicamp.cst.behavior.glas.GlasSequence; import br.unicamp.cst.behavior.glas.GlasSequenceElements; import br.unicamp.cst.behavior.glas.Individual; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.entities.RawMemory; import br.unicamp.cst.core.exceptions.CodeletActivationBoundsException; import br.unicamp.cst.memory.WorkingStorage; /** * @author klaus * */ public class LearnerCodelet extends Codelet { ArrayList<Individual> indi_list = new ArrayList<Individual>(); private static int maxEventsSequenceLenght = Integer.MAX_VALUE; // Defines a maximum number of events that can be stored in EVENTS_SEQUENCE_MO (used mostly for experiments and debug purposes) boolean first_run=true; double goal_fitness=Double.POSITIVE_INFINITY; private Memory EVENTS_SEQUENCE_MO; private Memory SOLUTION_TREE_MO; //Holds a phenotype of the best solution until now private boolean plot_solution=false; //GlasPlot ploter =null; //TODO The algorithm should be able to find out the following variables on its own static int nNodes = 7; static int nReRuns=1; static int nActions = 1; static int nStimuli = 1; JSONArray best_solution_tree = new JSONArray(); private int last_number_of_events=0; private boolean enabled=true; private boolean printSequenceUsedForLearning=false; private boolean printLearnedSolutionTree; private int maxNumberOfSolutions=Integer.MAX_VALUE; //When learner reaches maxNumberOfSolutions, it stops learning. Used primarily for debug and experimental purposes. private int maxNumberOfNodes=10; private int minNumberOfNodes=2; private RawMemory rawMemory; public LearnerCodelet(int nStimuli, int nActions, RawMemory rawMemory, WorkingStorage ws) { this.nStimuli = nStimuli; this.nActions = nActions; this.rawMemory = rawMemory; //this.setTimeStep(0); // No waiting between reruns? if(rawMemory!=null) this.SOLUTION_TREE_MO=rawMemory.createMemoryObject("SOLUTION_TREE", ""); this.addOutput(this.SOLUTION_TREE_MO); if(ws!=null) ws.putMemoryObject(this.SOLUTION_TREE_MO); GlasOptProblem gop = new GlasOptProblem(nNodes, nStimuli, nActions); //TODO Which is better here, getting a random initial solution or a fixed standard one? // Such as: [0,1,1,1,1,1,1,0,1,2,3,4,5,6,0,1,1,1,1,1,1] // IntegerGenotype random_tree_gen = gop.getGlasGenotype(); // int[] random_tree_gen_fixed = {1,1,1,1,1,1,1,2,3,4,5,6,1,1,1,1,1,1}; int[] initial_solution_tree_int = {0,1, 0,1, 0,1}; JSONArray initial_solution_tree_json = new JSONArray(); for(int i = 0; i<initial_solution_tree_int.length;i++){ initial_solution_tree_json.put(initial_solution_tree_int[i]); } this.SOLUTION_TREE_MO.setI(initial_solution_tree_json.toString()); // [0,1,1,2,3,4,5,0,1,2,3,4,5,6,0,1,1,1,1,2,2] if(ws!=null) ws.registerCodelet(this,"EVENTS_SEQUENCE", 0); } /* (non-Javadoc) * @see br.unicamp.cogsys.core.entities.Codelet#accessMemoryObjects() */ @Override public void accessMemoryObjects() { EVENTS_SEQUENCE_MO = this.getInput("EVENTS_SEQUENCE", 0); } /* (non-Javadoc) * @see br.unicamp.cogsys.core.entities.Codelet#calculateActivation() */ @Override public void calculateActivation() { try { this.setActivation(0.0); } catch (CodeletActivationBoundsException e) { e.printStackTrace(); } } /* (non-Javadoc) * @see br.unicamp.cogsys.core.entities.Codelet#proc() */ @Override public void proc() { if(enabled){ if( (first_run || (SOLUTION_TREE_MO.getEvaluation()<this.getGoal_fitness())) && !((String)EVENTS_SEQUENCE_MO.getI()).isEmpty()){ // System.out.println("Init proc ... "); try { JSONArray sequence_json = new JSONArray(EVENTS_SEQUENCE_MO.getI()); System.out.print("."); int sequence_lenght = sequence_json.length(); //If (maxEventsSequenceLenght==Integer.MAX_VALUE), it tries to learn a new tree as soon as possible (if it has new events and previous learning is over) //TODO Increment this condition for it to start learning only if it makes a mistake? //If maxEventsSequenceLenght is a finite integer (set by the user) it waits until maxEventsSequenceLenght new events are presented to the current solution. Only then does it start learning a new sequence. if(maxEventsSequenceLenght==Integer.MAX_VALUE || (sequence_lenght-last_number_of_events)>=maxEventsSequenceLenght){ while(sequence_json.length()>maxEventsSequenceLenght){ // learns only with the last MAX_EVENTS_SEQUENCE_LENGHT events sequence_json.remove(0); } if(this.printSequenceUsedForLearning){System.out.println("");} GlasSequence mySequence = new GlasSequence(); if(this.printSequenceUsedForLearning){System.out.println("Sequence used for learning: ");} for(int e=0;e<sequence_json.length();e++){ //TODO Should be inside GlasSequence? JSONObject event_json = sequence_json.getJSONObject(e); int stim = event_json.getInt(GlasSequenceElements.SENSED_STIMULUS.toString()); int act = event_json.getInt(GlasSequenceElements.EXPECTED_ACTION.toString()); double rew = event_json.getDouble(GlasSequenceElements.REWARD_RECEIVED.toString()); // Sequence used for learning: // 0,2,0,-1.0 //TODO if(this.printSequenceUsedForLearning){System.out.println(e+","+stim+","+act+","+rew);} mySequence.addEvent(new GlasEvent(stim,act,rew)); } //TODO Store WHO acted on this sequence, and its results JSONArray solution_tree_phenotype_jsonarray = new JSONArray(SOLUTION_TREE_MO.getI()); int[] solution_tree_phenotype_int = new int[solution_tree_phenotype_jsonarray.length()]; for(int i=0; i<solution_tree_phenotype_jsonarray.length();i++){ solution_tree_phenotype_int[i]=solution_tree_phenotype_jsonarray.getInt(i); } int[] genotype_int = this.getGenotypeFromPhenotype(solution_tree_phenotype_int); int nNodesIndi = (solution_tree_phenotype_int.length/3); Individual indi =new Individual(nNodesIndi, nStimuli, nActions); indi.setChromossome(genotype_int); double max_fit = this.getMaxFitnessForSequence(mySequence); double fit = indi.getFitness(mySequence); indi.setNormalizedFitness(fit/max_fit); indi_list.add(indi); if(this.printLearnedSolutionTree){ // System.out.println(""); System.out.print(fit+","); System.out.print(fit/max_fit+","); System.out.print(nNodesIndi+","); for(int i=0; i<genotype_int.length;i++){ System.out.print(genotype_int[i]+","); } System.out.print(indi_list.size()); System.out.println(""); } //LEARNING PHASE System.out.println("I just started learning from a new sequence..."); int[] temp_best_found_int = {1,1,1}; double temp_best_found_fit = Double.NEGATIVE_INFINITY; double normalized_fitness = Double.NEGATIVE_INFINITY; GlasLearner myLearner = new GlasLearner(nNodes, nStimuli, nActions); for(int local_nNodes =minNumberOfNodes; local_nNodes<=maxNumberOfNodes; local_nNodes++){ myLearner = new GlasLearner(local_nNodes, nStimuli, nActions); boolean show_gui = false; myLearner.setShow_gui(show_gui); myLearner.setnReRuns(nReRuns); // int max_number_reRuns=500; //int max_number_reRuns=500; // int nParticles = 1000; //int nParticles = 1000; // myLearner.setMax_number_reRuns(max_number_reRuns); // myLearner.setnParticles(nParticles); // myLearner.learnSequence(mySequence); // if(myLearner.getBest_found_fit()>temp_best_found_fit){ temp_best_found_int = myLearner.getBest_found_solution(); temp_best_found_fit = myLearner.getBest_found_fit(); } if(this.printLearnedSolutionTree){ double temp_max_fit = this.getMaxFitnessForSequence(mySequence); // System.out.println(""); System.out.print(temp_best_found_fit+","); normalized_fitness=temp_best_found_fit/temp_max_fit; System.out.print(normalized_fitness+","); System.out.print(local_nNodes+","); for(int i=0; i<temp_best_found_int.length-1;i++){ System.out.print(temp_best_found_int[i]+","); } System.out.println(temp_best_found_int[temp_best_found_int.length-1]); } } System.out.println("...finished learning."); int[] best_found_int = temp_best_found_int; //TODO Unnecessary? int[] new_solution_tree_int = this.getPhenotypeFromGenotype(best_found_int); double best_found_fit = temp_best_found_fit; //TODO Unnecessary? best_solution_tree = new JSONArray(); for(int i=0;i<new_solution_tree_int.length;i++){ best_solution_tree.put(new_solution_tree_int[i]); } SOLUTION_TREE_MO.setI(best_solution_tree.toString()); // SOLUTION_TREE_MO.setEvaluation(best_found_fit); SOLUTION_TREE_MO.setEvaluation(normalized_fitness); first_run=false; // } if(SOLUTION_TREE_MO.getEvaluation()>=this.getGoal_fitness()){ System.out.println("Found goal fitness = "+SOLUTION_TREE_MO.getEvaluation()); } if(plot_solution){ double[] best_found_double=new double[best_found_int.length]; for(int i=0;i<best_found_double.length;i++){ best_found_double[i]=((double)best_found_int[i]); } double[] sol = new double[nNodes*3]; int count=0; for(int i=0;i<sol.length;i++){ if((i%nNodes)==0){ sol[i]=0; }else{ sol[i]=best_found_double[count]; count++; } } // ploter = new GlasPlot(sol); // ploter.plot(); } sequence_json = new JSONArray(EVENTS_SEQUENCE_MO.getI()); last_number_of_events=sequence_json.length(); // System.out.println("##########################################"); } //if(sequence_json.length()>=MAX_EVENTS_SEQUENCE_LENGHT) } catch (JSONException e) { System.out.println("This should not happen! (at LearnerCodelet)"); e.printStackTrace(); } } if(indi_list.size()>=this.maxNumberOfSolutions){ System.out.println("Stopped learning."); this.setEnabled(false); } }else{//if enabled // System.out.println("Learning is halted."); //Do nothing } }//proc private int[] getPhenotypeFromGenotype(int[] genotype) { int number_of_nodes = (genotype.length/3)+1; int[] solution_tree_phenotype = new int[number_of_nodes*3]; int count=0; solution_tree_phenotype[count]=0; count++; for(int i = 0; i < genotype.length/3; i++){ solution_tree_phenotype[count]=genotype[i]; count++; } solution_tree_phenotype[count]=0; count++; for(int i = genotype.length/3; i < 2*genotype.length/3; i++){ solution_tree_phenotype[count]=genotype[i]; count++; } solution_tree_phenotype[count]=0; count++; for(int i = 2*genotype.length/3; i < 3*genotype.length/3; i++){ solution_tree_phenotype[count]=genotype[i]; count++; } return solution_tree_phenotype; } private double getMaxFitnessForSequence(GlasSequence mySequence) { double max_fit = 0; ArrayList<GlasEvent> events = mySequence.getEvents(); for(GlasEvent event : events){ max_fit=max_fit+Math.abs(event.getReward()); } return max_fit; } public double getGoal_fitness() { return goal_fitness; } public void setGoalFitness(double goal_fitness) { this.goal_fitness = goal_fitness; } /** * @return the maxEventsSequenceLenght */ public static int getMaxEventsSequenceLenght() { return maxEventsSequenceLenght; } /** * @param Max_Events_Sequence_Lenght the Max_Events_Sequence_Lenght to set */ public void setMaxEventsSequenceLenght(int Max_Events_Sequence_Lenght) { maxEventsSequenceLenght = Max_Events_Sequence_Lenght; } public int[] getGenotypeFromPhenotype(int[] phenotype) { int number_of_nodes=Math.round(phenotype.length/3); int[] genotype = new int[(number_of_nodes-1)*3]; int count=0; for(int i = 1; i<number_of_nodes;i++){ genotype[count]=phenotype[i]; count++; } for(int i = number_of_nodes+1; i<2*number_of_nodes;i++){ genotype[count]=phenotype[i]; count++; } for(int i = 2*number_of_nodes+1; i<3*number_of_nodes;i++){ genotype[count]=phenotype[i]; count++; } return genotype; } /** * @return the enabled */ public boolean isEnabled() { return enabled; } /** * @param enabled the enabled to set */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * @return the nNodes */ public static int getnNodes() { return nNodes; } /** * @param nNodes the nNodes to set */ public static void setnNodes(int nNodes) { LearnerCodelet.nNodes = nNodes; } /** * @return the nActions */ public static int getnActions() { return nActions; } /** * @param nActions the nActions to set */ public static void setnActions(int nActions) { LearnerCodelet.nActions = nActions; } /** * @return the nStimuli */ public static int getnStimuli() { return nStimuli; } /** * @param nStimuli the nStimuli to set */ public static void setnStimuli(int nStimuli) { LearnerCodelet.nStimuli = nStimuli; } /** * @return the nReRuns */ public static int getnReRuns() { return nReRuns; } /** * @param nReRuns the nReRuns to set */ public static void setnReRuns(int nReRuns) { LearnerCodelet.nReRuns = nReRuns; } /** * @return the printLearnedSolutionTree */ public boolean isPrintLearnedSolutionTree() { return printLearnedSolutionTree; } /** * @param printLearnedSolutionTree the printLearnedSolutionTree to set */ public void setPrintLearnedSolutionTree(boolean printLearnedSolutionTree) { this.printLearnedSolutionTree = printLearnedSolutionTree; } /** * @return the printSequenceUsedForLearning */ public boolean isPrintSequenceUsedForLearning() { return printSequenceUsedForLearning; } /** * @param printSequenceUsedForLearning the printSequenceUsedForLearning to set */ public void setPrintSequenceUsedForLearning(boolean printSequenceUsedForLearning) { this.printSequenceUsedForLearning = printSequenceUsedForLearning; } /** * @return the maxNumberOfSolutions */ public int getMaxNumberOfSolutions() { return maxNumberOfSolutions; } /** * @param maxNumberOfSolutions the maxNumberOfSolutions to set */ public void setMaxNumberOfSolutions(int maxNumberOfSolutions) { this.maxNumberOfSolutions = maxNumberOfSolutions; } /** * @return the maxNumberOfNodes */ public int getMaxNumberOfNodes() { return maxNumberOfNodes; } /** * Higher bound for number of nodes the solution tree can have. * Must be: minNumberOfNodes less or equal maxNumberOfNodes * Default: maxNumberOfNodes equals 10 * * Warning: Large values of maxNumberOfNodes might make learning too slow * @param maxNumberOfNodes the maxNumberOfNodes to set */ public void setMaxNumberOfNodes(int maxNumberOfNodes) { if(maxNumberOfNodes>=minNumberOfNodes){ this.maxNumberOfNodes = maxNumberOfNodes; } } /** * Lower bound for number of nodes the solution tree can have. * Must be: minNumberOfNodes less or equals 1 and minNumberOfNodes less or equals maxNumberOfNodes * Default: minNumberOfNodes equals 1 * @return the minNumberOfNodes */ public int getMinNumberOfNodes() { return minNumberOfNodes; } // /** //TODO Verify the utility for this method.. // * Lower bound for number of nodes the solution tree can assume. // * Must be: minNumberOfNodes>=2 and minNumberOfNodes<= maxNumberOfNodes // * Default: minNumberOfNodes=2 // * // * @param minNumberOfNodes the minNumberOfNodes to set // */ // public void setMinNumberOfNodes(int minNumberOfNodes) { // if(minNumberOfNodes>=2 && minNumberOfNodes<= maxNumberOfNodes){ // this.minNumberOfNodes = minNumberOfNodes; // // // // int[] random_tree_gen_fixed = new int[(minNumberOfNodes-1)*3]; // int count=1; // for(int i=0;i<(minNumberOfNodes-1)*3;i++){ // if(i<(minNumberOfNodes-1) || i>=2*(minNumberOfNodes-1)){ // random_tree_gen_fixed[i]=1; // }else{ // random_tree_gen_fixed[i]=count; // count++; // } // } // // // JSONArray initial_solution_tree = new JSONArray(); // // for(int i = 0; i<random_tree_gen_fixed.length;i++){ // initial_solution_tree.put(random_tree_gen_fixed[i]); // } // // this.SOLUTION_TREE_MO.updateInfo(initial_solution_tree.toString()); // // // } // } }
17,565
26.234109
209
java
cst
cst-master/src/main/java/br/unicamp/cst/memory/BehaviorProposition.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation * E. M. Froes - documentation ******************************************************************************/ package br.unicamp.cst.memory; import java.util.ArrayList; import java.util.List; /** * This is an object used to store a behavior proposition, composed by the behavior's name, its add list and delete list. * It is useful to build strings with this information for memory objects. * @author klaus * */ public class BehaviorProposition { private String name; private ArrayList<String> addList=new ArrayList<String>(); private ArrayList<String> delList=new ArrayList<String>(); private ArrayList<String> actionList=new ArrayList<String>(); private boolean performed; //defines if the memory object holding this information has been used or not private String behaviorPropositionString; /** * Constructor that initializes all attributes and composes "behaviorPropositionString". * @param name the name of the behavior proposition * @param addList add-list of strings to add * @param delList del-list of strings to delete * @param actionList list of actions */ public BehaviorProposition(String name, ArrayList<String> addList, ArrayList<String> delList,ArrayList<String> actionList){ this.name=name; this.addList.addAll(addList); this.delList.addAll(delList); this.performed=false; this.actionList=actionList; createBehaviorPropositionString(); } /** * Constructor receive the "behaviorPropositionString" String as parameter and initialize all attributes of class. * @param behaviorPropositionString the string with the behavior proposition */ public BehaviorProposition(String behaviorPropositionString){ this.behaviorPropositionString=behaviorPropositionString; createBehaviorPropositions(); } /** * This method return action list. * @return List of Actions */ public ArrayList<String> getActionList() { return actionList; } /** * This method set action list. * @param actionList the actionList to be set */ public void setActionList(ArrayList<String> actionList) { this.actionList = actionList; } /** * This method is responsible for initializing the attributes of the class from "behaviorPropositionString". */ private void createBehaviorPropositions() { String[] tempString; tempString=behaviorPropositionString.split("<NAME>"); if((tempString!=null)&&(tempString.length>1)){ //unnecessary check this.name=tempString[1]; }else{this.name=null;} tempString=behaviorPropositionString.split("<PERFORMED>"); //unnecessary check if((tempString!=null)&&(tempString.length>1)){ if(tempString[1].equals("true")){performed=true;} else {performed=false;} //TODO could there be a problem here in case recorded data were corrupted? }else{performed=false;}//without other information, i assume it was not used tempString=behaviorPropositionString.split("<DELLIST>"); if((tempString!=null)&&(tempString.length>1)){ tempString=tempString[1].substring(0, tempString[1].length()-1).split(",");//Exception in thread "Thread-12" java.lang.ArrayIndexOutOfBoundsException: 1 this.delList.clear(); for(String prop:tempString){ this.delList.add(prop); } }else{this.delList=null;} tempString=behaviorPropositionString.split("<ADDLIST>"); if((tempString!=null)&&(tempString.length>1)){ tempString=tempString[1].substring(0, tempString[1].length()-1).split(","); this.addList.clear(); for(String prop:tempString){ this.addList.add(prop); } }else{this.addList=null;} tempString=behaviorPropositionString.split("<ACTIONLIST>"); if((tempString!=null)&&(tempString.length>1)){ tempString=tempString[1].substring(0, tempString[1].length()-1).split(","); this.actionList.clear(); for(String prop:tempString){ this.actionList.add(prop); } }else{this.actionList=null;} } /** * This method is responsible for composing the "behaviorPropositionString" from the attributes of class. */ private void createBehaviorPropositionString() { behaviorPropositionString=""; behaviorPropositionString=behaviorPropositionString+"<NAME>"+this.getName()+"<NAME>"; //TODO THis is not standard XML behaviorPropositionString=behaviorPropositionString+"<PERFORMED>"+String.valueOf(performed)+"<PERFORMED>"; if((addList!=null)&&(!addList.isEmpty())){ behaviorPropositionString=behaviorPropositionString+"<ADDLIST>"; for(String add:addList){ behaviorPropositionString=behaviorPropositionString+add+","; } behaviorPropositionString=behaviorPropositionString+"<ADDLIST>"; } if((delList!=null)&&(!delList.isEmpty())){ behaviorPropositionString=behaviorPropositionString+"<DELLIST>"; for(String del:delList){ behaviorPropositionString=behaviorPropositionString+del+","; } behaviorPropositionString=behaviorPropositionString+"<DELLIST>"; } if((actionList!=null)&&(!actionList.isEmpty())){ behaviorPropositionString=behaviorPropositionString+"<ACTIONLIST>"; for(String action:actionList){ behaviorPropositionString=behaviorPropositionString+action+","; } behaviorPropositionString=behaviorPropositionString+"<ACTIONLIST>"; } } /** * This method set the behavior proposition string. * @param behaviorPropositionString the behaviorPropositionString to set */ public synchronized void setBehaviorPropositionString(String behaviorPropositionString) { this.behaviorPropositionString = behaviorPropositionString; createBehaviorPropositions();//updates the variables based on the new string } /** * This method return the behavior proposition string. * @return behavior proposition string. */ public synchronized String getBehaviorPropositionString(){ return this.behaviorPropositionString; } /** * This return name. * @return name. */ public synchronized String getName() { return this.name; } /** * Return if the bp was performed or not. * @return was performed or not */ public boolean isPerformed() { return performed; } /** * This, set performed attribute and composes the behavior proposition string from attributes of class. * @param performed defines if the Proposition was performed or not */ public void setPerformed(boolean performed) { //System.out.println("##### Trying to set performed to "+performed+" ########"); //System.out.println("Before: performed = "+this.performed+" string: "+this.behaviorPropositionString); this.performed = performed; createBehaviorPropositionString(); //Updates the variables in the string //System.out.println("After: performed = "+this.performed+" string: "+this.behaviorPropositionString); //System.out.println("#######################################"); } /** * Return the addList. * @return addList. */ public List<String> getAddList() { return this.addList; } /** * Set the add list. * @param addList the addList to set */ public void setAddList(ArrayList<String> addList) { this.addList = addList; } /** * Return the delete list. * @return the delList */ public List<String> getDelList() { return delList; } /** * This, set the delete list. * @param delList the delList to set */ public void setDelList(ArrayList<String> delList) { this.delList = delList; } /** * Set name of Behavior Proposition. * @param name the name to set */ public synchronized void setName(String name) { this.name = name; } }
8,185
31.613546
155
java
cst
cst-master/src/main/java/br/unicamp/cst/memory/EpisodicMemory.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.memory; /** * Created by du on 19/12/16. */ public class EpisodicMemory { }
651
35.222222
82
java
cst
cst-master/src/main/java/br/unicamp/cst/memory/LongTermMemory.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation * E. M. Froes - documentation ******************************************************************************/ package br.unicamp.cst.memory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.ArrayList; import br.unicamp.cst.core.entities.MemoryObject; import br.unicamp.cst.core.entities.RawMemory; /** * This long term memory is responsible for providing access to stored knowledge * @author klaus * */ public class LongTermMemory { private ArrayList<MemoryObject> ltmMOs = new ArrayList<MemoryObject>(); private static String path = "LongTermMemory/"; private RawMemory rawMemory; /** * Default constructor. * @param rawMemory */ public LongTermMemory(RawMemory rawMemory) { this.rawMemory = rawMemory; //learnedPropositions = new ConcurrentHashMap<String,MemoryObject>(); boolean success = (new File("LongTermMemory")).mkdirs(); } /** * This method receive a object "File" as parameter and return the contents of the file in a byte array. * @param file the file to get bytes from * @return byte[] array of bytes taken from the file. * @throws IOException IOException */ public static byte[] getBytesFromFile(File file) throws IOException { InputStream is = new FileInputStream(file); // Get the size of the file long length = file.length(); // You cannot create an array using a long type. // It needs to be an int type. // Before converting to an int type, check // to ensure that file is not larger than Integer.MAX_VALUE. if (length > Integer.MAX_VALUE) { // File is too large } // Create the byte array to hold the data byte[] bytes = new byte[(int)length]; // Read in the bytes int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { offset += numRead; } // Ensure all the bytes have been read in if (offset < bytes.length) { throw new IOException("Could not completely read file "+file.getName()); } // Close the input stream and return bytes is.close(); return bytes; } /** * * Avoids cloning. */ public Object clone() throws CloneNotSupportedException{ throw new CloneNotSupportedException(); } /** * Stores Information of a given type in long term memory. * /TODO At this moment, long term memory is persisted in a json file in hard disk. This should be changed to use a DB such as postgre or mysql. * * @param mo */ public void learn(MemoryObject mo) { MemoryObject hasMemory=this.checksIfMemoryExists(mo.getName(),mo.getI()); if(hasMemory==null){ //doesn't exist yet int endIndex = ((String)mo.getI()).length(); if(endIndex>8){endIndex=8;} String filename=mo.getName()+"_"+((String)mo.getI()).substring(0, endIndex)+"_"+mo.getTimestamp().toString().replace(":", "-"); String extension=".mo"; //SERIALIZE try { // Serialize to a file ObjectOutput out = new ObjectOutputStream(new FileOutputStream(path+filename+extension)); out.writeObject(mo); out.close(); // Serialize to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream() ; out = new ObjectOutputStream(bos) ; out.writeObject(mo); out.close(); // Get the bytes of the serialized object byte[] buf = bos.toByteArray(); } catch (IOException e) { System.out.println("Couldn't create file with serialized memory object."); } } } /** * Searches in persisted long term memory if this memory object already exists. * The criteria are its type and info. * @param type * @param info * @return the existing memory object, or null if there aren't any. */ private MemoryObject checksIfMemoryExists(String type, Object info) { MemoryObject ltmMO=null; File pathName = new File(path); // gets the element at the index of the List String[] fileNames = pathName.list(); // lists all files in the directory if(fileNames!=null){ for(int i = 0; i < fileNames.length; i++) { File f = new File(pathName.getPath(), fileNames[i]); // getPath converts abstract path to path in String, if (!f.isDirectory()) { // System.out.println(f.getCanonicalPath()); MemoryObject recoveredMO=this.deserializeMO(f); if(type.equalsIgnoreCase(recoveredMO.getName()) && info.equals(recoveredMO.getI())){ ltmMO=recoveredMO; break; } } } if(ltmMO!=null) { if(rawMemory!=null) rawMemory.addMemory(ltmMO); } } return ltmMO; } /** * Reads a memory object from disk. * @param file * @return memory object. */ private MemoryObject deserializeMO(File file){ //DESERIALIZE MemoryObject mo2=null; try { // Deserialize from a file //File file = new File(path+filename+extension); ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // Deserialize the object mo2 = (MemoryObject) in.readObject(); in.close(); // Get some byte array data byte[] bytes = getBytesFromFile(file); // see Reading a File into a Byte Array for the implementation of this method // Deserialize from a byte array in = new ObjectInputStream(new ByteArrayInputStream(bytes)); mo2 = (MemoryObject) in.readObject(); in.close(); } catch (ClassNotFoundException e) { System.out.println("Could not deserialize memory object from long term memory."); } catch (IOException e) { System.out.println("Could not deserialize memory object from long term memory."); } return mo2; } /** * Retrieves from long term memory a given type and info of memory object. * It first looks for it in the memory objects already loaded in ram LTM. * If it fails to find it, it then looks for it on disk. * @param type * @param info * @return memory object. */ public MemoryObject retrieve(String type, String info) { MemoryObject retrievedMO=null; boolean isInRAM=false; //Check if has already been loaded for(MemoryObject ramMO:this.ltmMOs){ if(ramMO.getName().equalsIgnoreCase(type) && ramMO.getI().equals(info)){ retrievedMO=ramMO; isInRAM=true; break; } } if(!isInRAM){//Couldn't find in ram, look for it in disk retrievedMO=this.checksIfMemoryExists(type,info); if(retrievedMO!=null){ ltmMOs.add(retrievedMO); } } return retrievedMO; } /** * WARNING: * Clears everything from LTM, both from ram and disk. * Use with extreme care! */ public void totalClearLTM() { File f = new File(path); // gets the element at the index of the List File[] lista = f.listFiles(); //System.out.println(lista); if(lista!=null){ for (File c : f.listFiles()) //Cleans up directory for other tests c.delete(); } } /** * Prints all active content in ltm. */ public void printLTM(){ System.out.println("LTM Active Content: "+ltmMOs); } /** * Clears LTM from memory. */ public void shutDown() { this.ltmMOs.clear(); } }
7,773
27.372263
147
java
cst
cst-master/src/main/java/br/unicamp/cst/memory/WorkingStorage.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.memory; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.entities.RawMemory; import br.unicamp.cst.core.entities.Subject; /** * "In the brain, working storage is believed to involve the medial * temporal cortex and prefrontal regions. Working storage is dynamic- * i.e. it involves active populations of neurons called cell * assemblies, which can 'crystalize' into permanent memories."[Baars and Gage 2010] * * @author klaus raizer */ public class WorkingStorage implements Subject { private HashMap<Codelet,HashMap<String,List<Memory>>> what_ws_sent_to_codelets_inputs = new HashMap<Codelet, HashMap<String,List<Memory>>>(); private HashMap<Codelet,HashMap<String,List<Memory>>> what_ws_sent_to_codelets_outputs = new HashMap<Codelet, HashMap<String,List<Memory>>>(); private HashMap<String, List<Codelet>> codelet_input_registry_by_type = new HashMap<String,List<Codelet>>(); private HashMap<String, List<Codelet>> codelet_output_registry_by_type = new HashMap<String,List<Codelet>>(); private HashMap<String,ArrayList<Memory>> workingStorageContents = new HashMap<String, ArrayList<Memory>>(); private ArrayList<Memory> workingStorageContentList = new ArrayList<Memory>(); private int maxCapacity; private boolean useHashMap=false; private RawMemory rawMemory; public WorkingStorage(int maxCapacity,RawMemory rawMemory) { this.rawMemory = rawMemory; setMaxCapacity(maxCapacity); } /** * * Avoids cloning */ public Object clone() throws CloneNotSupportedException{ throw new CloneNotSupportedException(); } /** * Returns a list of all memory objects of a given type. * @param type of the wished memory objects * @return list of memory objects to be returned */ public synchronized ArrayList<Memory> getAllOfType(String type){ ArrayList<Memory> allOfType=new ArrayList<Memory>(); if(useHashMap){ ArrayList<Memory> temp=workingStorageContents.get(type); if(temp!=null){ allOfType.addAll(workingStorageContents.get(type)); } }else{ for(Memory mo:workingStorageContentList){ if(mo.getName().equalsIgnoreCase(type)){ allOfType.add(mo); } } } //System.out.println("ALL OF TYPE new: "+allOfType); return allOfType; } /** * @param maxCapacity the maxCapacity to set */ public void setMaxCapacity(int maxCapacity) { this.maxCapacity = maxCapacity; } /** * @return the maxCapacity */ public int getMaxCapacity() { return maxCapacity; } /** * Prints all memory objects in Working Storage, organized by TYPE. */ public synchronized void printStatus() { ArrayList<Memory> allMOs=this.getAll(); HashMap<String,ArrayList<Memory>> organizedMOs= new HashMap<String,ArrayList<Memory>>(); for(Memory mo : allMOs){ String key = mo.getName(); if(organizedMOs.containsKey(key)){ organizedMOs.get(key).add(mo); }else{ ArrayList<Memory> newList = new ArrayList<Memory>(); newList.add(mo); organizedMOs.put(key, newList); } } System.out.println("###### Working Storage ########"); System.out.println("# Number of Memory Objects: "+allMOs.size()); // System.out.println(allMOs); Iterator it = organizedMOs.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); System.out.println("--- Type: "+pairs.getKey()+" ---"); ArrayList<Memory> listaMOs=(ArrayList<Memory>) pairs.getValue(); for(Memory mo: listaMOs){ System.out.println(mo); } } System.out.println("###############################"); } /** * @return All memory objects in Working Storage */ public synchronized ArrayList<Memory> getAll() { ArrayList<Memory> allMOs=new ArrayList<Memory>(); allMOs.addAll(workingStorageContentList); return allMOs; } public synchronized boolean contains(Memory mo) { String type = mo.getName(); ArrayList<Memory> allOfType = this.getAllOfType(type); boolean contains=false; if(allOfType!=null){ contains=allOfType.contains(mo); }else{ contains=false; //not needed } return contains; } /** * Adds a memory object to working storage * @param mo one memory object to be added */ public synchronized void putMemoryObject(Memory mo) { if((mo!=null)){//TODO should i get rid of older content? // boolean not_contain_old = !workingStorageContentList.contains(mo); //Compares by content! boolean not_contain=true; ArrayList<Memory> tempList= new ArrayList<Memory>(); tempList.addAll(workingStorageContentList); for(Memory oldMo:tempList){ if(oldMo==mo){ not_contain=false; } } if(not_contain){//TODO This is not working properlly! workingStorageContentList.add(mo); // System.out.println("Trying to add: "+mo); //In update, I must check if this type of mo should be sent to any registered codelet // if so, I need to take note at what_ws_sent_to_codelets String type = mo.getName(); if(codelet_input_registry_by_type.containsKey(type)){ List<Codelet> setOfCodelets = codelet_input_registry_by_type.get(type); updateCodeletsList(setOfCodelets,type,0); } if(codelet_output_registry_by_type.containsKey(type)){ List<Codelet> setOfCodelets = codelet_output_registry_by_type.get(type); updateCodeletsList(setOfCodelets,type,1); } } } } private synchronized void updateCodeletsList(List<Codelet> setOfCodelets,String type, int io) { //TODO remember to acquire lock! List<Memory> sentLista=null; for(Codelet co : setOfCodelets){ List<Memory> lista=null; if(io==0){//update inputs lista=co.getInputs(); if(what_ws_sent_to_codelets_inputs.containsKey(co)){ HashMap<String, List<Memory>> listOfTypes = what_ws_sent_to_codelets_inputs.get(co); if(listOfTypes.containsKey(type)){ sentLista = what_ws_sent_to_codelets_inputs.get(co).get(type); } }else{ HashMap<String, List<Memory>> listOfTypes = new HashMap<String, List<Memory>>(); sentLista = new ArrayList<Memory>(); listOfTypes.put(type, sentLista); what_ws_sent_to_codelets_inputs.put(co, listOfTypes); } }else if(io==1){//update outputs lista=co.getOutputs(); if(what_ws_sent_to_codelets_outputs.containsKey(co)){ HashMap<String, List<Memory>> listOfTypes = what_ws_sent_to_codelets_outputs.get(co); if(listOfTypes.containsKey(type)){ sentLista = what_ws_sent_to_codelets_outputs.get(co).get(type); } }else{ HashMap<String, List<Memory>> listOfTypes = new HashMap<String, List<Memory>>(); sentLista = new ArrayList<Memory>(); listOfTypes.put(type, sentLista); what_ws_sent_to_codelets_outputs.put(co, listOfTypes); } }else{ throw new IllegalArgumentException(); } ArrayList<Memory> whats_missing = new ArrayList<Memory>(); whats_missing.addAll(this.getAllOfType(type)); whats_missing.removeAll(lista); if(io==0){//update inputs co.addInputs(whats_missing); }else if(io==1){//update outputs co.addOutputs(whats_missing); }else{ throw new IllegalArgumentException(); } sentLista.addAll(whats_missing);//recording what was sent to codelets } } /** * Removes this memory object from Working Storage if it is there, but keeps it in Raw Memory. * Be careful when using this! * @param mo */ public synchronized void removeFromWorkingStorageWithoutDelete(Memory mo) { // System.out.println("--> Working storage before removal: "+this.getAll()); workingStorageContentList.remove(mo); // Must also remove from registered codelet's lists //If I do so, check if I was responsible for putting it there in the first place, by looking at what_ws_sent_to_codelets //Only then should I remove it from the codelet's IO list // (if it was not in what_ws_sent_to_codelets, then it is not my responsibility to remove it) String type=mo.getName(); if(codelet_input_registry_by_type.containsKey(type)){ List<Codelet> codelets = codelet_input_registry_by_type.get(type); //TODO preciso fazer um loop aqui // private HashMap<Codelet,HashMap<MemoryObjectType,List<Memory>>> what_ws_sent_to_codelets_inputs = new HashMap<Codelet, HashMap<MemoryObjectType,List<Memory>>>(); // private HashMap<Codelet,HashMap<MemoryObjectType,List<Memory>>> what_ws_sent_to_codelets_outputs = new HashMap<Codelet, HashMap<MemoryObjectType,List<Memory>>>(); for(Codelet co :codelets){ if(what_ws_sent_to_codelets_inputs.containsKey(co)){ HashMap<String, List<Memory>> listOfTypes = what_ws_sent_to_codelets_inputs.get(co); if(listOfTypes.containsKey(type)){ List<Memory> mos = listOfTypes.get(type); List<Memory> tempMo= new ArrayList<Memory>(); tempMo.add(mo); co.removeFromInput(tempMo); mos.remove(mo); } } } } if(codelet_output_registry_by_type.containsKey(type)){ List<Codelet> codelets = codelet_output_registry_by_type.get(type); for(Codelet co :codelets){ if(what_ws_sent_to_codelets_outputs.containsKey(co)){ HashMap<String, List<Memory>> listOfTypes = what_ws_sent_to_codelets_outputs.get(codelets); if(listOfTypes!=null && listOfTypes.containsKey(type)){ List<Memory> mos = listOfTypes.get(type); List<Memory> tempMo= new ArrayList<Memory>(); tempMo.add(mo); co.removeFromOutput(tempMo); mos.remove(mo); } } } } } /** * WARNING! * Removes this memory object from Working Storage if it is there, and also removes it from Raw Memory * @param bpMo */ public synchronized void removeFromWorkingStorageWithDelete(Memory bpMo) { workingStorageContentList.remove(bpMo); if(rawMemory!=null) rawMemory.destroyMemoryObject(bpMo); } /** * Removes all memory objects from Working Memory and delete them from raw memory. * Be careful when using this method! */ public void clearWithDelete() { if(rawMemory!=null && workingStorageContentList!=null) for(Memory mo: workingStorageContentList) { rawMemory.destroyMemoryObject(mo); } this.workingStorageContentList.clear(); } // public enum IO{ // INPUT, // OUTPUT; // } @Override public void registerCodelet(Codelet co, String type, int io) { // IO ioList; if(io==0){ // ioList = IO.INPUT; if(codelet_input_registry_by_type.containsKey(type)){ List<Codelet> setOfCodelets = codelet_input_registry_by_type.get(type); setOfCodelets.add(co); }else{ List<Codelet> setOfCodelets = new ArrayList<Codelet>(); setOfCodelets.add(co); codelet_input_registry_by_type.put(type, setOfCodelets); } }else if(io==1){ // ioList = IO.OUTPUT; if(codelet_output_registry_by_type.containsKey(type)){ List<Codelet> setOfCodelets = codelet_output_registry_by_type.get(type); setOfCodelets.add(co); }else{ List<Codelet> setOfCodelets = new ArrayList<Codelet>(); setOfCodelets.add(co); codelet_output_registry_by_type.put(type, setOfCodelets); } }else{ throw new IllegalArgumentException(); } // //TODO I need to look for memory objects that are already in working storage and add them to the newly registered codelet // ArrayList<Memory> allOfType = new ArrayList<Memory>(); // // allOfType.addAll(this.getAllOfType(type)); // //TODO Get a lock here? // // ArrayList<Codelet> setOfCodelets = new ArrayList<Codelet>(); // setOfCodelets.add(co); // updateCodeletsList(setOfCodelets,type,io); // //I need to look for memory objects that are already in working storage and add them to the newly registered codelet //After that, I need to register those memory objects at what_ws_sent_to_codelets_inputs or what_ws_sent_to_codelets_outputs. ArrayList<Memory> allOfType = new ArrayList<Memory>(); allOfType.addAll(this.getAllOfType(type)); //TODO Get a lock here? if(io==0){ allOfType.removeAll(co.getInputs()); co.addInputs(allOfType); //Adding to codelet if(what_ws_sent_to_codelets_inputs.containsKey(co)){ HashMap<String, List<Memory>> temp = what_ws_sent_to_codelets_inputs.get(co); if(temp.containsKey(type)){ List<Memory> temp2 = temp.get(type); temp2.addAll(allOfType); }else{ List<Memory> temp2 = new ArrayList<Memory>(); temp2.addAll(allOfType); temp.put(type,temp2); } }else{ HashMap<String, List<Memory>> temp = new HashMap<String, List<Memory>>(); List<Memory> temp2 = new ArrayList<Memory>(); temp2.addAll(allOfType); temp.put(type,temp2); what_ws_sent_to_codelets_inputs.put(co, temp); } } if(io==1){ allOfType.removeAll(co.getOutputs());//TODO WEIRD!! It is removing something that doesn't exist! co.addOutputs(allOfType); //Adding to codelet if(what_ws_sent_to_codelets_outputs.containsKey(co)){ HashMap<String, List<Memory>> temp = what_ws_sent_to_codelets_outputs.get(co); if(temp.containsKey(type)){ List<Memory> temp2 = temp.get(type); temp2.addAll(allOfType); }else{ List<Memory> temp2 = new ArrayList<Memory>(); temp2.addAll(allOfType); temp.put(type,temp2); } }else{ HashMap<String, List<Memory>> temp = new HashMap<String, List<Memory>>(); List<Memory> temp2 = new ArrayList<Memory>(); temp2.addAll(allOfType); temp.put(type,temp2); what_ws_sent_to_codelets_outputs.put(co, temp); } } // // //These hashmaps keep track of which memory objects Working Storage is responsible for sending to a given codelet. // private HashMap<Codelet,HashMap<MemoryObjectType,List<Memory>>> what_ws_sent_to_codelets_inputs = new HashMap<Codelet, HashMap<MemoryObjectType,List<Memory>>>(); // private HashMap<Codelet,HashMap<MemoryObjectType,List<Memory>>> what_ws_sent_to_codelets_outputs = new HashMap<Codelet, HashMap<MemoryObjectType,List<Memory>>>(); // // //These hashmaps keep a registry of what codelets are registered to receive a given type of memory object. One hashmap keeps track of input lists, and the other of output lists. // private HashMap<MemoryObjectType, List<Codelet>> codelet_input_registry_by_type = new HashMap<MemoryObjectType,List<Codelet>>(); // private HashMap<MemoryObjectType, List<Codelet>> codelet_output_registry_by_type = new HashMap<MemoryObjectType,List<Codelet>>(); // // // } @Override public void unregisterCodelet(Codelet co, String type, int io) { if(io==0){ // ioList = IO.INPUT; if(codelet_input_registry_by_type.containsKey(type)){ codelet_input_registry_by_type.get(type).remove(co); HashMap<String, List<Memory>> reg0 = what_ws_sent_to_codelets_inputs.get(co); List<Memory> setOfInputMOs = reg0.get(type); co.removeFromInput((List<Memory>) setOfInputMOs); reg0.remove(type); }else{ //nothing here to be removed } }else if(io==1){ // ioList = IO.OUTPUT; if(codelet_output_registry_by_type.containsKey(type)){ what_ws_sent_to_codelets_outputs.get(type).remove(co); HashMap<String, List<Memory>> reg1 = what_ws_sent_to_codelets_outputs.get(co); List<Memory> setOfOutputMOs = reg1.get(type); co.removeFromInput((List<Memory>) setOfOutputMOs); reg1.remove(type); }else{ //nothing here to be removed } }else{ throw new IllegalArgumentException(); } //Now i must check if what was sent has nothing inside co, if so, remove co as well HashMap<String, List<Memory>> reg0 = what_ws_sent_to_codelets_inputs.get(co); HashMap<String, List<Memory>> reg1 = what_ws_sent_to_codelets_outputs.get(co); List<Memory> t0 = reg0.get(type); List<Memory> t1 = reg1.get(type); if(t0.isEmpty()){ reg0.remove(type); } if(t1.isEmpty()){ reg1.remove(type); } if(reg0.isEmpty()){ what_ws_sent_to_codelets_inputs.remove(co); } if(reg1.isEmpty()){ what_ws_sent_to_codelets_outputs.remove(co); } } @Override public void notifyCodelets() { // TODO Auto-generated method stub } /** * Destroys all memory object from WorkingStorage. * Cleans up registered codelets. */ public void shutDown() { ArrayList<Memory> list = new ArrayList<Memory>(); list.addAll(this.getAll()); for(Memory mo:list){ this.removeFromWorkingStorageWithDelete(mo); } this.codelet_input_registry_by_type.clear(); this.codelet_output_registry_by_type.clear(); this.workingStorageContentList.clear(); this.workingStorageContents.clear(); this.what_ws_sent_to_codelets_inputs.clear(); this.what_ws_sent_to_codelets_outputs.clear(); } }
17,314
30.142086
183
java
cst
cst-master/src/main/java/br/unicamp/cst/motivational/Appraisal.java
/******************************************************************************* * Copyright (c) 2016 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * E. M. Froes, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.motivational; public class Appraisal { private String name; private double evaluation; private String currentStateEvaluation; public Appraisal(String name, String currentStateEvaluation, double evaluation){ setName(name); setEvaluation(evaluation); setCurrentStateEvaluation(currentStateEvaluation); } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getEvaluation() { return evaluation; } public void setEvaluation(double evaluation) { this.evaluation = evaluation; } public String getCurrentStateEvaluation() { return currentStateEvaluation; } public void setCurrentStateEvaluation(String currentState) { this.currentStateEvaluation = currentState; } @Override public String toString(){ return "Appraisal [name:"+ getName()+", evaluation:"+getEvaluation()+", currentStateEvaluation:"+getCurrentStateEvaluation()+"]"; } }
1,613
26.355932
137
java
cst
cst-master/src/main/java/br/unicamp/cst/motivational/AppraisalCodelet.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.motivational; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.exceptions.CodeletActivationBoundsException; import br.unicamp.cst.representation.idea.Idea; import java.util.*; public abstract class AppraisalCodelet extends Codelet { public static final String INPUT_IDEA_MEMORY = "INPUT_IDEA_MEMORY"; public static final String OUTPUT_IDEA_MEMORY = "OUTPUT_IDEA_MEMORY"; public static final String OUTPUT_APPRAISAL_MEMORY = "OUTPUT_APPRAISAL_MEMORY"; private String id; private Idea inputAbstractObject; private Idea outputAbstractObject; private Appraisal appraisal; private Memory inputAbstractObjectMO; private Memory outputAbstractObjectMO; private Memory outputAppraisalMO; public AppraisalCodelet(String id) { setId(id); setName(id); setAppraisal(new Appraisal(id, "", 1d)); } @Override public void accessMemoryObjects() { if (getInputIdeaMO() == null) { setInputIdeaMO(this.getInput(INPUT_IDEA_MEMORY, 0)); setInputIdea((Idea) getInputIdeaMO().getI()); } if (getOutputIdeaMO() == null) { setOutputIdeaMO(this.getOutput(OUTPUT_IDEA_MEMORY, 0)); setOutputIdea(getInputIdea()); } if (getOutputAppraisalMO() == null) { setOutputAppraisalMO(this.getOutput(OUTPUT_APPRAISAL_MEMORY, 0)); getOutputAppraisalMO().setI(getAppraisal()); } } @Override public synchronized void calculateActivation() { setInputIdea((Idea) getInputIdeaMO().getI()); setAppraisal(appraisalGeneration(getInputIdea().clone())); getAppraisal().setName(getId()); Optional<Idea> first = getInputIdea().getL().stream().filter(property -> property.getName().equals(getId())).findFirst(); if (first.isPresent()) { Idea property = first.get(); Idea evaluation = property.getL().stream().filter(quality -> quality.getName().equals("evaluation")).findFirst().get(); evaluation.setValue(getAppraisal().getEvaluation()); Idea currentState = property.getL().stream().filter(quality -> quality.getName().equals("currentStateEvaluation")).findFirst().get(); currentState.setValue(getAppraisal().getCurrentStateEvaluation()); } else { List<Idea> appraisalQ = new ArrayList<>(); appraisalQ.add(new Idea("evaluation", getAppraisal().getEvaluation(),1)); appraisalQ.add(new Idea("currentStateEvaluation", getAppraisal().getCurrentStateEvaluation(),1)); Idea appraisalProperty = new Idea(getId(), appraisalQ); getInputIdea().add(appraisalProperty); } setOutputIdea(getInputIdea()); try { setActivation(getAppraisal().getEvaluation()); } catch (CodeletActivationBoundsException e) { e.printStackTrace(); } } @Override public synchronized void proc(){ getOutputAppraisalMO().setI(getAppraisal()); getOutputIdeaMO().setI(getOutputIdea()); } public abstract Appraisal appraisalGeneration(Idea inputIdea); public Idea getInputIdea() { return inputAbstractObject; } public void setInputIdea(Idea inputIdea) { this.inputAbstractObject = inputIdea; } public Appraisal getAppraisal() { return appraisal; } public void setAppraisal(Appraisal appraisal) { this.appraisal = appraisal; } public Memory getInputIdeaMO() { return inputAbstractObjectMO; } public void setInputIdeaMO(Memory inputIdeaMO) { this.inputAbstractObjectMO = inputIdeaMO; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Memory getOutputIdeaMO() { return outputAbstractObjectMO; } public void setOutputIdeaMO(Memory outputIdeaMO) { this.outputAbstractObjectMO = outputIdeaMO; } public Idea getOutputIdea() { return outputAbstractObject; } public void setOutputIdea(Idea outputIdea) { this.outputAbstractObject = outputIdea; } public Memory getOutputAppraisalMO() { return outputAppraisalMO; } public void setOutputAppraisalMO(Memory outputAppraisalMO) { this.outputAppraisalMO = outputAppraisalMO; } }
5,049
28.532164
145
java
cst
cst-master/src/main/java/br/unicamp/cst/motivational/Drive.java
/******************************************************************************* * Copyright (c) 2016 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * E. M. Froes, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.motivational; import br.unicamp.cst.support.ToString; import java.io.Serializable; public class Drive implements Serializable { private static final long serialVersionUID = 1L; private String name; private double activation; private double priority; private double level; private double urgencyThreshold; private double emotionalDistortion = 0; private boolean urgencyState = false; public Drive(String name){ setName(name); } public Drive(String name, double activation, double priority, double level, double urgentThreshold){ setName(name); setActivation(activation); setPriority(priority); setLevel(level); setUrgencyThreshold(urgentThreshold); } public Drive(String name, double activation, double priority, double level, double urgentThreshold, double emotionalDistortion){ setName(name); setActivation(activation); setPriority(priority); setLevel(level); setUrgencyThreshold(urgentThreshold); setEmotionalDistortion(emotionalDistortion); } public synchronized String getName() { return name; } public synchronized void setName(String name) { this.name = name; } public synchronized double getActivation() { return activation; } public synchronized void setActivation(double activation) { this.activation = activation; } public synchronized double getPriority() { return priority; } public synchronized void setPriority(double priority) { this.priority = priority; } public synchronized double getLevel() { return level; } public synchronized void setLevel(double level) { this.level = level; } public synchronized double getUrgencyThreshold() { return urgencyThreshold; } public synchronized void setUrgencyThreshold(double urgencyThreshold) { this.urgencyThreshold = urgencyThreshold; } public synchronized double getEmotionalDistortion() { return emotionalDistortion; } public synchronized void setEmotionalDistortion(double emotionalDistortion) { this.emotionalDistortion = emotionalDistortion; } @Override public String toString(){ return(ToString.from(getActivation())); } public String toStringComplete() { return"Drive [name="+getName()+", activation="+getActivation()+", urgency state="+isUrgencyState()+", priority="+getPriority()+", level="+getLevel() +", urgency threshold="+getUrgencyThreshold()+", emotional distortion="+getEmotionalDistortion()+"]"; } public boolean isUrgencyState() { return urgencyState; } public void setUrgencyState(boolean urgencyState) { this.urgencyState = urgencyState; } }
3,425
28.534483
156
java
cst
cst-master/src/main/java/br/unicamp/cst/motivational/EmotionalCodelet.java
/******************************************************************************* * Copyright (c) 2016 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * E. M. Froes, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.motivational; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.entities.CSTMessages; import br.unicamp.cst.core.exceptions.CodeletActivationBoundsException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class EmotionalCodelet extends Codelet { public final static String INPUT_DRIVES_MEMORY = "INPUT_DRIVES_MEMORY"; public final static String INPUT_AFFECTED_DRIVE_MEMORY = "INPUT_AFFECTED_DRIVE_MEMORY"; public final static String INPUT_MOOD_MEMORY = "INPUT_MOOD_MEMORY"; public final static String OUTPUT_AFFECTED_DRIVE_MEMORY = "OUTPUT_AFFECTED_DRIVE_MEMORY"; private String id; private Drive affectedDrive; private Map<Memory, Double> inputDrives; private Memory inputDrivesMO; private Memory inputAffectedDriveMO; private Memory outputAffectedDriveMO; private Memory inputMoodMO; public EmotionalCodelet(String id) throws CodeletActivationBoundsException { this.setId(id); this.setName(id); this.setActivation(0.0d); setAffectedDrive(new Drive(id)); } @Override public void accessMemoryObjects() { if (getInputDrivesMO() == null) { setInputDrivesMO(this.getInput(INPUT_DRIVES_MEMORY, 0)); setInputDrives((HashMap<Memory, Double>) getInputDrivesMO().getI()); } if (getInputAffectedDriveMO() == null) { setInputAffectedDriveMO(getInput(INPUT_AFFECTED_DRIVE_MEMORY, 0)); setAffectedDrive((Drive) ((Memory)getInputAffectedDriveMO().getI()).getI()); } if (getInputMoodMO() == null) { setInputMoodMO(this.getInput(INPUT_MOOD_MEMORY, 0)); } if (getOutputAffectedDriveMO() == null) { setOutputAffectedDriveMO(this.getOutput(OUTPUT_AFFECTED_DRIVE_MEMORY, 0)); } } public abstract double calculateEmotionalDistortion(List<Drive> listOfDrives, Mood mood); @Override public synchronized void calculateActivation() { double activation = 0d; List<Drive> listOfDrives = new ArrayList<Drive>(); for (Map.Entry<Memory, Double> drive : getInputDrives().entrySet()) { listOfDrives.add((Drive) ((Memory)drive.getKey()).getI()); } Mood mood = (Mood) ((Memory)getInputMoodMO().getI()).getI(); if(mood != null) { activation = this.calculateEmotionalDistortion(listOfDrives, mood); } else{ activation = 0; } setAffectedDrive((Drive) ((Memory)getInputAffectedDriveMO().getI()).getI()); if(getAffectedDrive() != null) getAffectedDrive().setEmotionalDistortion(activation); } @Override public void proc() { if(getAffectedDrive() != null) { getOutputAffectedDriveMO().setI(getAffectedDrive()); getOutputAffectedDriveMO().setEvaluation(getAffectedDrive().getEmotionalDistortion()); } } public String getId() { return id; } public void setId(String id) { try { if (id.equals("")) { throw new Exception(CSTMessages.MSG_VAR_EMOTIONAL_NAME_NULL); } this.id = id; } catch (Exception me) { me.printStackTrace(); } } private synchronized Map<Memory, Double> getInputDrives() { return inputDrives; } private synchronized void setInputDrives(Map<Memory, Double> inputDrives) { try { if (inputDrives == null) { throw new Exception(CSTMessages.MSG_VAR_EMOTIONAL_DRIVE_VOTES); } for (Map.Entry<Memory, Double> drive : inputDrives.entrySet()) { if (drive.getValue() > 1 || drive.getValue() < 0) { throw new Exception("Drive:" + drive.getKey().getName() + " " + CSTMessages.MSG_VAR_RELEVANCE); } } this.inputDrives = inputDrives; } catch (Exception me) { me.printStackTrace(); } } public Memory getInputDrivesMO() { return inputDrivesMO; } public void setInputDrivesMO(Memory inputDrivesMO) { this.inputDrivesMO = inputDrivesMO; } public Memory getOutputAffectedDriveMO() { return outputAffectedDriveMO; } public void setOutputAffectedDriveMO(Memory outputAffectedDriveMO) { this.outputAffectedDriveMO = outputAffectedDriveMO; } public Memory getInputMoodMO() { return inputMoodMO; } public void setInputMoodMO(Memory inputMoodMO) { this.inputMoodMO = inputMoodMO; } public Drive getAffectedDrive() { return affectedDrive; } public void setAffectedDrive(Drive affectedDrive) { this.affectedDrive = affectedDrive; } public Memory getInputAffectedDriveMO() { return inputAffectedDriveMO; } public void setInputAffectedDriveMO(Memory inputAffectedDriveMO) { this.inputAffectedDriveMO = inputAffectedDriveMO; } }
5,693
29.449198
115
java
cst
cst-master/src/main/java/br/unicamp/cst/motivational/Goal.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.motivational; import br.unicamp.cst.representation.idea.Idea; /** * Created by du on 19/12/16. */ public class Goal { private String id; private Idea goalIdeas; public Goal(String id, Idea goalIdeas){ this.setId(id); this.setGoalIdeas(goalIdeas); } public String getId() { return id; } public void setId(String id) { this.id = id; } public Idea getGoalIdeas() { return goalIdeas; } public void setGoalIdeas(Idea goalIdeas) { this.goalIdeas = goalIdeas; } }
1,135
24.818182
82
java
cst
cst-master/src/main/java/br/unicamp/cst/motivational/GoalCodelet.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.motivational; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.exceptions.CodeletActivationBoundsException; import br.unicamp.cst.representation.idea.Idea; public abstract class GoalCodelet extends Codelet { public static final String INPUT_HYPOTHETICAL_SITUATIONS_MEMORY = "INPUT_HYPOTHETICAL_SITUATIONS_MEMORY"; public static final String OUTPUT_GOAL_MEMORY = "OUTPUT_GOAL_MEMORY"; private String id; private Memory inputHypotheticalSituationsMO; private Memory goalMO; private Idea hypotheticalSituation; private Idea goal; private boolean init = false; public GoalCodelet(String id) { this.setId(id); } @Override public void accessMemoryObjects() { if (getInputHypotheticalSituationsMO() == null) { setInputHypotheticalSituationsMO(this.getInput(INPUT_HYPOTHETICAL_SITUATIONS_MEMORY, 0)); } if (getGoalMO() == null) { setGoalMO(this.getOutput(OUTPUT_GOAL_MEMORY, 0)); } } @Override public void calculateActivation() { try { setActivation(0); } catch (CodeletActivationBoundsException e) { e.printStackTrace(); } } @Override public void proc() { if (isInit()) { setHypotheticalSituation((Idea) ((Memory) getInputHypotheticalSituationsMO().getI()).getI()); setGoal(goalGeneration(getHypotheticalSituation())); getGoalMO().setI(getGoal()); } setInit(true); } public abstract Idea goalGeneration(Idea hypoteticalSituation); public Memory getInputHypotheticalSituationsMO() { return inputHypotheticalSituationsMO; } public void setInputHypotheticalSituationsMO(Memory inputHypotheticalSituationsMO) { this.inputHypotheticalSituationsMO = inputHypotheticalSituationsMO; } public Memory getGoalMO() { return goalMO; } public void setGoalMO(Memory goalMO) { this.goalMO = goalMO; } public Idea getHypotheticalSituation() { return hypotheticalSituation; } public void setHypotheticalSituation(Idea hypotheticalSituation) { this.hypotheticalSituation = hypotheticalSituation; } public Idea getGoal() { return goal; } public void setGoal(Idea goal) { this.goal = goal; } public String getId() { return id; } public void setId(String id) { this.id = id; } public boolean isInit() { return init; } public void setInit(boolean init) { this.init = init; } }
3,255
26.59322
109
java
cst
cst-master/src/main/java/br/unicamp/cst/motivational/Mood.java
/******************************************************************************* * Copyright (c) 2016 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * E. M. Froes, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.motivational; public class Mood { private String name; private String emotionalState; private double value; public Mood(String name, double value){ setName(name); setValue(value); setEmotionalState(""); } public Mood(String name, String emotionalState, double value){ setName(name); setValue(value); setEmotionalState(emotionalState); } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } public String getEmotionalState() { return emotionalState; } public void setEmotionalState(String emotionalState) { this.emotionalState = emotionalState; } @Override public String toString(){ return "Mood [name:"+getName()+", value:"+getValue()+", emotionalState:"+getEmotionalState()+"]"; } }
1,589
24.238095
105
java
cst
cst-master/src/main/java/br/unicamp/cst/motivational/MoodCodelet.java
/******************************************************************************* * Copyright (c) 2016 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * E. M. Froes, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.motivational; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import java.util.ArrayList; import java.util.List; public abstract class MoodCodelet extends Codelet { public static final String INPUT_DRIVES_MEMORY = "INPUT_DRIVES_MEMORY"; public static final String INPUT_APPRAISAL_MEMORY = "INPUT_APPRAISAL_MEMORY"; public static final String INPUT_SENSORY_MEMORY = "INPUT_SENSORY_MEMORY"; public static final String OUTPUT_MOOD_MEMORY = "OUTPUT_MOOD_MEMORY"; private String id; private List<Memory> listOfDrivesMO; private Appraisal appraisal; private List<Object> sensors; private Mood outputMood; private Memory inputDrivesMemoryMO; private Memory inputAppraisalMO; private Memory inputSensoryMO; private Memory outputMoodMO; public MoodCodelet(String id){ this.setId(id); this.setName(id); this.setListOfDrivesMO(new ArrayList<Memory>()); this.setSensors(new ArrayList<Object>()); this.setOutputMood(new Mood(getId(), "", 0d)); } @Override public void accessMemoryObjects() { if(getInputDrivesMemoryMO() == null){ setInputDrivesMemoryMO(getInput(INPUT_DRIVES_MEMORY, 0)); setListOfDrivesMO((List<Memory>) getInputDrivesMemoryMO().getI()); } if(getInputAppraisalMO() == null){ setInputAppraisalMO(getInput(INPUT_APPRAISAL_MEMORY, 0)); setAppraisal((Appraisal) ((Memory) getInputAppraisalMO().getI()).getI()); } if(getInputSensoryMO() == null){ setInputSensoryMO(getInput(INPUT_SENSORY_MEMORY, 0)); setSensors((List<Object>) getInputSensoryMO().getI()); } if(getOutputMoodMO() == null){ setOutputMoodMO(getOutput(OUTPUT_MOOD_MEMORY, 0)); } } @Override public synchronized void calculateActivation() { List<Drive> listOfDrive = new ArrayList<>(); getListOfDrivesMO().stream().forEach(memory -> { listOfDrive.add((Drive) memory.getI()); }); Mood mood = moodGeneration(listOfDrive, (Appraisal) ((Memory) getInputAppraisalMO().getI()).getI(), getSensors()); mood.setName(getId()); setOutputMood(mood); } @Override public synchronized void proc(){ getOutputMoodMO().setI(getOutputMood()); } public abstract Mood moodGeneration(List<Drive> listOfDrives, Appraisal appraisal, List<Object> sensors); public String getId() { return id; } public void setId(String id) { this.id = id; } public List<Memory> getListOfDrivesMO() { return listOfDrivesMO; } public void setListOfDrivesMO(List<Memory> listOfDrivesMO) { this.listOfDrivesMO = listOfDrivesMO; } public Appraisal getAppraisal() { return appraisal; } public void setAppraisal(Appraisal appraisal) { this.appraisal = appraisal; } public Memory getInputDrivesMemoryMO() { return inputDrivesMemoryMO; } public void setInputDrivesMemoryMO(Memory inputDrivesMemoryMO) { this.inputDrivesMemoryMO = inputDrivesMemoryMO; } public Memory getInputAppraisalMO() { return inputAppraisalMO; } public void setInputAppraisalMO(Memory inputAppraisalMO) { this.inputAppraisalMO = inputAppraisalMO; } public Memory getInputSensoryMO() { return inputSensoryMO; } public void setInputSensoryMO(Memory inputSensoryMO) { this.inputSensoryMO = inputSensoryMO; } public Memory getOutputMoodMO() { return outputMoodMO; } public void setOutputMoodMO(Memory outputMoodMO) { this.outputMoodMO = outputMoodMO; } public List<Object> getSensors() { return sensors; } public void setSensors(List<Object> sensors) { this.sensors = sensors; } public Mood getOutputMood() { return outputMood; } public void setOutputMood(Mood outputMood) { this.outputMood = outputMood; } }
4,667
27.290909
122
java
cst
cst-master/src/main/java/br/unicamp/cst/motivational/MotivationalCodelet.java
/******************************************************************************* * Copyright (c) 2016 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * E. M. Froes, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.motivational; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import br.unicamp.cst.core.entities.CSTMessages; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.exceptions.CodeletActivationBoundsException; public abstract class MotivationalCodelet extends Codelet { public static final String INPUT_DRIVES_MEMORY = "INPUT_DRIVES_MEMORY"; public static final String INPUT_SENSORS_MEMORY = "INPUT_SENSORS_MEMORY"; public static final String OUTPUT_DRIVE_MEMORY = "OUTPUT_DRIVE_MEMORY"; private String id; private double priority; private double urgencyThreshold; private double level; private boolean urgencyState = false; private double emotionalDistortion; private Map<Memory, Double> drivesRelevance; private List<Memory> sensoryVariables; private Drive outputDrive; private Memory inputDrivesMO; private Memory inputSensorsMO; private Memory outputDriveMO; public MotivationalCodelet(String id, double level, double priority, double urgencyThreshold) { setLevel(level); setId(id); setName(id); setPriority(priority); setUrgencyThreshold(urgencyThreshold); setDrivesRelevance(new HashMap<Memory, Double>()); setSensoryVariables(new ArrayList<Memory>()); setOutputDrive(new Drive(getId(), 0, getPriority(), getLevel(), getUrgencyThreshold(), 0)); } @Override public void accessMemoryObjects() { if (getInputDrivesMO() == null) { setInputDrivesMO(this.getInput(INPUT_DRIVES_MEMORY, 0)); this.setDrivesRelevance((Map<Memory, Double>) getInputDrivesMO().getI()); } if (getInputSensorsMO() == null) { setInputSensorsMO(this.getInput(INPUT_SENSORS_MEMORY, 0)); this.setSensoryVariables(Collections.synchronizedList((List<Memory>) getInputSensorsMO().getI())); } if (getOutputDriveMO() == null) { setOutputDriveMO(this.getOutput(OUTPUT_DRIVE_MEMORY, 0)); getOutputDriveMO().setI(getOutputDrive()); } } @Override public synchronized void proc() { synchronized (getOutputDriveMO()) { getOutputDrive().setActivation(getActivation()); //getOutputDrive().setEmotionalDistortion(getEmotionalDistortion()); getOutputDriveMO().setEvaluation(getActivation()); getOutputDriveMO().setI(getOutputDrive()); } } public void addDrive(Memory drive, double relevance) { getDrivesRelevance().put(drive, relevance); } public void removeDrive(Memory drive) { getDrivesRelevance().remove(drive); } @Override public synchronized void calculateActivation() { synchronized (this) { try { if (getDrivesRelevance().size() > 0) { List<Drive> listOfDrives = new ArrayList<Drive>(); for (Map.Entry<Memory, Double> driveMO : getDrivesRelevance().entrySet()) { Drive drive = (Drive) driveMO.getKey(); Drive driveClone = new Drive(drive.getName(), drive.getActivation(), drive.getPriority(), drive.getLevel(), drive.getUrgencyThreshold(), drive.getEmotionalDistortion()); driveClone.setActivation(driveClone.getActivation() * driveMO.getValue()); listOfDrives.add(driveClone); } this.setActivation(verifingUrgencyThreshold(calculateSecundaryDriveActivation(getSensoryVariables(), listOfDrives), getOutputDrive())); } else { if (getSensoryVariables().size() > 0) { double activation = verifingUrgencyThreshold(calculateSimpleActivation(getSensoryVariables()), getOutputDrive()); if (activation < 0.0d) activation = 0.0d; if (activation > 1.0d) activation = 1.0d; this.setActivation(activation); } else { this.setActivation(0); } } } catch (CodeletActivationBoundsException e) { e.printStackTrace(); } } } private synchronized double verifingUrgencyThreshold(double driveActivation, Drive drive) { double evaluation = 0; double verifyUrgency = driveActivation + drive.getEmotionalDistortion() >= 1? 1 : driveActivation + drive.getEmotionalDistortion(); if (verifyUrgency >= getUrgencyThreshold()) { evaluation = 0.5 + drive.getPriority(); drive.setUrgencyState(true); } else { evaluation = (driveActivation + drive.getEmotionalDistortion())/2; drive.setUrgencyState(false); } return evaluation; } public abstract double calculateSimpleActivation(List<Memory> sensors); public abstract double calculateSecundaryDriveActivation(List<Memory> sensors, List<Drive> listOfDrives); public synchronized double getLevel() { return level; } public synchronized Map<Memory, Double> getDrivesRelevance() { return drivesRelevance; } public synchronized String getId() { return id; } public synchronized void setId(String id) { try { if (id == null) { throw new Exception(CSTMessages.MSG_VAR_NAME_NULL); } this.id = id; } catch (Exception me) { me.printStackTrace(); } } public synchronized double getPriority() { return priority; } public synchronized void setPriority(double priority) { try { if (priority <= 0) { throw new Exception(CSTMessages.MSG_VAR_PRIORITY_NULL); } this.priority = priority; } catch (Exception me) { me.printStackTrace(); } } public Memory getInputDrivesMO() { return inputDrivesMO; } public void setInputDrivesMO(Memory inputDrivesMO) { this.inputDrivesMO = inputDrivesMO; } public Memory getInputSensorsMO() { return inputSensorsMO; } public void setInputSensorsMO(Memory inputSensorsMO) { this.inputSensorsMO = inputSensorsMO; } public Memory getOutputDriveMO() { return outputDriveMO; } public void setOutputDriveMO(Memory outputDriveMO) { this.outputDriveMO = outputDriveMO; } public List<Memory> getSensoryVariables() { return sensoryVariables; } public void setSensoryVariables(List<Memory> sensoryVariables) { this.sensoryVariables = sensoryVariables; } public void setLevel(double level) { try { if (level < 0 || level > 1) { throw new Exception(CSTMessages.MSG_VAR_URGENT_ACTIVATION_THRESHOLD_RANGE); } else { this.level = level; } } catch (Exception ex) { ex.printStackTrace(); } } private void setDrivesRelevance(Map<Memory, Double> drivesRelevance) { this.drivesRelevance = drivesRelevance; } private Drive getOutputDrive() { return outputDrive; } private void setOutputDrive(Drive outputDrive) { this.outputDrive = outputDrive; } public double getUrgencyThreshold() { return urgencyThreshold; } public void setUrgencyThreshold(double urgencyThreshold) { this.urgencyThreshold = urgencyThreshold; } public double getEmotionalDistortion() { return emotionalDistortion; } public void setEmotionalDistortion(double emotionalDistortion) { this.emotionalDistortion = emotionalDistortion; } }
8,682
29.79078
155
java
cst
cst-master/src/main/java/br/unicamp/cst/perception/Perception.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation * E. M. Froes - documentation ******************************************************************************/ package br.unicamp.cst.perception; import java.util.ArrayList; import java.util.HashMap; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.memory.WorkingStorage; /** * This Perception class allows us to create codelets with additional methods. * A perception codelet has the property of always sending its output memory objects to working storage. * Note: A Perception Codelet clears its output list at every iteration. * * * @author Klaus Raizer * */ public abstract class Perception extends Codelet { private HashMap<Memory, Boolean> world_state_log = new HashMap<Memory, Boolean>(); private ArrayList<Memory> list_of_true_world_states=new ArrayList<Memory>(); private ArrayList<Memory> list_of_false_world_states=new ArrayList<Memory>(); private ArrayList<Memory> known_percepts=new ArrayList<Memory>();//list of all known percepts (only grows with time) private ArrayList<Memory> detected_percepts=new ArrayList<Memory>();//list of all percepts that were detected by the codelet (is reset after uptadeOutputWithPercepts is called) private WorkingStorage localWS; /** * Default constructor. * @param localWS */ public Perception(WorkingStorage localWS) { this.localWS = localWS; } /** * This method pushes a memory object representing a percept detected in the world into a list, so this perception codelet knows what is true. * Important: Remember to call uptadeOutputWithPercepts() in order to keep pushed percepts into this codelet's output list. * @param pe */ public synchronized void pushDetectedPercept(Memory pe) { if(!this.detected_percepts.contains(pe)){ this.detected_percepts.add(pe); } if(!this.known_percepts.contains(pe)){ this.known_percepts.add(pe); } } /** * This method makes sure all detected percepts are kept in this codelet's output list. * All known percepts that were not detected should be removed from output list if any of them are still there. * Being a Perception codelet, it keeps its output list synched with Working Storage at all times. */ public synchronized void uptadeOutputWithPercepts(){ ArrayList<Memory> D = new ArrayList<Memory>(); ArrayList<Memory> K = new ArrayList<Memory>(); ArrayList<Memory> O = new ArrayList<Memory>(); ArrayList<Memory> addDK = new ArrayList<Memory>(); ArrayList<Memory> addDO = new ArrayList<Memory>(); ArrayList<Memory> remove = new ArrayList<Memory>(); D.addAll(this.detected_percepts); K.addAll(this.known_percepts); O.addAll(this.getOutputs()); //Intersection between D and K, minus O addDK.addAll(D); addDK.retainAll(K); addDK.removeAll(O); //Intersection between D and O, minus K addDO.addAll(D); addDO.retainAll(O); addDO.removeAll(K); //Intersection between O and K minus D remove.addAll(O); remove.retainAll(K); remove.removeAll(D); for(Memory mo : addDK){ this.addOutput(mo); } for(Memory mo : addDO){ this.addOutput(mo); } for(Memory mo : remove){ this.removesOutput(mo); } //Resets detected list this.detected_percepts.clear(); // // // ArrayList<Memory> outputs = new ArrayList<Memory>(); // outputs.addAll(this.getOutputs()); // // ArrayList<Memory> detected=new ArrayList<Memory>(); // detected.addAll(this.detected_percepts); // detected.removeAll(outputs); // // //Removing false propositions // for(Memory mo:outputs){ // if(!detected_percepts.contains(mo.getInfo())){ // this.removesOutput(mo); // } // } // // // outputs = new ArrayList<Memory>(); // outputs.addAll(this.getOutputs()); // // ArrayList<Memory> undetected=new ArrayList<Memory>(); // undetected.addAll(this.known_percepts); // undetected.removeAll(outputs); // // // // //Adding true propositions // for(String trueProp:trueStates){ // Memory mo = worldState_string_mo.get(trueProp); // if(!outputs.contains(mo)){ // this.addOutput(mo); // } // } } /** * This method adds an output memory in the output list. * @param output */ public synchronized void addOutput(Memory output) { this.getOutputs().add(output); list_of_true_world_states.add(output); list_of_false_world_states.remove(output); this.synchWithWorkingStorage(); } /** * This method removes an output memory in the output list. * @param output */ public synchronized void removesOutput(Memory output) { this.getOutputs().remove(output); list_of_true_world_states.remove(output); list_of_false_world_states.add(output); this.synchWithWorkingStorage(); } /** * Makes sure what this perception codelet perceives as true, remains in working storage, while what it perceives as being false does not. * This method resets the list of detected percepts. */ private void synchWithWorkingStorage() { //TODO Remember to acquire lock! ArrayList<Memory> alreadyInWorkingStorage = new ArrayList<Memory>(); alreadyInWorkingStorage.addAll(localWS.getAll()); //alreadyInWorkingStorage.retainAll(this.getOutputs()); ArrayList<Memory> mustAdd = new ArrayList<Memory>(); mustAdd.addAll(list_of_true_world_states); mustAdd.removeAll(alreadyInWorkingStorage); ArrayList<Memory> mustRemove = new ArrayList<Memory>(); mustRemove.addAll(list_of_false_world_states); for(Memory mo : mustRemove){ localWS.removeFromWorkingStorageWithoutDelete(mo); } for(Memory mo:mustAdd){ localWS.putMemoryObject(mo); } } }
6,236
29.573529
177
java
cst
cst-master/src/main/java/br/unicamp/cst/perception/PerceptionProxy.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation * E. M. Froes - documentation ******************************************************************************/ package br.unicamp.cst.perception; import br.unicamp.cst.core.entities.CodeRack; import br.unicamp.cst.core.entities.Codelet; import java.util.ArrayList; import java.util.List; /** * Perception proxy holds the codelets responsible for interpreting data coming from sensors * * @author klaus.raizer */ public class PerceptionProxy { private List<Codelet> listInterpreters; private CodeRack codeRack; /** * Default Constructor. * @param codeRack */ public PerceptionProxy(CodeRack codeRack) { this.codeRack = codeRack; listInterpreters = new ArrayList<Codelet>(); } /** * Starts all interpreters in this proxy. */ public void start() { for(Codelet interpreter:listInterpreters) { interpreter.start(); } } /** * Stops all interpreters in this proxy. */ public void stop() { for(Codelet interpreter:listInterpreters) { interpreter.stop(); } } /** * Add an new interpreter to this proxy. * @param interpreter to be added to this proxy */ public void add(Codelet interpreter) { listInterpreters.add(interpreter); } /** * Removes the given codelet from this proxy and destroys it in code rack. * @param co */ public void removeWithDelete(Codelet co) { this.listInterpreters.remove(co); if(codeRack!=null) codeRack.destroyCodelet(co); } /** * Removes the given codelet from this proxy but keepts it in CodeRack. * @param co */ public void remove(Codelet co){ this.listInterpreters.remove(co); } }
2,251
22.705263
93
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/idea/Category.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.representation.idea; /** * This interface is used to represent a Category, i.e. a set that is subject to a membership law * indicated by the membership method. The instantiation method provides a random instance for * the category, subject to a set of constraints, when available. * @author rgudwin */ public interface Category { /** * The method getInstance provides a random instance of this category, subject to a list of constraints, when available * @param constraints a list of constraints for the new instance, in the form of Ideas * @return the new Idea that was generated */ public Idea getInstance(Idea constraints ); /** * This method tests if a provided Idea is a member of this category. * @param idea the idea under consideration for membership * @return the membership value, a value among 0 and 1. */ public double membership(Idea idea); }
1,538
44.264706
97
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/idea/Habit.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.representation.idea; import java.util.List; /** * This interface is used to represent a Habit, i.e., an executable action, that typically is used * to create or modify an idea * @author rgudwin */ public interface Habit { /** * This method executes the habit * @param idea an optional parameter representing an idea that might be used by the habit to generate a new idea * @return a list of generated or modified ideas */ public Idea exec(Idea idea); }
1,105
38.5
116
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/idea/HabitExecutionerCodelet.java
/*********************************************************************************************** * Copyright (c) 2012-2023 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors for this file: * R. R. Gudwin ***********************************************************************************************/ package br.unicamp.cst.representation.idea; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author rgudwin */ public class HabitExecutionerCodelet extends Codelet { Habit h; Idea root; @Override public void accessMemoryObjects() { root = new Idea("root"); for (Memory m : this.inputs) { Object o = m.getI(); if (o instanceof Idea) { Idea id = (Idea)o; Object value = id.getValue(); if (value instanceof Habit) { h = (Habit) value; } else { root.add((Idea)o); } } } if (root.isLeaf()) { Logger.getAnonymousLogger().log(Level.INFO, "I was not able to find any valid Idea at inputs"); } if (h == null) { Logger.getAnonymousLogger().log(Level.INFO, "I found no habit to execute"); } } @Override public void calculateActivation() { /* We are not using activation in this codelet */ } @Override public void proc() { if (h != null) { Idea ois = h.exec(root); for (Memory m : outputs) m.setI(ois); } } }
1,945
28.484848
107
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/idea/Idea.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.representation.idea; import br.unicamp.cst.support.ToString; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * This class is used as the standard knowledge representation entity within CST * * @author rgudwin */ public class Idea implements Category,Habit { private long id; private String name=""; private Object value=""; private List<Idea> l= new CopyOnWriteArrayList<>(); private int type=0; private String category=""; private int scope=1; // 0: possibility, 1: existence, 2: law private transient IdeaComparator ideaComparator = new IdeaComparator(); // This list is used while building a toStringFull() /** * The repo hashmap is a list of known Ideas used by the createIdea factory method to * avoid that Ideas with a same new to be created. This list is used to reuse an * Idea with the same name. This variable provides a global list with all known * Ideas created so far. */ public static ConcurrentHashMap<String,Idea> repo = new ConcurrentHashMap<>(); // This list is used while converting a Java Object to an Idea, to avoid recursions transient static CopyOnWriteArrayList<Object> listtoavoidloops = new CopyOnWriteArrayList<>(); /** * This variable stores the last Id used while creating new Ideas. */ public static long lastId = 0; private static final String CDOUBLE = "java.lang.Double"; private static final String CFLOAT = "java.lang.Float"; private static final String CINT = "java.lang.Integer"; private static final String CLONG = "java.lang.Long"; private static final String CSHORT = "java.lang.Short"; private static final String CBYTE = "java.lang.Byte"; private static final String CBOOLEAN = "java.lang.Boolean"; private static final String CSTRING = "java.lang.String"; /** * This function generates a new id to be assigned to a new Idea being created. * This id is generated in a serialized format, being the first one with value 0 * and incrementally increased by one for each new created Idea. The value of the * last id created so far is stored in the <i>lastId</i> static variable. * @return the generated new id */ public static long genId() { return(lastId++); } /** * This is the simpler constructor for an Idea. Basically, it finds a new id and creates an empty Idea. */ public Idea() { id = genId(); } /** * This construction initializes the Idea just with a name (and an id). * @param name The name to be assigned to the Idea */ public Idea(String name) { this.name = name; id = genId(); } /** * This constructor initializes the Idea with a name, a value and a type. * The value can be any Java object. The type is an integer number, which * describes the kind of Idea. Even though the type can be used for any purpose, * the following reference for Idea types is used as a reference: * 0 - AbstractObject * 1 - Property * 2 - Link or Reference to another Idea * 3 - QualityDimension * 4 - Episode * 5 - Composite * 6 - Aggregate * 7 - Configuration * 8 - TimeStep * 9 - PropertyCategory * 10 - ObjectCategory * 11 - EpisodeCategory * 12 - PropertyPossibility * 13 = ObjectPossibility * 14 - EpisodePossibility * 15 - ActionPossibility * 16 - Action * 17 - ActionCategory * 18 - Goal * * @param name The name assigned to the Idea. * @param value The value to be assigned to the Idea (can be an empty String, or null). If the value is given a null value, it is substituted by the String "null". * @param type The type assigned to the Idea */ public Idea(String name, Object value, int type) { this.name = name; if (value != null) this.value = value; else this.value = "null"; this.type = type; id = genId(); } /** * This constructor is a wrapper for an Idea with type 1. If the value is a String, it is parsed in order to create a numeric value with a proper type. Up to now, the constructor recognizes Integers and Doubles. * @param name The name assigned to the Idea * @param value The value assigned to the Idea. If this value is a String, it is parsed to check if this String describes an Integer or a Double and converts the number to a prpper type (an int or a double). */ public Idea(String name, Object value) { type = 1; this.name = name; id = genId(); if (value instanceof String) { String svalue = (String) value; try { int ivalue = Integer.parseInt(svalue); this.value = ivalue; } catch(Exception e) { try { double dvalue = Double.parseDouble(svalue); this.value = dvalue; } catch(Exception e2) { this.value = svalue; } } } else this.value = value; } /** * This constructor initializes the Idea with a name, a value, a type, a category and a scope. * @param name The name assigned to the Idea * @param value The value to be assigned to the Idea (can be an empty String, or null). If the value is given a null value, it is substituted by the String "null". * @param type The type assigned to the Idea * @param category The category assigned to the Idea * @param scope The scope assigned to the Idea (0: possibility, 1: existence, 2: law) */ public Idea(String name, Object value, int type, String category, int scope) { this(name,value,type); this.category = category; this.scope = scope; } /** * This constructor initializes the Idea with a name, a value, a category and a scope. * The Idea type is guessed, based on its category * @param name The name assigned to the Idea * @param value The value to be assigned to the Idea (can be an empty String, or null). If the value is given a null value, it is substituted by the String "null". * @param category The category assigned to the Idea * @param scope The scope assigned to the Idea (0: possibility, 1: existence, 2: law) */ public Idea(String name, Object value, String category, int scope) { this(name,value,guessType(category,scope)); this.category = category; this.scope = scope; } /** * The createIdea method is used as a static Idea factory, which tries to reuse Ideas with the same name. * It can be used, for example, in cases where Ideas are created in a periodic way, being disposed in the sequence. * The use of this method allows for a better use of memory, avoiding an excessive use of garbage collection mechanism. * An Idea created with this method will not create a new Idea if given a name already used in the past. In this case, * it will return a reference to this already created Idea. Ideas with the same name, with a different type will be * treated as different Ideas. * @param name The name associated to the created Idea * @param value The value assigned to the Idea * @param type The type assigned to the Idea * @return The newly created Idea */ public synchronized static Idea createIdea(String name, Object value, int type) { Idea ret = repo.get(name+"."+type); if (ret == null) { ret = new Idea(name,value,type); repo.put(name+"."+type, ret); } else { ret.setValue(value); ret.l= new CopyOnWriteArrayList<>(); } return(ret); } public static int guessType(String category, int scope) { int guess = 0; if (category != null) { if (category.equalsIgnoreCase("AbstractObject") && scope == 1) { guess = 0; } if (category.equalsIgnoreCase("Property") && scope == 1) { guess = 1; } else if (category.equalsIgnoreCase("Link")) { guess = 2; } else if (category.equalsIgnoreCase("QualityDimension")) { guess = 3; } else if (category.equalsIgnoreCase("Episode") && scope == 1) { guess = 4; } else if (category.equalsIgnoreCase("Composite")) { guess = 5; } else if (category.equalsIgnoreCase("Aggregate")) { guess = 6; } else if (category.equalsIgnoreCase("Configuration")) { guess = 7; } else if (category.equalsIgnoreCase("TimeStep")) { guess = 8; } else if (category.equalsIgnoreCase("Property") && scope == 2) { guess = 9; } else if (category.equalsIgnoreCase("AbstractObject") && scope == 2) { guess = 10; } else if (category.equalsIgnoreCase("Episode") && scope == 2) { guess = 11; } else if (category.equalsIgnoreCase("Property") && scope == 0) { guess = 12; } else if (category.equalsIgnoreCase("AbstractObject") && scope == 0) { guess = 13; } else if (category.equalsIgnoreCase("Episode") && scope == 0) { guess = 14; } else if (category.equalsIgnoreCase("Action") && scope == 0) { guess = 15; } else if (category.equalsIgnoreCase("Action") && scope == 1) { guess = 16; } else if (category.equalsIgnoreCase("Action") && scope == 2) { guess = 17; } else if (category.equalsIgnoreCase("Goal")) { guess = 18; } } return(guess); } /** * This method returns the simple name of the given Idea. * This method returns what is called the "Simple" name of an Idea. * An Idea with a registered name "workingMemory.PhonologicLoop.VowelA" * will return just "VowelA". If you need the full name assigned to the Idea, * use the getFullName() method instead. * @return The "simple name" of the given Idea */ public String getName() { return ToString.getSimpleName(name); } /** * This method returns the full name of the given Idea. * If the Idea name is a structured one, like e.g. "workingMemory.PhonologicLoop.VowelA", * this method will return the full registered name. If you want just the simple name * (in the example "VowelA", use getName() instead. * @return The full name registered for the Idea. */ public String getFullName() { return(name); } /** * Sets a new name for the Idea * @param name The new name to be assigned to the Idea */ public void setName(String name) { this.name = name; } /** This method returns the list of child Ideas associated to the current Idea. * * @return The list of Ideas associated with the current Idea */ public List<Idea> getL() { return l; } /** * This method sets a new list of associated or child Ideas, to the current Idea. * @param l The list of Ideas to substitute the old list of associated Ideas. */ public void setL(List<Idea> l) { this.l = l; } /** * This method returns the id associated to the current Idea * @return the id of the current Idea */ public long getId() { return(id); } /** * This method associates another Idea to the current Idea * @param node the Idea to be associated as a child Idea * @return the add method also returns the associated Idea, for nesting the association of Ideas with a single call. This return can be safely ignored. */ public Idea add(Idea node) { l.add(node); sort(); return(node); } /** * This static method is used to reset the list of known names used by the createIdea factory */ public static void reset() { listtoavoidloops = new CopyOnWriteArrayList<>(); } /** * This method returns a String short version of the Idea * @return the name of the Idea, used as a short version of the Idea */ public String toString() { return(name); } /** * This method returns an extended String version of the Idea. * In the case the Idea has multiple child Ideas, this method returns a multi-line String * @return a String with a multi-line version of the Idea */ public String toStringFull() { return(toStringFull(false)); } /** * This method is equivalent to the toStringFull() method, with an additional "withid" flag, to indicate if the * Idea id should be included in the String version of the Idea * @param withid a boolean flag to indicate if the id should be included (use withid = true to include the id) * @return a String with a multi-line version of the Idea, including the Idea id. */ public String toStringFull(boolean withid) { reset(); return(toStringFull(1,withid)); } private String toStringPlus(boolean withid) { String appendix = ""; String out; switch(getType()) { default: case 0: if (value != null && !value.equals("")) appendix = " ["+value+"]"; if (withid) appendix += " <"+id+">"; out = "* "+ getName()+appendix; break; case 1: if (withid) appendix += " <"+id+">"; out = "- "+getName()+": "+value+appendix; break; case 2: if (value != null && !value.equals("")) appendix = " ["+value+"]"; if (withid) appendix += " <"+id+">"; appendix += " #"; out = "* "+ getName()+appendix; } return(out); } private String toStringFull(int level, boolean withid) { String out; if (isLeaf()) { out = toStringPlus(withid)+"\n"; return out; } else { out = toStringPlus(withid)+"\n"; listtoavoidloops.add(toStringPlus(withid)); for (Idea ln : l) { for (int i=0;i<level;i++) out += " "; if (listtoavoidloops.contains(ln.toStringPlus(withid)) || already_exists(ln.toStringPlus(withid))) { out += ln.toStringPlus(withid)+"\n"; } else out += ln.toStringFull(level+1,withid); } return(out); } } /** * This method is used to search for an Idea, which is registered as a child Idea, of the current Idea. * If this Idea is named "a", and Idea "b" is associated to it, and further Idea "c" is associated to "b", * we can use this method, passing the argument "b.c" as a parameter, to receive back the "c" Idea. * In this case, we can do a.get("b.c") to receive back the "c" Idea. * @param path The path to localize the associated Idea. * @return The localized Idea, if it exists. Otherwise, it returns null. */ public Idea get(String path) { String[] spath = path.split("\\."); if (spath.length == 1) { for (Idea i : getL()) { if (i != null && i.getName() != null && spath != null && spath.length > 0) { if (i.getName().equals(spath[0])) { return i; } } } return null; } else { Idea i = this; for (String s : spath) { i = i.get(s); if (i == null) return(null); } return i; } } /** * This method returns the value of the current Idea * @return the value of the current Idea */ public Object getValue() { return value; } /** * This method sets a new value to the current Idea * @param value the new value of the Idea */ public void setValue(Object value) { this.value = value; } /** * This method returns the type of the current Idea. * Even though the type can be used for any purpose, * the following reference for Idea types is used as a reference: * 0 - AbstractObject (Existent) * 1 - Property (Existent) * 2 - Link or Reference to another Idea * 3 - QualityDimension * 4 - Episode (Existent) * 5 - Composite * 6 - Aggregate * 7 - Configuration * 8 - TimeStep * 9 - Property (Law) * 10 - AbstractObject (Law) * 11 - Episode (Law) * 12 - Property (Possibility) * 13 - AbstractObject (Possibility) * 14 - Episode (Possibility) * 15 - ActionPossibility * 16 - Action * 17 - ActionCategory * 18 - Goal * @return an integer indicating the type of the Idea */ public int getType() { return type; } /** * This method is used to set a new type for the Idea * @param type the new type assigned to the Idea */ public void setType(int type) { this.type = type; } /** * This method is used to get the category for the Idea * @return a String with the name of the Idea category */ public String getCategory() { return category; } /** * This method is used to set the category for the Idea * @param category a String with the name of the Idea category */ public void setCategory(String category) { this.category = category; } /** * This method is used to set the scope of the Idea * The scope indicates if this idea is to be interpreted as * a possibility (scope = 0), an existent (scope = 1) or a law * (scope = 2) * @return the Idea scope */ public int getScope() { return scope; } /** * This method is used to return the Idea's scope * The scope indicates if this idea is to be interpreted as * a possibility (scope = 0), an existent (scope = 1) or a law * (scope = 2) * @param scope the Idea's scope (0: possibility, 1: existent, 2:law) */ public void setScope(int scope) { this.scope = scope; } /** * This convenience method is used to test if an Idea is of a given type * @param type the type to be tested * @return a boolean indicating if the test succeeded or not. */ public boolean isType(int type) { return(this.type==type); } /** * This convenience method is used to test if the value of the current Idea is a double. * @return a boolean indicating if the value of the current Idea is a double number. */ public boolean isDouble() { if (value == null) return false; if (value instanceof Double) return true; return(false); } /** * This convenience method is used to test if the value of the current Idea is a float. * @return a boolean indicating if the value of the current Idea is a float number. */ public boolean isFloat() { if (value == null) return false; if (value instanceof Float) return true; return(false); } /** * This convenience method is used to test if the value of the current Idea is an int. * @return a boolean indicating if the value of the current Idea is an integer number. */ public boolean isInteger() { if (value == null) return false; if (value instanceof Integer) return true; return(false); } /** * This convenience method is used to test if the value of the current Idea is a long. * @return a boolean indicating if the value of the current Idea is a long number. */ public boolean isLong() { if (value == null) return false; if (value instanceof Long) return true; return(false); } /** * This convenience method is used to test if the value of the current Idea is a number. * It tests if the value is a float, a double, an int or a long. * @return a boolean indicating if the value of the current Idea is a number. */ public boolean isNumber() { if (isFloat() || isDouble() || isLong() || isInteger()) return(true); return(false); } /** * This convenience method is used to test if the value of the current Idea is a HashMap. * @return a boolean indicating if the value of the current Idea is a HashMap. */ public boolean isHashMap(){ if (value == null) return false; if (value instanceof HashMap) return true; return(false); } /** * This convenience method is used to test if the value of the current Idea is a String. * @return a boolean indicating if the value of the current Idea is a String. */ public boolean isString() { if (value == null) return false; if (value instanceof String) return true; return(false); } /** * This convenience method is used to test if the value of the current Idea is a boolean. * @return a boolean indicating if the value of the current Idea is a boolean. */ public boolean isBoolean() { if (value == null) return false; if (value instanceof Boolean) return true; return(false); } private Float tryParseFloat(String value) { Float returnValue = null; try { returnValue = Float.parseFloat(value); } catch (Exception ex) { returnValue = null; } return returnValue; } private Double tryParseDouble(String value) { Double returnValue = null; try { returnValue = Double.parseDouble(value); } catch (Exception ex) { returnValue = null; } return returnValue; } private Integer tryParseInteger(String value) { Integer returnValue = null; try { returnValue = Integer.parseInt(value); } catch (Exception ex) { returnValue = null; } return returnValue; } private Long tryParseLong(String value) { Long returnValue = null; try { returnValue = Long.parseLong(value); } catch (Exception ex) { returnValue = null; } return returnValue; } private Short tryParseShort(String value) { Short returnValue = null; try { returnValue = Short.parseShort(value); } catch (Exception ex) { returnValue = null; } return returnValue; } private Byte tryParseByte(String value) { Byte returnValue = null; try { returnValue = Byte.parseByte(value,16); } catch (Exception ex) { returnValue = null; } return returnValue; } /** * This method creates a clone of the current Idea. * In an Idea with associated Ideas, a full clone of all associated Ideas is created. * @return a cloned version of this Idea */ public Idea clone() { Idea newnode; newnode = new Idea(getName(), getValue(), getType(), getCategory(), getScope()); newnode.l = new ArrayList(); for (Idea i : getL()) { Idea ni = i.clone(); newnode.add(ni); } return newnode; } /** * This method returns a resumed value of this Idea value, in a String format. * @return A String with a resumed value of this Idea value. */ public String getResumedValue() { String result; if (isFloat() || isDouble()) { result = String.format("%4.1f",getValue()); } else { try { int trial = Integer.parseInt(getValue().toString()); result = String.format("%d",trial); } catch(Exception ee) { try { double trial = Double.parseDouble(getValue().toString()); result = String.format("%4.1f",trial); } catch(Exception e) { result = getValue().toString(); } } } return(result); } /** * This convenience method returns true if the parameter Object is a primitive Object * @param o The Object to be tested * @return true if the Object is a primitive or false if not. */ public boolean isPrimitive(Object o) { if (o == null) return(true); if (o.getClass().isPrimitive()) return(true); if (o instanceof Integer || o instanceof Long || o instanceof Double || o instanceof Float || o instanceof Boolean || o instanceof Short || o instanceof Byte) return(true); return(false); } /** * This method checks if an Idea with the Object passed as a parameter was already created. * It is used to avoid infinite loops while converting a Java Object to an Idea. * @param o The Object to be tested * @return true if there is already an Idea using this Object as a value. */ public boolean already_exists(Object o) { if (o == null || isPrimitive(o)) return false; for (Object oo : listtoavoidloops) if (oo.hashCode() == o.hashCode()) return true; return false; } /** * This method sorts the internal list of associated Ideas, using their name as a reference. */ public void sort() { Collections.sort(l, ideaComparator); } /** * This convenience method creates an Object of a given class, using the parameter class name, passed as a String * @param classname the full name of the class for the object to be created. * @return the created Object */ public static Object createJavaObject(String classname) { if (classname.equals(CDOUBLE)) { return Double.valueOf(0.0); } else if (classname.equals(CFLOAT)) { return Float.valueOf(0.0f); } else if (classname.equals(CINT)) { return Integer.valueOf(0); } else if (classname.equals(CLONG)) { return Long.valueOf(0L); } else if (classname.equals(CSHORT)) { short ret = 0; return Short.valueOf(ret); } else if (classname.equals(CBYTE)) { byte ret = 0; return Byte.valueOf(ret); } else if (classname.equals(CBOOLEAN)) { return Boolean.valueOf(false); } Class type = null; Object javaObject = null; try { type = Class.forName(classname); javaObject = type.getDeclaredConstructor().newInstance(); type.cast(javaObject); } catch (Exception e) { Logger.getAnonymousLogger().log(Level.INFO, "The class name {0} is not on the Java Library Path !", classname); } return (javaObject); } private Object convertObject(Object origin, String className) { if (origin == null) return(null); if (origin.getClass().getCanonicalName().equals(CSTRING) && ((String)origin).equalsIgnoreCase("null")) return(null); String objectClass = origin.getClass().getName(); if (className.equals("double") || className.equals(CDOUBLE)) { double value; if (objectClass.equals(CSTRING)) { value = tryParseDouble((String) origin); } else { value = ((Number) origin).doubleValue(); } return (value); } else if (className.equals("float") || className.equals(CFLOAT)) { float value; if (objectClass.equals(CSTRING)) { value = tryParseFloat((String) origin); } else { value = ((Number) origin).floatValue(); } return (value); } else if (className.equals("long") || className.equals(CLONG)) { long value; if (objectClass.equals(CSTRING)) { value = tryParseLong((String) origin); } else { value = ((Number) origin).longValue(); } return (value); } else if (className.equals("int") || className.equals(CINT)) { int value; if (objectClass.equals(CSTRING)) { value = tryParseInteger((String) origin); } else { value = ((Number) origin).intValue(); } return (value); } else if (className.equals("short") || className.equals(CSHORT)) { short value; if (objectClass.equals(CSTRING)) { value = tryParseShort((String) origin); } else { value = ((Number) origin).shortValue(); } return (value); } else if (className.equals("byte") || className.equals(CBYTE)) { Byte value; if (objectClass.equals(CSTRING)) { value = tryParseByte((String) origin); } else { value = ((Number) origin).byteValue(); } return (value); } else if (className.equals("boolean") || className.equals(CBOOLEAN)) { boolean value; if (objectClass.equals(CSTRING)) { if (((String)origin).equals("true")) value = true; else value = false; } else { value = false; } return (value); } else if (className.equals("java.util.Date")) { Date value; try { SimpleDateFormat parser = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS"); parser.setTimeZone(TimeZone.getTimeZone("GMT")); value = parser.parse((String) origin); } catch(Exception e) { value = null; } return (value); } else return (origin); } private Object mountArray(Idea o, String classname) { if (classname.equals("int[]")) { int[] out = new int[o.getL().size()]; int j=0; for (Idea i : o.getL()) { out[j++] = (Integer) convertObject(i.getValue(),CINT); } return(out); } else if (classname.equals("double[]")) { double[] out = new double[o.getL().size()]; int j=0; for (Idea i : o.getL()) { out[j++] = (Double) convertObject(i.getValue(),CDOUBLE); } return(out); } else if (classname.equals("float[]")) { float[] out = new float[o.getL().size()]; int j=0; for (Idea i : o.getL()) { out[j++] = (Float) convertObject(i.getValue(),CFLOAT); } return(out); } else if (classname.equals("long[]")) { long[] out = new long[o.getL().size()]; int j=0; for (Idea i : o.getL()) { out[j++] = (Long) convertObject(i.getValue(),CLONG); } return(out); } else if (classname.equals("short[]")) { short[] out = new short[o.getL().size()]; int j=0; for (Idea i : o.getL()) { out[j++] = (Short) convertObject(i.getValue(),CSHORT); } return(out); } else if (classname.equals("byte[]")) { byte[] out = new byte[o.getL().size()]; int j=0; for (Idea i : o.getL()) { out[j++] = (Byte) convertObject(i.getValue(),CBYTE); } return(out); } else if (classname.equals("boolean[]")) { boolean[] out = new boolean[o.getL().size()]; int j=0; for (Idea i : o.getL()) { out[j++] = (Boolean) convertObject(i.getValue(),CBOOLEAN); } return(out); } else { Object out=null; String realclassname = classname.split("\\[\\]")[0]; try { Class<?> c = Class.forName(realclassname); out = Array.newInstance(c,o.getL().size()); } catch(Exception e) { e.printStackTrace(); } int j=0; for (Idea i : o.getL()) { if (i.getL().size() > 0) { Array.set(out, j++,getObject(o.getName()+"."+i.getName(),realclassname) ); } else Array.set(out,j++,null); } return(out); } } private boolean isArray(String classname) { String sname[] = classname.split("\\["); if (sname.length == 2) return true; else return false; } /** * This method tries to get an internal Idea and convert it to a Java Object of the indicated class * * @param name The name of the internal Idea to be get * @param classname The name of the Java Class to be used for conversion * @return a new Java Object reflecting the desired Idea */ public Object getObject(String name, String classname) { if (classname.equals(CDOUBLE) || classname.equals(CFLOAT) || classname.equals(CINT) || classname.equals(CLONG) || classname.equals(CSHORT) || classname.equals(CBYTE) || classname.equals(CSTRING) || classname.equals("java.util.Date") ) { return convertObject(getValue(),classname); } if (isArray(classname)) { Idea i = get(name); if (i != null) { return mountArray(i,classname); } else { return null; } } if (classname.equals("java.util.List")) { classname = "java.util.ArrayList"; } Object ret = createJavaObject(classname); if (ret == null) return(null); try { Field[] fieldList = ret.getClass().getDeclaredFields(); for (Field field : fieldList) { String fieldClass = field.getType().getCanonicalName(); Idea o = get(name+"."+field.getName()); if (o == null) { //System.out.println("I was not able to get "+getFullName()+"."+name+"."+field.getName()); } else { if (field.getType().isArray()) { Object out = mountArray(o,field.getType().getCanonicalName()); try { field.setAccessible(true); field.set(ret,out); } catch(Exception e) { System.out.println(e.getMessage()); System.out.println("Array "+field.getName()+" should be of type "+field.getType().getCanonicalName()+" but I received "+value.toString()+": "+value.getClass().getCanonicalName()+""); } } else if (field.getType().getCanonicalName().equals("java.util.List")) { List out = new ArrayList(); for (Idea i : o.getL()) { ParameterizedType type = (ParameterizedType) field.getGenericType(); String stype = type.getActualTypeArguments()[0].getTypeName(); out.add(i.getObject(i.getName(), stype)); } try { field.setAccessible(true); field.set(ret,out); } catch(Exception e) { System.out.println("Field "+field.getName()+" should be of type "+field.getType().getCanonicalName()+" but I received "+value.toString()+": "+value.getClass().getCanonicalName()+""); } } else { Object value = o.getValue(); if (value == null) System.out.println("Warning: value of "+field.getName()+" is null"); value = convertObject(value,field.getType().getCanonicalName()); try { field.setAccessible(true); field.set(ret,value); } catch(Exception e) { o = get(name); Object out; if (o.getL().size() > 0) out = o.getObject(field.getName(),field.getType().getCanonicalName()); else out = null; try { field.setAccessible(true); field.set(ret,out); } catch(Exception e2) { if (value != null) System.out.println(">> Field "+field.getName()+" should be of type "+field.getType().getCanonicalName()+" but I received "+value.toString()+": "+value.getClass().getCanonicalName()); else System.out.println(">> Field "+field.getName()+" should be of type "+field.getType().getCanonicalName()+" but I received <null>"); } } } } } } catch (Exception e) { e.printStackTrace(); System.out.println("Exception: " + e.getStackTrace().toString()); } return(ret); } /** * This method uses a Java Object as template, creating an Idea with a similar structure. * This new Idea is added to the current Idea * @param obj The Java Object to be used as a template * @param fullname the full name to be assigned to added Idea */ public synchronized void addObject(Object obj, String fullname) { addObject(obj,fullname,true); } /** * This method uses a Java Object as template, creating an Idea with a similar structure. * This new Idea is added to the current Idea. This version allows the global list of names * to be reset * @param obj The Java Object to be used as a template. * @param fullname The full name to be assigned to the added Idea. * @param reset a boolean flag indicating if the global list of names should be reset. */ public synchronized void addObject(Object obj, String fullname, boolean reset) { if (reset) reset(); if (obj == null) { Idea child = createIdea(getFullName()+"."+fullname,"null",0); add(child); return; } if (listtoavoidloops.contains(obj) || already_exists(obj)) { Idea child = createIdea(getFullName()+"."+fullname,obj.toString(),2); Idea alternative = repo.get(getFullName()+"."+fullname); if (alternative != null) System.out.println("Ah ... I already found "+getFullName()+"."+fullname); else System.out.println("Strange ... it seems that "+getFullName()+"."+fullname+" is already in the repo but I can't find it"); add(child); return; } String s = ToString.from(obj); if (s != null) { Idea child = createIdea(getFullName()+"."+fullname,s,1); add(child); return; } else if (obj.getClass().isArray()) { int l = Array.getLength(obj); String type = obj.getClass().getSimpleName(); if (l>0) { Object otype = Array.get(obj,0); if (otype != null) type = otype.getClass().getSimpleName(); } else { type = type.split("\\[\\]")[0]; } if (type.equalsIgnoreCase("Double") || type.equalsIgnoreCase("Integer") || type.equalsIgnoreCase("String") || type.equalsIgnoreCase("Float") || type.equalsIgnoreCase("Long") || type.equalsIgnoreCase("Boolean") || type.equalsIgnoreCase("Short") || type.equalsIgnoreCase("Byte") ) { Idea anode = Idea.createIdea(getFullName()+"."+fullname,"",0); for (int i=0;i<l;i++) { Object oo = Array.get(obj,i); Idea node = createIdea(ToString.el(getFullName()+"."+fullname, i),oo,1); anode.add(node); } this.add(anode); } else { Idea onode = createIdea(getFullName()+"."+fullname,"",0); for (int i=0;i<l;i++) { Object oo = Array.get(obj,i); onode.addObject(oo,ToString.el(fullname,i),false); listtoavoidloops.add(obj); } this.add(onode); } return; } else if (obj instanceof List) { List ll = (List) obj; String label = ""; if (ll.size() > 0) label = "{"+ll.size()+"} of "+ll.get(0).getClass().getSimpleName(); else label = "{0}"; Idea onode = createIdea(getFullName()+"."+fullname,label,0); int i=0; for (Object o : ll) { onode.addObject(o,ToString.el(ToString.getSimpleName(fullname),i),false); listtoavoidloops.add(obj); i++; } this.add(onode); return; } else if (obj instanceof Idea) { Idea ao = (Idea) obj; this.add(ao); listtoavoidloops.add(obj); return; } else { Idea ao = createIdea(getFullName()+"."+ToString.getSimpleName(fullname),"",0); listtoavoidloops.add(obj); Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { String fname = field.getName(); try { field.setAccessible(true); Object fo=null; try { fo = field.get(obj); } catch (Exception e) { e.printStackTrace();} if (!already_exists(fo)) { ao.addObject(fo,fname,false); } else { String ideaname = getFullName()+"."+ToString.getSimpleName(fullname)+"."+fname; Idea fi = createIdea(ideaname,"",2); Idea alternative2 = null; if (!Modifier.isStatic(field.getModifiers())) { for (Map.Entry<String,Idea> entry : repo.entrySet()) { String key = entry.getKey(); Idea v = entry.getValue(); if (ToString.getSimpleName(ideaname).equals(ToString.getSimpleName(key))) { System.out.println("The Idea "+ideaname+" is already in the repository"); } } System.out.println(fo.getClass().getCanonicalName()); Idea alternative = repo.get(ideaname); if (alternative != null) System.out.println("Ah ... I already found "+ideaname); else System.out.println("Strange ... it seems that "+ideaname+" is already in the repo but I can't find it"); } ao.add(fi); } } catch (Exception e) { } } this.add(ao); return; } } /** * This method can be called from an Idea, it the Idea is a Habit. * It executes the Habit without the necessity to first recover the Habit from the Idea * @param idea an Idea passed as a parameter to the Habit. Can be null if no parameter is required * @return an Idea, which is the result of the Habit execution. Can be null */ @Override public Idea exec(Idea idea) { if (isHabit()) { Habit h = (Habit) getValue(); return(h.exec(idea)); } else return(null); } public Idea getInstance() { return getInstance(null); } @Override public Idea getInstance(Idea constraints ) { if (getValue() instanceof Category) { Category c = (Category) getValue(); return(c.getInstance(constraints)); } return(null); } @Override public double membership(Idea idea) { if (getValue() instanceof Category) { Category c = (Category) getValue(); return(c.membership(idea)); } return(0.0); } /** * This method returns true if the present Idea is a Category, i.e., have a Category as its value. * If it is a Habit, an user can call the methods instantiation and membership from this Idea * @return true if this idea is a Category or false otherwise */ public boolean isCategory() { if (getValue() instanceof Category) return(true); else return(false); } /** * This method returns true if the present Idea is a Habit, i.e., have a Habit as its value. * If it is a Habit, an user can call the method exec (or exec0) from this Idea * @return true if this idea is a Habit or false otherwise */ public boolean isHabit() { if (getValue() instanceof Habit) return(true); else return(false); } /** * This method returns true if the present Idea is a Leaf, i.e., does not have any children Idea * @return true if this idea is a leaf or false otherwise */ public boolean isLeaf() { return this.l.isEmpty(); } }
48,403
36.609946
217
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/idea/IdeaComparator.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.representation.idea; import java.util.Comparator; /** * * @author rgudwin */ public class IdeaComparator implements Comparator { private final boolean order; public IdeaComparator() { this(true); } public IdeaComparator(boolean order) { this.order = order; } int getInt(String s) { int n; try { n = Integer.parseInt(s); } catch(Exception e) { return(Integer.MIN_VALUE); } return(n); } int getNumber(String name) { String[] splitter = name.split("\\["); if (splitter.length > 1) { return(getInt(splitter[1].split("\\]")[0].trim())); } else return Integer.MIN_VALUE; } @Override public int compare(Object o1, Object o2) { Idea i1 = (Idea) o1; Idea i2 = (Idea) o2; int try1 = getNumber(i1.getName()); int try2 = getNumber(i2.getName()); if (try1 != Integer.MIN_VALUE && try2 != Integer.MIN_VALUE) { if (try1 > try2) return(1); else return(-1); } if (i1.getName().startsWith("operator") && !i2.getName().startsWith("operator")) return(1); else if(!i1.getName().startsWith("operator") && i2.getName().startsWith("operator")) return(-1); else if (i1.getType() == i2.getType() || i1.getType() == 0 && i2.getType() == 2 || i1.getType() == 2 && i2.getType() == 0) { return i1.getName().compareTo(i2.getName()); } else if (i1.getType() == 1 && i2.getType() == 0 || i1.getType() == 1 && i2.getType() == 2 || i1.getType() == 2 && i2.getType() == 0 ) { return(1); } else return(-1); } }
2,577
33.837838
147
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/owrl/AbstractObject.java
/** * **************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * S. M. de Paula and R. R. Gudwin * **************************************************************************** */ package br.unicamp.cst.representation.owrl; import br.unicamp.cst.language.NameGenerator; import br.unicamp.cst.support.ToString; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.util.*; import java.util.stream.Collectors; /** * @author Suelen Mapa and Eduardo Froes. */ public class AbstractObject implements Cloneable, Entity { private List<Property> properties;//1-n; private List<AbstractObject> compositeList;//1-n; private List<AbstractObject> aggregateList;//1-n; private List<Affordance> affordances; private String name; public AbstractObject(String name) { setName(name); setProperties(new ArrayList<Property>()); setCompositeList(new ArrayList<AbstractObject>()); setAggregateList(new ArrayList<AbstractObject>()); setAffordances(new ArrayList<>()); } public AbstractObject(String name, List<Property> props) { setName(name); setProperties(props); setCompositeList(new ArrayList<AbstractObject>()); setAggregateList(new ArrayList<AbstractObject>()); setAffordances(new ArrayList<>()); } public AbstractObject(String name, List<Property> props, List<AbstractObject> composite, List<AbstractObject> aggregate) { setName(name); setCompositeParts(composite); setAggregatePart(aggregate); setProperties(props); setAffordances(new ArrayList<>()); } public AbstractObject(String name, List<Property> props, List<AbstractObject> composite) { setName(name); setCompositeParts(composite); setProperties(props); setAffordances(new ArrayList<>()); } public AbstractObject(List<AbstractObject> aggregate, List<Property> props, String name) { setName(name); setAggregatePart(aggregate); setProperties(props); setAffordances(new ArrayList<>()); } public AbstractObject(File file) { String line; //AbstractObject newAO = null; List<Entity> parseAOs = new ArrayList<Entity>(); try { BufferedReader reader = new BufferedReader(new FileReader(file)); while ((line = reader.readLine()) != null) { String linesplitted[] = line.split(" "); int level = getLevel(linesplitted); mode m = getMode(linesplitted); String name = getName(linesplitted); String value = getValue(linesplitted); AbstractObject ao; AbstractObject father; Property pfather; if (level == 0) { setName(name); setProperties(new ArrayList<Property>()); setCompositeList(new ArrayList<AbstractObject>()); setAggregateList(new ArrayList<AbstractObject>()); setAffordances(new ArrayList<>()); parseAOs.add(this); } else { switch(m) { case COMPOSITE:ao = new AbstractObject(name); parseAOs.add(ao); father = (AbstractObject) parseAOs.get(level-1); father.addCompositePart(ao); if (level >= parseAOs.size()) parseAOs.add(ao); else parseAOs.set(level, ao); break; case AGGREGATE:ao = new AbstractObject(name); parseAOs.add(ao); father = (AbstractObject) parseAOs.get(level-1); father.addAggregatePart(ao); if (level >= parseAOs.size()) parseAOs.add(ao); else parseAOs.set(level, ao); break; case PROPERTY:Property p = new Property(name); father = (AbstractObject) parseAOs.get(level-1); father.addProperty(p); if (level >= parseAOs.size()) parseAOs.add(p); else parseAOs.set(level, p); break; case QUALITY_DIMENSION:QualityDimension qd = new QualityDimension(name,value); pfather = (Property) parseAOs.get(level-1); pfather.addQualityDimension(qd); break; } } //System.out.println(line+" -> level: "+level+" mode: "+m+" name: "+name+" value: "+value); } reader.close(); } catch (Exception e) {e.printStackTrace();} } public enum mode {NULL, COMPOSITE, AGGREGATE, PROPERTY, QUALITY_DIMENSION} private int getLevel(String splitted[]) { int level = 0; for (int i=0;i<splitted.length;i++) { if (splitted[i].equals("")) level++; } return(level/3); } private mode getMode(String splitted[]) { mode m = mode.NULL; for (int i=0;i<splitted.length;i++) { if (splitted[i].equals("*")) { m = mode.COMPOSITE; break; } if (splitted[i].equals("+")) { m = mode.AGGREGATE; break; } if (splitted[i].equals(">")) { m = mode.PROPERTY; break; } if (splitted[i].equals("-")) { m = mode.QUALITY_DIMENSION; break; } } return(m); } private String getName(String splitted[]) { int level = getLevel(splitted); if (level == 0) return(splitted[0]); else return(splitted[3*level+1]); } private String getValue(String splitted[]) { String value = ""; for (int i=0;i<splitted.length;i++) { if (splitted[i].equals(":")) { value = splitted[i+1]; break; } } return(value); } public List<Object> search(String path) { path = path.trim(); int dot = path.indexOf("."); String name = path; String subPath = null; if (dot > -1) { name = path.substring(0, dot); subPath = path.substring(dot + 1); } List<Object> results = new ArrayList<>(); if (getName().equals(name)) { if (subPath != null) { results.addAll(search(subPath)); } else { results.add(this); } } for (AbstractObject composite : getCompositeList()) { if (composite.getName().equals(name)) { if (subPath != null) { results.addAll(composite.search(subPath)); } else { results.add(composite); } } results.addAll(composite.search(path)); } for (AbstractObject aggregate : getAggregateList()) { if (aggregate.getName().equals(name)) { if (subPath != null) { results.addAll(aggregate.search(subPath)); } else { results.add(aggregate); } } results.addAll(aggregate.search(path)); } for (Property property : getProperties()) { if (property.getName().equals(name)) { if (subPath != null) { results.addAll(property.search(subPath)); } else { results.add(property); } } results.addAll(property.search(path)); } for (Affordance affordance : affordances) { if (affordance.getName().equals(name)) { results.add(affordance); } } return results; } public void delete(String path) { String parentPath = null; String name = path; int dot = path.lastIndexOf("."); if (dot > -1) { parentPath = path.substring(0, dot); name = path.substring(dot + 1); } Object parent = this; List<Object> children = new ArrayList<>(); if (parentPath != null) { List<Object> parents = search(parentPath); int p = parents.size(); do { p--; parent = parents.get(p); if (parent instanceof AbstractObject) { children = ((AbstractObject) parent).search(name); } else { children = ((Property) parent).search(name); } } while (p > 0 && children.isEmpty()); } else { children = search(name); } if (!children.isEmpty()) { Object child = children.get(children.size() - 1); if (parent instanceof AbstractObject) { AbstractObject ao = (AbstractObject) parent; if (child instanceof AbstractObject) { ao.removeAggregatePart((AbstractObject) child); ao.removeCompositePart((AbstractObject) child); } else { ao.removeProperty((Property) child); } } else { ((Property) parent).deleteChild(child); } } } public boolean detectAffordance(HashMap<String, AbstractObject> aggregateObjects, HashMap<String, AbstractObject> compositeObjects, HashMap<String, Property> modifiedProperties) { final boolean[] bVerify = {true}; if (getAffordances().size() != 0) { getAffordances().stream().forEach(affordance -> { aggregateObjects.entrySet().stream().forEach(aggrDetect -> { Optional<Map.Entry<String, AbstractObject>> first = affordance.getAggregateDetectorObjects().entrySet().stream().filter(aggr -> aggr.getKey().equals(aggrDetect.getKey()) && aggr.getValue().getName().equals(aggrDetect.getValue().getName())).findFirst(); if (!first.isPresent()) { bVerify[0] = false; return; } }); compositeObjects.entrySet().stream().forEach(compDetect -> { Optional<Map.Entry<String, AbstractObject>> first = affordance.getCompositeDetectorObjects().entrySet().stream().filter(comp -> comp.getKey().equals(compDetect.getKey()) && comp.getValue().getName().equals(compDetect.getValue().getName())).findFirst(); if (!first.isPresent()) { bVerify[0] = false; return; } }); modifiedProperties.entrySet().stream().forEach(propDetect -> { Optional<Map.Entry<String, Property>> first = affordance.getPropertyDetectorObjects().entrySet().stream().filter(prop -> prop.getKey().equals(propDetect.getKey()) && prop.getValue().getName().equals(propDetect.getValue().getName())).findFirst(); if (!first.isPresent()) { bVerify[0] = false; return; } }); }); } if (bVerify[0]) { return false; } else { return true; } } public void discoveryAffordance(AbstractObject after, List<AbstractObject> path) { HashMap<String, AbstractObject> aggregateObjects = verifyAbstractObjectsStatus(after.getAggregateParts(), getAggregateParts()); HashMap<String, AbstractObject> compositeObjects = verifyAbstractObjectsStatus(after.getCompositeParts(), getCompositeParts()); HashMap<String, Property> modifiedProperties = verifyPropertiesStatus(path); if (!detectAffordance(aggregateObjects, compositeObjects, modifiedProperties)) { Pair<String, String> applyCode = createApplyCode(aggregateObjects, compositeObjects, modifiedProperties); Pair<String, String> detectorCode = createDetectorCode(aggregateObjects, compositeObjects, modifiedProperties); if (applyCode != null && detectorCode != null) { DynamicAffordance newAffordance = new DynamicAffordance((new NameGenerator()).generateWord(), applyCode.getFirst(), applyCode.getSecond(), detectorCode.getFirst(), detectorCode.getSecond(), aggregateObjects, compositeObjects, modifiedProperties); this.addAffordance(newAffordance); getAggregateParts().forEach( aggr -> { Optional<AbstractObject> gotAggr = after.getAggregateParts().stream().filter(aAggr -> aAggr.getName().equals(aggr.getName())).findFirst(); if(gotAggr.isPresent()){ List<AbstractObject> pathAggr = new ArrayList<AbstractObject>(); path.stream().forEach(p -> pathAggr.addAll(p.getAggregateParts().stream().filter(pAggr -> pAggr.getName().equals(aggr.getName())).collect(Collectors.toList()))); aggr.discoveryAffordance(gotAggr.get(), pathAggr); } }); getCompositeParts().forEach( comp -> { Optional<AbstractObject> gotComp = after.getCompositeParts().stream().filter(aAggr -> aAggr.getName().equals(comp.getName())).findFirst(); if(gotComp.isPresent()){ List<AbstractObject> pathComp = new ArrayList<AbstractObject>(); path.stream().forEach(p -> pathComp.addAll(p.getCompositeParts().stream().filter(pAggr -> pAggr.getName().equals(comp.getName())).collect(Collectors.toList()))); comp.discoveryAffordance(gotComp.get(), pathComp); } }); } } } private Pair<String, String> createDetectorCode(HashMap<String, AbstractObject> aggregateObjects, HashMap<String, AbstractObject> compositeObjects, HashMap<String, Property> properties) { List<String> methodCodeIfStatement = new ArrayList<>(); List<String> methodParameterDetector = new ArrayList<>(); String className = "Detector" + this.getName().replace(" ", ""); String abstractObjectParameter = "AbstractObject " + this.getName().replace(" ", "").toLowerCase(); methodParameterDetector.add(abstractObjectParameter); CodeBuilder codeBuilderDetector = new CodeBuilder(className); codeBuilderDetector.addImports("java.util.List"); codeBuilderDetector.addImports("br.unicamp.cst.representation.owrl.AbstractObject"); codeBuilderDetector.addImports("br.unicamp.cst.representation.owrl.Property"); String methodCode = "if(@CONDITION){" + "return true;" + "}" + "else{" + "return false;" + "}"; if (aggregateObjects != null) { aggregateObjects.entrySet().stream().forEach(aggregateAO -> { String aggregateParameter = ""; if (aggregateAO.getKey() == "added") { aggregateParameter = "AbstractObject added" + aggregateAO.getValue().getName().replace(" ", "") + "AO"; methodCodeIfStatement.add(this.getName().replace(" ", "").toLowerCase() + ".getAggregateParts().stream().filter(oa -> oa.getName().equals(added" + aggregateAO.getValue().getName().replace(" ", "") + "AO.getName())).findFirst().isPresent()"); } else { aggregateParameter = "AbstractObject removed" + aggregateAO.getValue().getName().replace(" ", "") + "AO"; methodCodeIfStatement.add("!" + this.getName().replace(" ", "").toLowerCase() + ".getAggregateParts().stream().filter(oa -> oa.getName().equals(removed" + aggregateAO.getValue().getName().replace(" ", "") + "AO.getName())).findFirst().isPresent()"); } methodParameterDetector.add(aggregateParameter); }); } if (compositeObjects != null) { compositeObjects.entrySet().stream().forEach(compositeAO -> { String compositeParameter = ""; if (compositeAO.getKey() == "added") { compositeParameter = "AbstractObject added" + compositeAO.getValue().getName().replace(" ", "") + "CO"; methodCodeIfStatement.add(this.getName().replace(" ", "").toLowerCase() + ".getCompositeParts().stream().filter(oa -> oa.getName().equals(added" + compositeAO.getValue().getName().replace(" ", "") + "CO.getName())).findFirst().isPresent()"); } else { compositeParameter = "AbstractObject removed" + compositeAO.getValue().getName().replace(" ", "") + "CO"; methodCodeIfStatement.add("!" + this.getName().replace(" ", "").toLowerCase() + ".getCompositeParts().stream().filter(oa -> oa.getName().equals(removed" + compositeAO.getValue().getName().replace(" ", "") + "CO.getName())).findFirst().isPresent()"); } methodParameterDetector.add(compositeParameter); }); } if (properties != null) { properties.entrySet().stream().forEach(property -> { String propertyParameter = ""; if (property.getKey() == "added") { propertyParameter = "Property added" + property.getValue().getName().replace(" ", ""); methodCodeIfStatement.add(this.getName().replace(" ", "").toLowerCase() + ".getProperties().stream().filter(oa -> oa.getName().equals(added" + property.getValue().getName().replace(" ", "") + ".getName())).findFirst().isPresent()"); } else { if (property.getKey() == "removed") { propertyParameter = "Property removed" + property.getValue().getName().replace(" ", ""); methodCodeIfStatement.add("!" + this.getName().replace(" ", "").toLowerCase() + ".getProperties().stream().filter(oa -> oa.getName().equals(removed" + property.getValue().getName().replace(" ", "") + ".getName())).findFirst().isPresent()"); } else { propertyParameter = "Property mod" + property.getValue().getName().replace(" ", ""); methodCodeIfStatement.add(this.getName().replace(" ", "").toLowerCase() + ".getProperties().stream().filter(oa -> oa.getName().equals(mod" + property.getValue().getName().replace(" ", "") + ".getName())).findFirst().get().equals(mod" + property.getValue().getName().replace(" ", "") + ")"); } } methodParameterDetector.add(propertyParameter); }); } if (methodParameterDetector.size() != 0 && methodCodeIfStatement.size() != 0) { codeBuilderDetector.addMethod("public", "boolean", "detect", methodParameterDetector, methodCode.replace("@CONDITION", String.join(" &&\n", methodCodeIfStatement)), false); return new Pair<String, String>(codeBuilderDetector.getFullClassName(), codeBuilderDetector.buildClassCode()); } else { return null; } } private Pair<String, String> createApplyCode(HashMap<String, AbstractObject> aggregateObjects, HashMap<String, AbstractObject> compositeObjects, HashMap<String, Property> properties) { List<String> methodCodeApply = new ArrayList<>(); List<String> methodParameterApply = new ArrayList<>(); String className = "Apply" + this.getName().replace(" ", ""); String abstractObjectParameter = "AbstractObject " + this.getName().replace(" ", "").toLowerCase(); methodParameterApply.add(abstractObjectParameter); CodeBuilder codeBuilderApply = new CodeBuilder(className); codeBuilderApply.addImports("java.util.List"); codeBuilderApply.addImports("br.unicamp.cst.representation.owrl.AbstractObject"); codeBuilderApply.addImports("br.unicamp.cst.representation.owrl.Property"); if (aggregateObjects != null) { aggregateObjects.entrySet().stream().forEach(aggregateAO -> { String aggregateParameter = ""; if (aggregateAO.getKey() == "added") { aggregateParameter = "AbstractObject add" + aggregateAO.getValue().getName().replace(" ", "") + "AO"; methodCodeApply.add(this.getName().replace(" ", "").toLowerCase() + ".getAggregateParts().add(add" + aggregateAO.getValue().getName().replace(" ", "") + "AO);"); } else { aggregateParameter = "AbstractObject remove" + aggregateAO.getValue().getName().replace(" ", "") + "AO"; methodCodeApply.add(this.getName().replace(" ", "").toLowerCase() + ".getAggregateParts().removeIf(agg -> agg.getName().equals(remove" + aggregateAO.getValue().getName().replace(" ", "") + "AO.getName()));"); } methodParameterApply.add(aggregateParameter); }); } if (compositeObjects != null) { compositeObjects.entrySet().stream().forEach(compositeAO -> { String compositeParameter = ""; if (compositeAO.getKey() == "added") { compositeParameter = "AbstractObject add" + compositeAO.getValue().getName().replace(" ", "") + "CO"; methodCodeApply.add(this.getName().replace(" ", "").toLowerCase() + ".getCompositeParts().add(add" + compositeAO.getValue().getName().replace(" ", "") + "CO);"); } else { compositeParameter = "AbstractObject remove" + compositeAO.getValue().getName().replace(" ", "") + "CO"; methodCodeApply.add(this.getName().toLowerCase() + ".getCompositeParts().removeIf(comp -> comp.getName().equals(remove" + compositeAO.getValue().getName().replace(" ", "") + "CO.getName()));"); } methodParameterApply.add(compositeParameter); }); } if (properties != null) { properties.entrySet().stream().forEach(property -> { String propertyParameter = ""; if (property.getKey() == "added") { propertyParameter = "Property add" + property.getValue().getName().replace(" ", ""); methodCodeApply.add(this.getName().replace(" ", "").toLowerCase() + ".getProperties().add(add" + property.getValue().getName().replace(" ", "") + ");"); } else { if (property.getKey() == "removed") { propertyParameter = "Property remove" + property.getValue().getName().replace(" ", ""); methodCodeApply.add(this.getName().toLowerCase() + ".getProperties().removeIf(prop -> prop.getName().equals(remove" + property.getValue().getName().replace(" ", "") + ".getName()));"); } else { propertyParameter = "Property mod" + property.getValue().getName().replace(" ", ""); methodCodeApply.add(this.getName().toLowerCase() + ".getProperties().removeIf(prop -> prop.getName().equals(mod" + property.getValue().getName().replace(" ", "") + ".getName()));"); methodCodeApply.add(this.getName().replace(" ", "").toLowerCase() + ".getProperties().add(mod" + property.getValue().getName().replace(" ", "") + ");"); } } methodParameterApply.add(propertyParameter); }); } if (methodParameterApply.size() != 0 && methodCodeApply.size() != 0) { codeBuilderApply.addMethod("public", "void", "apply", methodParameterApply, String.join("\n", methodCodeApply), false); return new Pair<String, String>(codeBuilderApply.getFullClassName(), codeBuilderApply.buildClassCode()); } else { return null; } } private HashMap<String, Property> verifyPropertiesStatus(List<AbstractObject> path) { List<AbstractObject> pathWithRoot = new ArrayList<>(); pathWithRoot.add(this); pathWithRoot.addAll(path); HashMap<String, Property> properties = new HashMap<>(); for (int i = 0; i < path.size(); i++) { HashMap<String, Property> checkProperties = new HashMap<>(); if (i + 1 > path.size()) break; int finalI = i; pathWithRoot.get(i).getProperties().forEach(propertyFirst -> { Optional<Property> propertyOptional = pathWithRoot.get(finalI + 1).getProperties().stream().filter(propertySecond -> propertySecond.getName().equals(propertyFirst.getName())).findFirst(); if (propertyOptional.isPresent()) { if (!propertyFirst.equals(propertyOptional.get())) { if (!checkProperties.containsValue(propertyOptional.get())) { checkProperties.put("modified", propertyOptional.get().clone()); } } } else { checkProperties.put("removed", propertyFirst.clone()); } }); pathWithRoot.get(i + 1).getProperties().forEach(propertySecond -> { Optional<Property> propertyOptional = pathWithRoot.get(finalI).getProperties().stream().filter(propertyFirst -> propertySecond.getName().equals(propertySecond.getName())).findFirst(); if (!propertyOptional.isPresent()) { checkProperties.put("added", propertySecond.clone()); } }); if (checkProperties.size() == 0) { break; } else { properties.putAll(checkProperties); } } return properties; } private HashMap<String, AbstractObject> verifyAbstractObjectsStatus(List<AbstractObject> abstractObjectsAfter, List<AbstractObject> abstractObjectsBefore) { HashMap<String, AbstractObject> abstractObjects = new HashMap<>(); abstractObjectsAfter.stream().forEach(abstractObjectAfter -> { Optional<AbstractObject> first = abstractObjectsBefore.stream().filter(abstractObjectBefore -> abstractObjectBefore.getName().equals(abstractObjectAfter.getName())).findFirst(); if (!first.isPresent()) { abstractObjects.put("added", abstractObjectAfter.clone()); } }); abstractObjectsBefore.stream().forEach(abstractObjectBefore -> { Optional<AbstractObject> first = abstractObjectsAfter.stream().filter(abstractObjectAfter -> abstractObjectAfter.getName().equals(abstractObjectBefore.getName())).findFirst(); if (!first.isPresent()) { abstractObjects.put("removed", abstractObjectBefore.clone()); } }); return abstractObjects; } public List<AbstractObject> getCompositeParts() { return getCompositeList(); } public void setCompositeParts(List<AbstractObject> parts) { this.setCompositeList(parts); } public void addCompositePart(AbstractObject part) { getCompositeList().add(part); } public void removeCompositePart(AbstractObject part) { getCompositeList().remove(part); } public List<AbstractObject> getAggregateParts() { return getAggregateList(); } public void setAggregatePart(List<AbstractObject> aggregatedList) { this.setAggregateList(aggregatedList); } public void addAggregatePart(AbstractObject part) { getAggregateList().add(part); } public void removeAggregatePart(AbstractObject part) { getAggregateList().remove(part); } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Property> getProperties() { return properties; } public void setProperties(List<Property> props) { this.properties = props; } public void addProperty(Property prop) { getProperties().add(prop); } public void addProperty(String prop, Object value) { Property p = new Property(prop,value); addProperty(p); } public void removeProperty(Property prop) { getProperties().remove(prop); } public List<Affordance> getAffordances() { return affordances; } public void setAffordances(List<Affordance> affordances) { this.affordances = affordances; } @Override public AbstractObject clone() { List<Property> newProperties = new ArrayList<>(); for (Property p : getProperties()) { newProperties.add(p.clone()); } List<AbstractObject> newComposite = new ArrayList<>(); for (AbstractObject wo : getCompositeParts()) { newComposite.add(wo.clone()); } List<AbstractObject> newAggregate = new ArrayList<>(); for (AbstractObject wo : getAggregateParts()) { newAggregate.add(wo.clone()); } AbstractObject result = new AbstractObject(getName(), newProperties, newComposite, newAggregate); result.setAffordances(getAffordances()); return result; } public void deleteChild(Object child) { String childclass = child.getClass().getCanonicalName(); //System.out.println("Childclass: "+childclass); if (childclass.equals("br.unicamp.cst.representation.owrl.AbstractObject")) { boolean cres = getCompositeList().remove(child); boolean ares = getAggregateList().remove(child); //System.out.println("cres: "+cres+" ares: "+ares); } else if (childclass.equals("br.unicamp.cst.representation.owrl.Property")) { getProperties().remove(child); } } public void addAffordance(Affordance affordance) { this.getAffordances().add(affordance); } public List<AbstractObject> getCompositeList() { return compositeList; } public void setCompositeList(List<AbstractObject> compositeList) { this.compositeList = compositeList; } public List<AbstractObject> getAggregateList() { return aggregateList; } public void setAggregateList(List<AbstractObject> aggregateList) { this.aggregateList = aggregateList; } public String toString() { return(name); } public String toStringFull() { String out = this.toStringFull(1); return(out); } public String toStringFull(int level) { String out=""; out += name+"\n"; for (AbstractObject ao : compositeList) { for (int i=0;i<level;i++) out += " "; out += "* "+ ao.toStringFull(level+1); } for (AbstractObject ao : aggregateList) { for (int i=0;i<level;i++) out += " "; out += "+ "+ ao.toStringFull(level+1); } for (Property p : properties) { for (int i=0;i<level;i++) out += " "; out += "> "+ p.toStringFull(level+1); } return(out); } public boolean isEmpty() { if (properties.isEmpty() && compositeList.isEmpty() && aggregateList.isEmpty() && affordances.isEmpty()) return true; else return false; } transient ArrayList<Object> listtoavoidloops = new ArrayList<>(); public boolean already_exists(Object o) { for (Object oo : listtoavoidloops) if (oo.hashCode() == o.hashCode()) return true; return false; } public void addObject(Object obj, String fullname) { if (obj == null) { return; } if (listtoavoidloops.contains(obj) || already_exists(obj)) { System.out.println("Object found in listtoavoidloops"); //DefaultMutableTreeNode node = addString(obj.toString(),fullname); return; } String s = ToString.from(obj); if (s != null) { //System.out.println(ToString.getSimpleName(fullname)+" "+s); this.addProperty(ToString.getSimpleName(fullname),s); //DefaultMutableTreeNode node = addString(s,fullname); return; } else if (obj.getClass().isArray()) { int l = Array.getLength(obj); String type = obj.getClass().getSimpleName(); if (l>0) { Object otype = Array.get(obj,0); if (otype != null) type = otype.getClass().getSimpleName(); } //System.out.println("Array["+l+"] of "+type); if (type.equalsIgnoreCase("Double") || type.equalsIgnoreCase("Integer") || type.equalsIgnoreCase("String") || type.equalsIgnoreCase("Float") || type.equalsIgnoreCase("Long") || type.equalsIgnoreCase("Boolean")) { Property p = new Property(ToString.getSimpleName(fullname)); for (int i=0;i<l;i++) { Object oo = Array.get(obj,i); p.addQualityDimension(ToString.el(fullname, i),oo); } this.addProperty(p); } else { AbstractObject ao = new AbstractObject(ToString.getSimpleName(fullname)); //addAbstractObject(Item(fullname,"Array["+l+"] of "+type,obj,TreeElement.ICON_OBJECT); for (int i=0;i<l;i++) { Object oo = Array.get(obj,i); ao.addObject(oo,ToString.el(fullname, i)); } this.addCompositePart(ao); } return; } else if (obj instanceof List) { //System.out.println("Object is a list"); List ll = (List) obj; String label = ""; if (ll.size() > 0) label = "List["+ll.size()+"] of "+ll.get(0).getClass().getSimpleName(); else label = "List[0]"; AbstractObject ao = new AbstractObject(ToString.getSimpleName(fullname)); //DefaultMutableTreeNode objNode = addItem(fullname,label,obj,TreeElement.ICON_OBJECT); int i=0; for (Object o : ll) { ao.addObject(o,ToString.el(fullname,i)); i++; } this.addCompositePart(ao); return; } else if (obj instanceof AbstractObject) { System.out.println("Haha ... object is already an AbstractObject"); AbstractObject ao = (AbstractObject) obj; this.addCompositePart(ao); //DefaultMutableTreeNode objNode = addAbstractObject(fullname,ao,false); //addItem(fullname,ao.getName(),obj,TreeElement.ICON_OBJECT); listtoavoidloops.add(obj); //DefaultMutableTreeNode fieldNode = addAbstractObject(fullname,ao,false); //objNode.add(fieldNode); return; } else { //System.out.println("Object "+fullname+" : "+obj.toString()+" "+obj+" is from class "+obj.getClass().getCanonicalName()); AbstractObject ao = new AbstractObject(ToString.getSimpleName(fullname)); //DefaultMutableTreeNode objNode = addItem(fullname,obj.toString(),obj,TreeElement.ICON_OBJECT); listtoavoidloops.add(obj); Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { String fname = field.getName(); if (!field.isAccessible()) field.setAccessible(true); Object fo=null; try { fo = field.get(obj); } catch (Exception e) { e.printStackTrace();} // if (already_exists(fo)) System.out.println("Object already exists"); // if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { // System.out.println("Field "+field+" is static ... "+listtoavoidloops.size()+" hash:"+fo.hashCode()); // for (Object o : listtoavoidloops) { // System.out.println(o.hashCode()); // } // } //if (!java.lang.reflect.Modifier.isStatic(field.getModifiers())) if (fo != null && !already_exists(fo)) ao.addObject(fo,fullname+"."+fname); //objNode.add(fieldNode); } this.addCompositePart(ao); return; } } }
39,050
41.539216
203
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/owrl/Affordance.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.representation.owrl; import java.util.HashMap; /** * Created by du on 23/05/17. */ public abstract class Affordance { private String name; private HashMap<String, AbstractObject> aggregateDetectorObjects; private HashMap<String, AbstractObject> compositeDetectorObjects; private HashMap<String, Property> propertyDetectorObjects; public Affordance(String name) { setName(name); } public Affordance(String name, HashMap<String, AbstractObject> aggregateDetectorObjects, HashMap<String, AbstractObject> compositeDetectorObjects, HashMap<String, Property> propertyDetectorObjects) { setName(name); setAggregateDetectorObjects(aggregateDetectorObjects); setCompositeDetectorObjects(compositeDetectorObjects); setPropertyDetectorObjects(propertyDetectorObjects); } public abstract Object apply(String applyName, Object... args); public abstract Object detector(String detectorName, Object... args); public String getName() { return name; } public void setName(String name) { this.name = name; } public HashMap<String, AbstractObject> getAggregateDetectorObjects() { return aggregateDetectorObjects; } public void setAggregateDetectorObjects(HashMap<String, AbstractObject> aggregateDetectorObjects) { this.aggregateDetectorObjects = aggregateDetectorObjects; } public HashMap<String, AbstractObject> getCompositeDetectorObjects() { return compositeDetectorObjects; } public void setCompositeDetectorObjects(HashMap<String, AbstractObject> compositeDetectorObjects) { this.compositeDetectorObjects = compositeDetectorObjects; } public HashMap<String, Property> getPropertyDetectorObjects() { return propertyDetectorObjects; } public void setPropertyDetectorObjects(HashMap<String, Property> propertyDetectorObjects) { this.propertyDetectorObjects = propertyDetectorObjects; } }
2,571
33.756757
203
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/owrl/Category.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors to this module: * S. M. de Paula and R. R. Gudwin ******************************************************************************/ package br.unicamp.cst.representation.owrl; import java.util.ArrayList; import java.util.List; /** * Created by du on 26/12/16. */ public class Category { private String name; private List<AbstractObject> listOfWorldObjects; public Category(String name){ this.setName(name); this.setListOfWorldObjects(new ArrayList<AbstractObject>()); } public Category(String name, List<AbstractObject> listOfWorldObjects){ this.setName(name); this.setListOfWorldObjects(listOfWorldObjects); } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<AbstractObject> getListOfWorldObjects() { return listOfWorldObjects; } public void setListOfWorldObjects(List<AbstractObject> listOfWorldObjects) { this.listOfWorldObjects = listOfWorldObjects; } }
1,438
27.215686
80
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/owrl/CodeBuilder.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.representation.owrl; import net.openhft.compiler.CompilerUtils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by du on 11/05/17. */ public class CodeBuilder { private final String ENTER = "\n"; private final String SPACE = " "; private String fullClassName; private String className; private String packagePath = "package br.unicamp.cst.util"; private String code = getPackagePath() + ";" + ENTER + "@IMPORTS" + ENTER + "public class @CLASS @INHERITANCE @INHERITANCE_ENTITY {" + ENTER + "@ATTRIBUTES" + ENTER + "@METHODS" + ENTER + "}"; private List<String> imports; private List<String> methods; private List<String> attributes; public CodeBuilder(String className) { this.setClassName(className); this.setFullClassName("br.unicamp.cst.util." + className); this.setCode(this.getCode().replace("@CLASS", className)); this.setCode(this.getCode().replace("@INHERITANCE_ENTITY", "")); this.setCode(this.getCode().replace("@INHERITANCE", "")); this.setMethods(new ArrayList<String>()); this.setAttributes(new ArrayList<String>()); this.setImports(new ArrayList<String>()); } public CodeBuilder(String className, String inheritance, String inheriranceEntity) { this.setClassName(className); this.setFullClassName(getPackagePath() + "." + className); this.setCode(this.getCode().replace("@CLASS", className)); if(inheritance != null) this.setCode(this.getCode().replace("@INHERITANCE", inheritance)); else this.setCode(this.getCode().replace("@INHERITANCE", "")); if(inheriranceEntity != null) this.setCode(this.getCode().replace("@INHERITANCE_ENTITY", inheriranceEntity)); else this.setCode(this.getCode().replace("@INHERITANCE_ENTITY", "")); this.setMethods(new ArrayList<String>()); this.setAttributes(new ArrayList<String>()); this.setImports(new ArrayList<String>()); } public void addImports(String importStatement){ getImports().add("import" + SPACE + importStatement + ";"); } public void addAttributes(String acessibility, String attributeType, String attributeName){ String attribute = acessibility + SPACE + attributeType + SPACE + attributeName + ";"; getAttributes().add(attribute); } public void addAttributes(String acessibility, String attributeType, String attributeName, String value){ String attribute = acessibility + SPACE + attributeType + SPACE + attributeName + SPACE + "=" + SPACE + value + ";"; getAttributes().add(attribute); } public void addMethod(String acessibility, String returnType, String methodName, List<String> parameterList, String methodCode, boolean isOverride) { String method = acessibility + SPACE + returnType + SPACE + methodName + "(@PARAMETERS){" + ENTER + "@CODE" + ENTER + "}"; method = isOverride ? "@Override" + ENTER + method : method; final String parameters = String.join(", ", parameterList); String finalMethodCode = ""; finalMethodCode = method.replace("@PARAMETERS", parameters); finalMethodCode = finalMethodCode.replace("@CODE", methodCode); this.getMethods().add(finalMethodCode); } public String buildClassCode() { String imports = String.join(ENTER, this.getImports()); String methods = String.join(ENTER, this.getMethods()); String attributes = String.join(ENTER, this.getAttributes()); String finalCode = this.getCode(); if(!getImports().isEmpty()) finalCode = finalCode.replace("@IMPORTS", imports); else finalCode = finalCode.replace("@IMPORTS", ""); finalCode = finalCode.replace("@METHODS", methods); finalCode = finalCode.replace("@ATTRIBUTES", attributes); return finalCode; } public static Object executeMethod(Object object, String methodName, Object... args) { Method method = Arrays.stream(object.getClass().getMethods()).filter(m -> m.getName().contains(methodName)).findFirst().get(); Object returnObject = null; try { returnObject = method.invoke(object, args); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return returnObject; } public static Class compile(String className, String code) { Class aClass = null; try { aClass = CompilerUtils.CACHED_COMPILER.loadFromJava(className, code); } catch (Exception e) { e.printStackTrace(); } return aClass; } public static Object generateNewInstance(Class aClass){ Object object = null; try { object = aClass.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return object; } public String getFullClassName() { return fullClassName; } public void setFullClassName(String fullClassName) { this.fullClassName = fullClassName; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getPackagePath() { return packagePath; } public void setPackagePath(String packagePath) { this.packagePath = packagePath; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public List<String> getMethods() { return methods; } public void setMethods(List<String> methods) { this.methods = methods; } public List<String> getAttributes() { return attributes; } public void setAttributes(List<String> attributes) { this.attributes = attributes; } public List<String> getImports() { return imports; } public void setImports(List<String> imports) { this.imports = imports; } }
7,044
30.035242
153
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/owrl/Configuration.java
/** ***************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors to this module: * S. M. de Paula and R. R. Gudwin ***************************************************************************** */ package br.unicamp.cst.representation.owrl; import br.unicamp.cst.motivational.Appraisal; import java.util.ArrayList; import java.util.List; /** * @author Suelen Mapa */ public class Configuration { private List<AbstractObject> objects; //String name; private Appraisal appraisal; public Configuration(List<AbstractObject> objs, Appraisal appraisal) { objects = objs; this.appraisal = appraisal; } public Configuration(List<AbstractObject> objs) { objects = objs; } public Configuration() { objects = new ArrayList<>(); } public List<AbstractObject> getObjects() { return objects; } public void addObject(AbstractObject obj) { objects.add(obj); } public boolean removeObject(int id) { /*for (int i = 0; i < objects.size(); ++i) { if (objects.get(i).getID() == id) { objects.remove(i); return true; } }*/ return false; } /* public boolean changeObject(int id, AbstractObject modifications) { for (int i = 0; i < objects.size(); ++i) { if (objects.get(i).getID() == id) { objects.get(i).modify(modifications); return true; } } return false; }*/ public Appraisal getAppraisal() { return appraisal; } public void setAppraisal(Appraisal appraisal) { this.appraisal = appraisal; } // TODO: Implement clone() inside Appraisal and call it here // public Configuration clone() { // List<AbstractObject> newObjects = new ArrayList<AbstractObject>(); // for (AbstractObject object : objects) { // newObjects.add(object.clone()); // } // return new Configuration(newObjects); // } }
2,364
26.823529
81
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/owrl/DynamicAffordance.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.representation.owrl; import br.unicamp.cst.core.entities.CSTMessages; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; /** * @author Suelen Mapa and Eduardo Froes. */ public class DynamicAffordance extends Affordance { private String applyCode; private String applyClassName; private String detectorCode; private String detectorClassName; private Object applyObject; private Object detectorObject; public DynamicAffordance(String name) { super(name, new HashMap<>(), new HashMap<>(), new HashMap<>()); } public DynamicAffordance(String name, HashMap<String, AbstractObject> aggregateObjects, HashMap<String, AbstractObject> compositeObjects, HashMap<String, Property> modifiedProperties) { super(name, aggregateObjects, compositeObjects, modifiedProperties); } public DynamicAffordance(String name, String applyClassName, String applyCode, String detectorClassName, String detectorCode, HashMap<String, AbstractObject> aggregateObjects, HashMap<String, AbstractObject> compositeObjects, HashMap<String, Property> modifiedProperties) { super(name, aggregateObjects, compositeObjects, modifiedProperties); setApplyCode(applyCode); setApplyClassName(applyClassName); setDetectorCode(detectorCode); setDetectorClassName(detectorClassName); setDetectorObject(CodeBuilder.generateNewInstance(CodeBuilder.compile(getDetectorClassName(), getDetectorCode()))); setApplyObject(CodeBuilder.generateNewInstance(CodeBuilder.compile(getApplyClassName(), getApplyCode()))); } public Object detector(String methodName, Object... args) { try { if (getDetectorObject() == null) { throw new Exception(CSTMessages.MSG_VAR_DETECTOR_OBJECT); } else { return CodeBuilder.executeMethod(getDetectorObject(), methodName, args); } } catch (Exception e) { e.printStackTrace(); } return null; } public Object apply(String methodName, Object... args) { try { if (getDetectorObject() == null) { throw new Exception(CSTMessages.MSG_VAR_APPLY_OBJECT); } else { return CodeBuilder.executeMethod(getApplyObject(), methodName, args); } } catch (Exception e){ e.printStackTrace(); } return null; } protected String getApplyCode() { return applyCode; } protected void setApplyCode(String applyCode) { this.applyCode = applyCode; } public String getApplyClassName() { return applyClassName; } public void setApplyClassName(String applyClassName) { this.applyClassName = applyClassName; } protected String getDetectorCode() { return detectorCode; } protected void setDetectorCode(String detectorCode) { this.detectorCode = detectorCode; } public String getDetectorClassName() { return detectorClassName; } public void setDetectorClassName(String detectorClassName) { this.detectorClassName = detectorClassName; } protected Object getApplyObject() { return applyObject; } protected void setApplyObject(Object applyObject) { this.applyObject = applyObject; } protected Object getDetectorObject() { return detectorObject; } protected void setDetectorObject(Object detectorObject) { this.detectorObject = detectorObject; } public static void main(String[] args) { String detectorClassName = "br.com.reflection.test.Detector"; String detectorCode = "package br.com.reflection.test;\n" + "public class Detector {" + "\n" + " public boolean compare(Integer i0, Integer i1) {" + "\n" + " if(i0 == i1)" + "\n" + " return true;"+ "\n" + " else"+ "\n" + " return false;"+ "\n" + " }" + "\n" + "}" + "\n"; String applyClassName = "br.com.reflection.test.Apply"; String applyCode = "package br.com.reflection.test;\n" + "import java.util.List;" + "\n" + "public class Apply {" + "\n" + " public void execute(List<Integer> list) {" + "\n" + " list.stream().forEach( i -> System.out.println(i));" + "\n" + " }" + "\n" + "}" + "\n"; Date dateTimeInit = new Date(); DynamicAffordance affordance = new DynamicAffordance("Test", applyClassName, applyCode, detectorClassName, detectorCode, new HashMap<>(), new HashMap<>(), new HashMap<>()); Date dateTimeFinish = new Date(); System.out.println("Compile Time:" + (dateTimeFinish.getTime() - dateTimeInit.getTime())); List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10); affordance.apply("execute", list); System.out.println(affordance.detector("compare", 1,1)); } }
5,749
33.023669
278
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/owrl/Entity.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.representation.owrl; /** * * @author rgudwin */ public interface Entity { }
653
31.7
82
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/owrl/Pair.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.representation.owrl; /** * @author Suelen Mapa and Eduardo Froes. */ public class Pair<F, S> { private F first; private S second; public Pair(F first, S second) { this.setFirst(first); this.setSecond(second); } public F getFirst() { return first; } public void setFirst(F first) { this.first = first; } public S getSecond() { return second; } public void setSecond(S second) { this.second = second; } }
1,080
24.738095
82
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/owrl/Property.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors to this module: * S. M. de Paula and R. R. Gudwin ******************************************************************************/ package br.unicamp.cst.representation.owrl; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * * @author suelenmapa */ public final class Property implements Entity { private List<QualityDimension> qualityDimensions;//1-n private String name; public Property(String name) { setName(name); qualityDimensions = new ArrayList<>(); } public Property(String name, QualityDimension qd) { this(name); addQualityDimension(qd); } public Property(String name, Object value) { this(name); QualityDimension qd = new QualityDimension("value",value); addQualityDimension(qd); } public Property(String name, List<QualityDimension> qd) { setName(name); qualityDimensions = qd; } Property() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public List<QualityDimension> getQualityDimensions() { return qualityDimensions; } public void addQualityDimension(QualityDimension qd) { qualityDimensions.add(qd); } public void addQualityDimension(String key, Object value) { QualityDimension qd = new QualityDimension(key,value); addQualityDimension(qd); } public String getName() { return name; } public void setName(String Name) { this.name = Name; } @Override public boolean equals(Object property){ final boolean[] isEquals = {true}; if (!(property instanceof Property)) { return false; } Property that = (Property) property; if(!that.getName().equals(this.getName())){ return false; } this.getQualityDimensions().forEach(dimension -> { Optional<QualityDimension> first = that.getQualityDimensions().stream().filter(tDimension -> tDimension.getName().equals(dimension.getName())).findFirst(); if(!first.isPresent()){ isEquals[0] = false; return; } else{ if(!dimension.getValue().equals(first.get().getValue())){ isEquals[0]=false; return; } } }); return isEquals[0]; } @Override public Property clone() { List<QualityDimension> newQualityDimension = new ArrayList<>(); for (QualityDimension qd : qualityDimensions) { newQualityDimension.add(qd.clone()); } return new Property(getName(), newQualityDimension); } public void deleteChild(Object child) { String childclass = child.getClass().getCanonicalName(); //System.out.println("Childclass: "+childclass); if (childclass.equals("br.unicamp.cst.representation.owrl.QualityDimension")) { boolean qdres = qualityDimensions.remove(child); //System.out.println("qdres: "+qdres); } } public List<Object> search(String name) { List<Object> results = new ArrayList<>(); for (QualityDimension qd : qualityDimensions) { if (qd.getName().equals(name)) { results.add(qd); } } return results; } public String toStringFull(int level) { String out=""; out += name+"\n"; for (QualityDimension qd : qualityDimensions) { for (int i=0;i<level;i++) out += " "; out += "- "+qd.toStringFull(level+1); } return out; } public String getResumedQDs(int limit) { String result = ""; if (qualityDimensions.size() > 1) result = "("; int n = 0; for (QualityDimension qd : qualityDimensions) { result += qd.getResumedValue(); if (n++ < qualityDimensions.size()) result += " "; } if (qualityDimensions.size() > 1) result += ")"; if (result.length() > limit) result = result.substring(0, limit)+"..."; return(result); } }
4,688
27.944444
167
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/owrl/QualityDimension.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors to this module: * S. M. de Paula and R. R. Gudwin ******************************************************************************/ package br.unicamp.cst.representation.owrl; import java.util.HashMap; /** * * @author suelenmapa */ public class QualityDimension implements Entity { private String name; private Object value; public QualityDimension(String name, Object value) { this.name = name; this.value = value; } public QualityDimension(String name) { this.name = name; this.value = ""; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public boolean isDouble() { String objectClassName = value.getClass().getName(); if (objectClassName.equals("java.lang.Double")) return(true); return(false); } public boolean isFloat() { String objectClassName = value.getClass().getName(); if (objectClassName.equals("java.lang.Double")) return(true); return(false); } public boolean isInteger() { String objectClassName = value.getClass().getName(); if (objectClassName.equals("java.lang.Long")) return(true); return(false); } public boolean isLong() { String objectClassName = value.getClass().getName(); if (objectClassName.equals("java.lang.Long")) return(true); return(false); } public boolean isNumber() { String objectClassName = value.getClass().getName(); if (objectClassName.equals("java.lang.Float") || objectClassName.equals("java.lang.Double") || objectClassName.equals("java.lang.Integer") || objectClassName.equals("java.lang.Long")) return(true); return(false); } public boolean isHashMap(){ String objectClassName = value.getClass().getName(); if (objectClassName.equals("java.util.HashMap")) return(true); return(false); } public boolean isString() { String objectClassName = value.getClass().getName(); if (objectClassName.equals("java.lang.String")) return(true); return(false); } public boolean isBoolean() { String objectClassName = value.getClass().getName(); if (objectClassName.equals("java.lang.Boolean")) return(true); return(false); } protected QualityDimension clone() { return new QualityDimension(getName(), getValue()); } public String toStringFull(int level) { String out=""; out += name+" : "+value+"\n"; return out; } public String getResumedValue() { String result; if (isFloat() || isDouble()) { result = String.format("%4.1f",getValue()); } else { try { int trial = Integer.parseInt(getValue().toString()); result = String.format("%d",trial); } catch(Exception ee) { try { double trial = Double.parseDouble(getValue().toString()); result = String.format("%4.1f",trial); } catch(Exception e) { result = getValue().toString(); } } } return(result); } }
3,982
27.45
191
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/owrl/grammar/CustomizedListener.java
/** ***************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors to this module: * S. M. de Paula and R. R. Gudwin ***************************************************************************** */ package br.unicamp.cst.representation.owrl.grammar; import br.unicamp.cst.representation.owrl.Property; import br.unicamp.cst.representation.owrl.QualityDimension; import br.unicamp.cst.representation.owrl.AbstractObject; import br.unicamp.cst.representation.owrl.Pair; import java.util.ArrayList; import java.util.List; /** * * @author suelenmapa */ public class CustomizedListener extends OwrlBaseListener { private List<Pair<String, List<AbstractObject>>> memory = new ArrayList<Pair<String, List<AbstractObject>>>(); private int contKey = 0; @Override public void enterStat(OwrlParser.StatContext ctx) { String command = ctx.command().getText(); List<AbstractObject> listWO = new ArrayList<>(); for (int i = 0; i < ctx.expr().size(); i++) { listWO.add(readElementsFromExpr(ctx.expr(i))); } memory.add(new Pair(command, listWO)); } public AbstractObject readElementsFromExpr(OwrlParser.ExprContext ctx) { String name = ctx.name().object().ID().getText(); int id = Integer.parseInt(ctx.name().cod().INT_VALUE().getText()); AbstractObject wo; if (!ctx.atrib().isEmpty()) { wo = new AbstractObject(name, readProperty(ctx.atrib(0).property()), readPart(ctx.atrib(0).part())); } else { wo = new AbstractObject(name); } return wo; } public List<AbstractObject> readPart(List<OwrlParser.PartContext> ctxPart) { List<AbstractObject> parts = new ArrayList<AbstractObject>(); AbstractObject onePart; if (ctxPart != null) { for (int i = 0; i < ctxPart.size(); i++) { String namePart = ctxPart.get(i).name().object().ID().getText(); int id = Integer.parseInt(ctxPart.get(i).name().cod().INT_VALUE().getText()); List<Property> listPropertiesPart = readProperty(ctxPart.get(i).property()); List<AbstractObject> subparts = readPart(ctxPart.get(i).part()); onePart = new AbstractObject(namePart, listPropertiesPart, subparts); parts.add(onePart); } } return parts; } public List<Property> readProperty(List<OwrlParser.PropertyContext> ctxProperty) { List<Property> listProperties = new ArrayList<Property>(); if (ctxProperty != null) { for (int i = 0; i < ctxProperty.size(); i++) { String nameProperty = ctxProperty.get(i).ID().getText(); Property property = new Property(nameProperty); for (int s = 0; s < ctxProperty.get(i).qualitydimension().size(); s++) { String st = ctxProperty.get(i).qualitydimension(s).value().getText(); String newvalue = st.substring(1, (st.length() - 1)); String qd = ctxProperty.get(i).qualitydimension(s).ID().getText(); property.addQualityDimension(new QualityDimension(qd, newvalue)); } listProperties.add(property); } } return listProperties; } public List<Pair<String, List<AbstractObject>>> getMemory() { return memory; } }
3,788
28.146154
114
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/owrl/grammar/OwrlBaseListener.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.representation.owrl.grammar; // Generated from Owrl.g4 by ANTLR 4.5.3 // Generated from Owrl.g4 by ANTLR 4.5.3 import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.TerminalNode; /** * This class provides an empty implementation of {@link OwrlListener}, * which can be extended to create a listener which only needs to handle a subset * of the available methods. */ public class OwrlBaseListener implements OwrlListener { /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterConf(OwrlParser.ConfContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitConf(OwrlParser.ConfContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterStat(OwrlParser.StatContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitStat(OwrlParser.StatContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterExpr(OwrlParser.ExprContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitExpr(OwrlParser.ExprContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterAtrib(OwrlParser.AtribContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitAtrib(OwrlParser.AtribContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterPart(OwrlParser.PartContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitPart(OwrlParser.PartContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterName(OwrlParser.NameContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitName(OwrlParser.NameContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterObject(OwrlParser.ObjectContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitObject(OwrlParser.ObjectContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterProperty(OwrlParser.PropertyContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitProperty(OwrlParser.PropertyContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterQualitydimension(OwrlParser.QualitydimensionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitQualitydimension(OwrlParser.QualitydimensionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterCommand(OwrlParser.CommandContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitCommand(OwrlParser.CommandContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterValue(OwrlParser.ValueContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitValue(OwrlParser.ValueContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterCod(OwrlParser.CodContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitCod(OwrlParser.CodContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitTerminal(TerminalNode node) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitErrorNode(ErrorNode node) { } }
5,309
26.091837
88
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/owrl/grammar/OwrlLexer.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.representation.owrl.grammar; // Generated from Owrl.g4 by ANTLR 4.5.3 // Generated from Owrl.g4 by ANTLR 4.5.3 import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.misc.*; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class OwrlLexer extends Lexer { static { RuntimeMetaData.checkVersion("4.5.3", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int T__0=1, T__1=2, T__2=3, T__3=4, T__4=5, T__5=6, T__6=7, T__7=8, ID=9, INT_VALUE=10, REAL_VALUE=11, NEWLINE=12, WS=13; public static String[] modeNames = { "DEFAULT_MODE" }; public static final String[] ruleNames = { "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", "T__7", "ID", "INT_VALUE", "REAL_VALUE", "NEWLINE", "WS" }; private static final String[] _LITERAL_NAMES = { null, "'['", "']'", "'<'", "'>'", "'create'", "'modify'", "'destroy'", "'\"'" }; private static final String[] _SYMBOLIC_NAMES = { null, null, null, null, null, null, null, null, null, "ID", "INT_VALUE", "REAL_VALUE", "NEWLINE", "WS" }; public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } public OwrlLexer(CharStream input) { super(input); _interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } @Override public String getGrammarFileName() { return "Owrl.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public String[] getModeNames() { return modeNames; } @Override public ATN getATN() { return _ATN; } public static final String _serializedATN = "\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\2\17`\b\1\4\2\t\2\4"+ "\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t"+ "\13\4\f\t\f\4\r\t\r\4\16\t\16\3\2\3\2\3\3\3\3\3\4\3\4\3\5\3\5\3\6\3\6"+ "\3\6\3\6\3\6\3\6\3\6\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\b\3\b\3\b\3\b\3\b\3"+ "\b\3\b\3\b\3\t\3\t\3\n\3\n\7\n@\n\n\f\n\16\nC\13\n\3\13\6\13F\n\13\r\13"+ "\16\13G\3\f\6\fK\n\f\r\f\16\fL\3\f\3\f\6\fQ\n\f\r\f\16\fR\3\r\5\rV\n\r"+ "\3\r\3\r\3\16\6\16[\n\16\r\16\16\16\\\3\16\3\16\2\2\17\3\3\5\4\7\5\t\6"+ "\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16\33\17\3\2\6\4\2C\\c|\5\2\62"+ ";C\\c|\3\2\62;\3\2\13\13e\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2"+ "\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2"+ "\25\3\2\2\2\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\3\35\3\2\2\2\5\37\3"+ "\2\2\2\7!\3\2\2\2\t#\3\2\2\2\13%\3\2\2\2\r,\3\2\2\2\17\63\3\2\2\2\21;"+ "\3\2\2\2\23=\3\2\2\2\25E\3\2\2\2\27J\3\2\2\2\31U\3\2\2\2\33Z\3\2\2\2\35"+ "\36\7]\2\2\36\4\3\2\2\2\37 \7_\2\2 \6\3\2\2\2!\"\7>\2\2\"\b\3\2\2\2#$"+ "\7@\2\2$\n\3\2\2\2%&\7e\2\2&\'\7t\2\2\'(\7g\2\2()\7c\2\2)*\7v\2\2*+\7"+ "g\2\2+\f\3\2\2\2,-\7o\2\2-.\7q\2\2./\7f\2\2/\60\7k\2\2\60\61\7h\2\2\61"+ "\62\7{\2\2\62\16\3\2\2\2\63\64\7f\2\2\64\65\7g\2\2\65\66\7u\2\2\66\67"+ "\7v\2\2\678\7t\2\289\7q\2\29:\7{\2\2:\20\3\2\2\2;<\7$\2\2<\22\3\2\2\2"+ "=A\t\2\2\2>@\t\3\2\2?>\3\2\2\2@C\3\2\2\2A?\3\2\2\2AB\3\2\2\2B\24\3\2\2"+ "\2CA\3\2\2\2DF\t\4\2\2ED\3\2\2\2FG\3\2\2\2GE\3\2\2\2GH\3\2\2\2H\26\3\2"+ "\2\2IK\t\4\2\2JI\3\2\2\2KL\3\2\2\2LJ\3\2\2\2LM\3\2\2\2MN\3\2\2\2NP\13"+ "\2\2\2OQ\t\4\2\2PO\3\2\2\2QR\3\2\2\2RP\3\2\2\2RS\3\2\2\2S\30\3\2\2\2T"+ "V\7\17\2\2UT\3\2\2\2UV\3\2\2\2VW\3\2\2\2WX\7\f\2\2X\32\3\2\2\2Y[\t\5\2"+ "\2ZY\3\2\2\2[\\\3\2\2\2\\Z\3\2\2\2\\]\3\2\2\2]^\3\2\2\2^_\b\16\2\2_\34"+ "\3\2\2\2\t\2AGLRU\\\3\b\2\2"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
5,330
37.352518
97
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/owrl/grammar/OwrlListener.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.representation.owrl.grammar; // Generated from Owrl.g4 by ANTLR 4.5.3 // Generated from Owrl.g4 by ANTLR 4.5.3 import org.antlr.v4.runtime.tree.ParseTreeListener; /** * This interface defines a complete listener for a parse tree produced by * {@link OwrlParser}. */ public interface OwrlListener extends ParseTreeListener { /** * Enter a parse tree produced by {@link OwrlParser#conf}. * @param ctx the parse tree */ void enterConf(OwrlParser.ConfContext ctx); /** * Exit a parse tree produced by {@link OwrlParser#conf}. * @param ctx the parse tree */ void exitConf(OwrlParser.ConfContext ctx); /** * Enter a parse tree produced by {@link OwrlParser#stat}. * @param ctx the parse tree */ void enterStat(OwrlParser.StatContext ctx); /** * Exit a parse tree produced by {@link OwrlParser#stat}. * @param ctx the parse tree */ void exitStat(OwrlParser.StatContext ctx); /** * Enter a parse tree produced by {@link OwrlParser#expr}. * @param ctx the parse tree */ void enterExpr(OwrlParser.ExprContext ctx); /** * Exit a parse tree produced by {@link OwrlParser#expr}. * @param ctx the parse tree */ void exitExpr(OwrlParser.ExprContext ctx); /** * Enter a parse tree produced by {@link OwrlParser#atrib}. * @param ctx the parse tree */ void enterAtrib(OwrlParser.AtribContext ctx); /** * Exit a parse tree produced by {@link OwrlParser#atrib}. * @param ctx the parse tree */ void exitAtrib(OwrlParser.AtribContext ctx); /** * Enter a parse tree produced by {@link OwrlParser#part}. * @param ctx the parse tree */ void enterPart(OwrlParser.PartContext ctx); /** * Exit a parse tree produced by {@link OwrlParser#part}. * @param ctx the parse tree */ void exitPart(OwrlParser.PartContext ctx); /** * Enter a parse tree produced by {@link OwrlParser#name}. * @param ctx the parse tree */ void enterName(OwrlParser.NameContext ctx); /** * Exit a parse tree produced by {@link OwrlParser#name}. * @param ctx the parse tree */ void exitName(OwrlParser.NameContext ctx); /** * Enter a parse tree produced by {@link OwrlParser#object}. * @param ctx the parse tree */ void enterObject(OwrlParser.ObjectContext ctx); /** * Exit a parse tree produced by {@link OwrlParser#object}. * @param ctx the parse tree */ void exitObject(OwrlParser.ObjectContext ctx); /** * Enter a parse tree produced by {@link OwrlParser#property}. * @param ctx the parse tree */ void enterProperty(OwrlParser.PropertyContext ctx); /** * Exit a parse tree produced by {@link OwrlParser#property}. * @param ctx the parse tree */ void exitProperty(OwrlParser.PropertyContext ctx); /** * Enter a parse tree produced by {@link OwrlParser#qualitydimension}. * @param ctx the parse tree */ void enterQualitydimension(OwrlParser.QualitydimensionContext ctx); /** * Exit a parse tree produced by {@link OwrlParser#qualitydimension}. * @param ctx the parse tree */ void exitQualitydimension(OwrlParser.QualitydimensionContext ctx); /** * Enter a parse tree produced by {@link OwrlParser#command}. * @param ctx the parse tree */ void enterCommand(OwrlParser.CommandContext ctx); /** * Exit a parse tree produced by {@link OwrlParser#command}. * @param ctx the parse tree */ void exitCommand(OwrlParser.CommandContext ctx); /** * Enter a parse tree produced by {@link OwrlParser#value}. * @param ctx the parse tree */ void enterValue(OwrlParser.ValueContext ctx); /** * Exit a parse tree produced by {@link OwrlParser#value}. * @param ctx the parse tree */ void exitValue(OwrlParser.ValueContext ctx); /** * Enter a parse tree produced by {@link OwrlParser#cod}. * @param ctx the parse tree */ void enterCod(OwrlParser.CodContext ctx); /** * Exit a parse tree produced by {@link OwrlParser#cod}. * @param ctx the parse tree */ void exitCod(OwrlParser.CodContext ctx); }
4,490
30.626761
82
java
cst
cst-master/src/main/java/br/unicamp/cst/representation/owrl/grammar/OwrlParser.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.representation.owrl.grammar; // Generated from Owrl.g4 by ANTLR 4.5.3 import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.*; import org.antlr.v4.runtime.tree.*; import java.util.List; import java.util.Iterator; import java.util.ArrayList; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class OwrlParser extends Parser { static { RuntimeMetaData.checkVersion("4.5.3", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int T__0=1, T__1=2, T__2=3, T__3=4, T__4=5, T__5=6, T__6=7, T__7=8, ID=9, INT_VALUE=10, REAL_VALUE=11, NEWLINE=12, WS=13; public static final int RULE_conf = 0, RULE_stat = 1, RULE_expr = 2, RULE_atrib = 3, RULE_part = 4, RULE_name = 5, RULE_object = 6, RULE_property = 7, RULE_qualitydimension = 8, RULE_command = 9, RULE_value = 10, RULE_cod = 11; public static final String[] ruleNames = { "conf", "stat", "expr", "atrib", "part", "name", "object", "property", "qualitydimension", "command", "value", "cod" }; private static final String[] _LITERAL_NAMES = { null, "'['", "']'", "'<'", "'>'", "'create'", "'modify'", "'destroy'", "'\"'" }; private static final String[] _SYMBOLIC_NAMES = { null, null, null, null, null, null, null, null, null, "ID", "INT_VALUE", "REAL_VALUE", "NEWLINE", "WS" }; public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } @Override public String getGrammarFileName() { return "Owrl.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public ATN getATN() { return _ATN; } public OwrlParser(TokenStream input) { super(input); _interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } public static class ConfContext extends ParserRuleContext { public TerminalNode NEWLINE() { return getToken(OwrlParser.NEWLINE, 0); } public List<StatContext> stat() { return getRuleContexts(StatContext.class); } public StatContext stat(int i) { return getRuleContext(StatContext.class,i); } public ConfContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_conf; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).enterConf(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).exitConf(this); } } public final ConfContext conf() throws RecognitionException { ConfContext _localctx = new ConfContext(_ctx, getState()); enterRule(_localctx, 0, RULE_conf); int _la; try { setState(34); switch (_input.LA(1)) { case T__0: enterOuterAlt(_localctx, 1); { setState(24); match(T__0); setState(26); _errHandler.sync(this); _la = _input.LA(1); do { { { setState(25); stat(); } } setState(28); _errHandler.sync(this); _la = _input.LA(1); } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__4) | (1L << T__5) | (1L << T__6))) != 0) ); setState(30); match(T__1); setState(31); match(NEWLINE); } break; case NEWLINE: enterOuterAlt(_localctx, 2); { setState(33); match(NEWLINE); } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class StatContext extends ParserRuleContext { public CommandContext command() { return getRuleContext(CommandContext.class,0); } public List<ExprContext> expr() { return getRuleContexts(ExprContext.class); } public ExprContext expr(int i) { return getRuleContext(ExprContext.class,i); } public StatContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_stat; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).enterStat(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).exitStat(this); } } public final StatContext stat() throws RecognitionException { StatContext _localctx = new StatContext(_ctx, getState()); enterRule(_localctx, 2, RULE_stat); int _la; try { enterOuterAlt(_localctx, 1); { setState(36); command(); setState(37); match(T__0); setState(39); _errHandler.sync(this); _la = _input.LA(1); do { { { setState(38); expr(); } } setState(41); _errHandler.sync(this); _la = _input.LA(1); } while ( _la==T__0 ); setState(43); match(T__1); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ExprContext extends ParserRuleContext { public NameContext name() { return getRuleContext(NameContext.class,0); } public List<AtribContext> atrib() { return getRuleContexts(AtribContext.class); } public AtribContext atrib(int i) { return getRuleContext(AtribContext.class,i); } public ExprContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_expr; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).enterExpr(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).exitExpr(this); } } public final ExprContext expr() throws RecognitionException { ExprContext _localctx = new ExprContext(_ctx, getState()); enterRule(_localctx, 4, RULE_expr); int _la; try { enterOuterAlt(_localctx, 1); { setState(45); match(T__0); setState(46); name(); setState(50); _errHandler.sync(this); _la = _input.LA(1); while (_la==T__0) { { { setState(47); atrib(); } } setState(52); _errHandler.sync(this); _la = _input.LA(1); } setState(53); match(T__1); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class AtribContext extends ParserRuleContext { public List<PartContext> part() { return getRuleContexts(PartContext.class); } public PartContext part(int i) { return getRuleContext(PartContext.class,i); } public List<PropertyContext> property() { return getRuleContexts(PropertyContext.class); } public PropertyContext property(int i) { return getRuleContext(PropertyContext.class,i); } public AtribContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_atrib; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).enterAtrib(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).exitAtrib(this); } } public final AtribContext atrib() throws RecognitionException { AtribContext _localctx = new AtribContext(_ctx, getState()); enterRule(_localctx, 6, RULE_atrib); int _la; try { enterOuterAlt(_localctx, 1); { setState(55); match(T__0); setState(59); _errHandler.sync(this); _la = _input.LA(1); while (_la==T__0) { { { setState(56); part(); } } setState(61); _errHandler.sync(this); _la = _input.LA(1); } setState(65); _errHandler.sync(this); _la = _input.LA(1); while (_la==T__2) { { { setState(62); property(); } } setState(67); _errHandler.sync(this); _la = _input.LA(1); } setState(68); match(T__1); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class PartContext extends ParserRuleContext { public NameContext name() { return getRuleContext(NameContext.class,0); } public List<PartContext> part() { return getRuleContexts(PartContext.class); } public PartContext part(int i) { return getRuleContext(PartContext.class,i); } public List<PropertyContext> property() { return getRuleContexts(PropertyContext.class); } public PropertyContext property(int i) { return getRuleContext(PropertyContext.class,i); } public PartContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_part; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).enterPart(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).exitPart(this); } } public final PartContext part() throws RecognitionException { PartContext _localctx = new PartContext(_ctx, getState()); enterRule(_localctx, 8, RULE_part); int _la; try { enterOuterAlt(_localctx, 1); { setState(70); match(T__0); setState(71); name(); setState(75); _errHandler.sync(this); _la = _input.LA(1); while (_la==T__0) { { { setState(72); part(); } } setState(77); _errHandler.sync(this); _la = _input.LA(1); } setState(81); _errHandler.sync(this); _la = _input.LA(1); while (_la==T__2) { { { setState(78); property(); } } setState(83); _errHandler.sync(this); _la = _input.LA(1); } setState(84); match(T__1); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class NameContext extends ParserRuleContext { public ObjectContext object() { return getRuleContext(ObjectContext.class,0); } public CodContext cod() { return getRuleContext(CodContext.class,0); } public NameContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_name; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).enterName(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).exitName(this); } } public final NameContext name() throws RecognitionException { NameContext _localctx = new NameContext(_ctx, getState()); enterRule(_localctx, 10, RULE_name); try { enterOuterAlt(_localctx, 1); { setState(86); match(T__0); setState(87); object(); setState(88); cod(); setState(89); match(T__1); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ObjectContext extends ParserRuleContext { public TerminalNode ID() { return getToken(OwrlParser.ID, 0); } public ObjectContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_object; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).enterObject(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).exitObject(this); } } public final ObjectContext object() throws RecognitionException { ObjectContext _localctx = new ObjectContext(_ctx, getState()); enterRule(_localctx, 12, RULE_object); try { enterOuterAlt(_localctx, 1); { setState(91); match(T__2); setState(92); match(ID); setState(93); match(T__3); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class PropertyContext extends ParserRuleContext { public TerminalNode ID() { return getToken(OwrlParser.ID, 0); } public List<QualitydimensionContext> qualitydimension() { return getRuleContexts(QualitydimensionContext.class); } public QualitydimensionContext qualitydimension(int i) { return getRuleContext(QualitydimensionContext.class,i); } public PropertyContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_property; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).enterProperty(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).exitProperty(this); } } public final PropertyContext property() throws RecognitionException { PropertyContext _localctx = new PropertyContext(_ctx, getState()); enterRule(_localctx, 14, RULE_property); try { int _alt; enterOuterAlt(_localctx, 1); { setState(95); match(T__2); setState(96); match(ID); setState(97); match(T__3); setState(99); _errHandler.sync(this); _alt = 1; do { switch (_alt) { case 1: { { setState(98); qualitydimension(); } } break; default: throw new NoViableAltException(this); } setState(101); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,8,_ctx); } while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class QualitydimensionContext extends ParserRuleContext { public TerminalNode ID() { return getToken(OwrlParser.ID, 0); } public ValueContext value() { return getRuleContext(ValueContext.class,0); } public QualitydimensionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_qualitydimension; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).enterQualitydimension(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).exitQualitydimension(this); } } public final QualitydimensionContext qualitydimension() throws RecognitionException { QualitydimensionContext _localctx = new QualitydimensionContext(_ctx, getState()); enterRule(_localctx, 16, RULE_qualitydimension); try { enterOuterAlt(_localctx, 1); { setState(103); match(T__2); setState(104); match(ID); setState(105); match(T__3); setState(106); value(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class CommandContext extends ParserRuleContext { public CommandContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_command; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).enterCommand(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).exitCommand(this); } } public final CommandContext command() throws RecognitionException { CommandContext _localctx = new CommandContext(_ctx, getState()); enterRule(_localctx, 18, RULE_command); int _la; try { enterOuterAlt(_localctx, 1); { setState(108); _la = _input.LA(1); if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__4) | (1L << T__5) | (1L << T__6))) != 0)) ) { _errHandler.recoverInline(this); } else { consume(); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ValueContext extends ParserRuleContext { public TerminalNode INT_VALUE() { return getToken(OwrlParser.INT_VALUE, 0); } public TerminalNode REAL_VALUE() { return getToken(OwrlParser.REAL_VALUE, 0); } public List<TerminalNode> ID() { return getTokens(OwrlParser.ID); } public TerminalNode ID(int i) { return getToken(OwrlParser.ID, i); } public ValueContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_value; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).enterValue(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).exitValue(this); } } public final ValueContext value() throws RecognitionException { ValueContext _localctx = new ValueContext(_ctx, getState()); enterRule(_localctx, 20, RULE_value); int _la; try { enterOuterAlt(_localctx, 1); { setState(110); match(T__2); setState(121); switch (_input.LA(1)) { case INT_VALUE: { setState(111); match(INT_VALUE); } break; case REAL_VALUE: { setState(112); match(REAL_VALUE); } break; case T__7: { { setState(113); match(T__7); setState(117); _errHandler.sync(this); _la = _input.LA(1); while (_la==ID) { { { setState(114); match(ID); } } setState(119); _errHandler.sync(this); _la = _input.LA(1); } setState(120); match(T__7); } } break; default: throw new NoViableAltException(this); } setState(123); match(T__3); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class CodContext extends ParserRuleContext { public TerminalNode INT_VALUE() { return getToken(OwrlParser.INT_VALUE, 0); } public CodContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_cod; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).enterCod(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof OwrlListener ) ((OwrlListener)listener).exitCod(this); } } public final CodContext cod() throws RecognitionException { CodContext _localctx = new CodContext(_ctx, getState()); enterRule(_localctx, 22, RULE_cod); try { enterOuterAlt(_localctx, 1); { setState(125); match(T__2); setState(126); match(INT_VALUE); setState(127); match(T__3); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static final String _serializedATN = "\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\3\17\u0084\4\2\t\2"+ "\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13"+ "\t\13\4\f\t\f\4\r\t\r\3\2\3\2\6\2\35\n\2\r\2\16\2\36\3\2\3\2\3\2\3\2\5"+ "\2%\n\2\3\3\3\3\3\3\6\3*\n\3\r\3\16\3+\3\3\3\3\3\4\3\4\3\4\7\4\63\n\4"+ "\f\4\16\4\66\13\4\3\4\3\4\3\5\3\5\7\5<\n\5\f\5\16\5?\13\5\3\5\7\5B\n\5"+ "\f\5\16\5E\13\5\3\5\3\5\3\6\3\6\3\6\7\6L\n\6\f\6\16\6O\13\6\3\6\7\6R\n"+ "\6\f\6\16\6U\13\6\3\6\3\6\3\7\3\7\3\7\3\7\3\7\3\b\3\b\3\b\3\b\3\t\3\t"+ "\3\t\3\t\6\tf\n\t\r\t\16\tg\3\n\3\n\3\n\3\n\3\n\3\13\3\13\3\f\3\f\3\f"+ "\3\f\3\f\7\fv\n\f\f\f\16\fy\13\f\3\f\5\f|\n\f\3\f\3\f\3\r\3\r\3\r\3\r"+ "\3\r\2\2\16\2\4\6\b\n\f\16\20\22\24\26\30\2\3\3\2\7\t\u0083\2$\3\2\2\2"+ "\4&\3\2\2\2\6/\3\2\2\2\b9\3\2\2\2\nH\3\2\2\2\fX\3\2\2\2\16]\3\2\2\2\20"+ "a\3\2\2\2\22i\3\2\2\2\24n\3\2\2\2\26p\3\2\2\2\30\177\3\2\2\2\32\34\7\3"+ "\2\2\33\35\5\4\3\2\34\33\3\2\2\2\35\36\3\2\2\2\36\34\3\2\2\2\36\37\3\2"+ "\2\2\37 \3\2\2\2 !\7\4\2\2!\"\7\16\2\2\"%\3\2\2\2#%\7\16\2\2$\32\3\2\2"+ "\2$#\3\2\2\2%\3\3\2\2\2&\'\5\24\13\2\')\7\3\2\2(*\5\6\4\2)(\3\2\2\2*+"+ "\3\2\2\2+)\3\2\2\2+,\3\2\2\2,-\3\2\2\2-.\7\4\2\2.\5\3\2\2\2/\60\7\3\2"+ "\2\60\64\5\f\7\2\61\63\5\b\5\2\62\61\3\2\2\2\63\66\3\2\2\2\64\62\3\2\2"+ "\2\64\65\3\2\2\2\65\67\3\2\2\2\66\64\3\2\2\2\678\7\4\2\28\7\3\2\2\29="+ "\7\3\2\2:<\5\n\6\2;:\3\2\2\2<?\3\2\2\2=;\3\2\2\2=>\3\2\2\2>C\3\2\2\2?"+ "=\3\2\2\2@B\5\20\t\2A@\3\2\2\2BE\3\2\2\2CA\3\2\2\2CD\3\2\2\2DF\3\2\2\2"+ "EC\3\2\2\2FG\7\4\2\2G\t\3\2\2\2HI\7\3\2\2IM\5\f\7\2JL\5\n\6\2KJ\3\2\2"+ "\2LO\3\2\2\2MK\3\2\2\2MN\3\2\2\2NS\3\2\2\2OM\3\2\2\2PR\5\20\t\2QP\3\2"+ "\2\2RU\3\2\2\2SQ\3\2\2\2ST\3\2\2\2TV\3\2\2\2US\3\2\2\2VW\7\4\2\2W\13\3"+ "\2\2\2XY\7\3\2\2YZ\5\16\b\2Z[\5\30\r\2[\\\7\4\2\2\\\r\3\2\2\2]^\7\5\2"+ "\2^_\7\13\2\2_`\7\6\2\2`\17\3\2\2\2ab\7\5\2\2bc\7\13\2\2ce\7\6\2\2df\5"+ "\22\n\2ed\3\2\2\2fg\3\2\2\2ge\3\2\2\2gh\3\2\2\2h\21\3\2\2\2ij\7\5\2\2"+ "jk\7\13\2\2kl\7\6\2\2lm\5\26\f\2m\23\3\2\2\2no\t\2\2\2o\25\3\2\2\2p{\7"+ "\5\2\2q|\7\f\2\2r|\7\r\2\2sw\7\n\2\2tv\7\13\2\2ut\3\2\2\2vy\3\2\2\2wu"+ "\3\2\2\2wx\3\2\2\2xz\3\2\2\2yw\3\2\2\2z|\7\n\2\2{q\3\2\2\2{r\3\2\2\2{"+ "s\3\2\2\2|}\3\2\2\2}~\7\6\2\2~\27\3\2\2\2\177\u0080\7\5\2\2\u0080\u0081"+ "\7\f\2\2\u0081\u0082\7\6\2\2\u0082\31\3\2\2\2\r\36$+\64=CMSgw{"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
24,494
26.866894
108
java
cst
cst-master/src/main/java/br/unicamp/cst/sensory/SensorBufferCodelet.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.sensory; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.MemoryObject; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Codelet implementation of SensorBuffers. In order to obtain data observation * to generate the feature maps for each dimension that will be used to compute * salience, a temporal window of data have to be stored. * @author L. M. Berto * @author L. L. Rossi (leolellisr) * @see Codelet * @see MemoryObject * @see ByteArrayInputStream * @see ByteArrayOutputStream * @see ObjectInputStream * @see ObjectOutputStream */ public class SensorBufferCodelet extends Codelet { private MemoryObject sensor_input; private MemoryObject buffer_output; private String sensorName; private String bufferName; private int maxcapacity; /** * init SensorBufferCodelet * @param sensorName * input sensor name * @param bufferName * output SensorBuffer name * @param maxcpcty * output SensorBuffer max. capacity */ public SensorBufferCodelet(String sensorName, String bufferName, int maxcpcty) { super(); this.bufferName = bufferName; this.sensorName = sensorName; maxcapacity = maxcpcty; } @Override /** * access MemoryObjects: input sensor * define output: bufferName */ public void accessMemoryObjects() { sensor_input = (MemoryObject) this.getInput(sensorName); buffer_output = (MemoryObject) this.getOutput(bufferName); } @Override public void calculateActivation() { // we don't need to calculate activation here } @Override /** * proc: codelet logical process * gets a serialized sensor_input queue of size maxcapacity * * Java serialization: * https://docs.oracle.com/javase/8/docs/technotes/guides/serialization/index.html */ public void proc() { try { Thread.sleep(10); } catch (Exception e) { Thread.currentThread().interrupt(); } List buffer_list = (List) buffer_output.getI(); if(buffer_list.size() == maxcapacity){ buffer_list.remove(0); } MemoryObject cloned_data = null; ObjectOutputStream oos; ObjectInputStream ois; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); // A oos = new ObjectOutputStream(bos); // B - serialize and pass the object oos.writeObject(sensor_input); // C oos.flush(); // D ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); // E ois = new ObjectInputStream(bin); // F - return the new object cloned_data = (MemoryObject) ois.readObject(); // G oos.close(); ois.close(); } catch(IOException | ClassNotFoundException e) { Logger.getAnonymousLogger().log(Level.INFO, "Exception in ObjectCloner = {0}", e); e.printStackTrace(); } buffer_list.add(cloned_data); buffer_output.setI(buffer_list); // This is necessary to set a new TimeStamp for the MemoryObject } }
3,999
35.697248
105
java
cst
cst-master/src/main/java/br/unicamp/cst/support/CodeletsProfiler.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.support; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.entities.MemoryContainer; import br.unicamp.cst.core.entities.MemoryObject; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; public class CodeletsProfiler { private final static String csvColumns = "MindIdentifier;Time;codeletName;ThreadName;Activation;Threshold;isLoop;TimeStep;isProfiling;"+ ";MemoryName;Evaluation;Info;Timestamp"+System.getProperty("line.separator"); private final static String openJSONList = "["+System.getProperty("line.separator"); private final static String closeJSONList = "]"+System.getProperty("line.separator"); private final static String csvSeparator = ";"; private final static String comma = ","; private final static String lineSeparator = System.getProperty("line.separator"); private String filePath; private String fileName; private String mindIdentifier; private Long intervalTimeMillis; private Integer queueSize; private long lastTimeMillis; private ConcurrentLinkedQueue<String> queue; private Gson gson = //new GsonBuilder().setPrettyPrinting().create(); new GsonBuilder().registerTypeAdapter(Memory.class, new InterfaceAdapter<MemoryObject>()) .registerTypeAdapter(Memory.class, new InterfaceAdapter<MemoryContainer>()) .setPrettyPrinting().create(); private FileFormat fileFormat; public enum FileFormat {CSV, JSON}; public CodeletsProfiler(String filePath, String fileName, String mindIdentifier, Integer queueSize, FileFormat fileFormat) { super(); this.filePath = filePath; this.fileName = fileName; this.queueSize = queueSize; if (this.queueSize == null) { this.intervalTimeMillis = 1000L; } this.mindIdentifier = mindIdentifier; this.fileFormat = fileFormat; this.initializeQueue(); } public CodeletsProfiler(String filePath, String fileName, String mindIdentifier, Long intervalTimeMillis, FileFormat fileFormat) { super(); this.filePath = filePath; this.fileName = fileName; this.mindIdentifier = mindIdentifier; this.intervalTimeMillis = intervalTimeMillis; if (this.intervalTimeMillis == null) { this.intervalTimeMillis = 1000L; } this.lastTimeMillis = System.currentTimeMillis(); this.fileFormat = fileFormat; this.initializeQueue(); } public CodeletsProfiler(String filePath, String fileName, String mindIdentifier, Integer queueSize, Long intervalTimeMillis, FileFormat fileFormat) { super(); this.filePath = filePath; this.fileName = fileName; this.mindIdentifier = mindIdentifier; this.intervalTimeMillis = intervalTimeMillis; this.lastTimeMillis = System.currentTimeMillis(); this.queueSize = queueSize; if (this.intervalTimeMillis == null && this.queueSize == null) { this.intervalTimeMillis = 1000L; } this.fileFormat = fileFormat; this.initializeQueue(); } private void initializeQueue() { if (this.queue == null) { this.queue = new ConcurrentLinkedQueue<String>(); } switch(fileFormat) { case CSV: queue.add(csvColumns); break; case JSON: queue.add(openJSONList); break; default: queue.add(openJSONList); } } private void createFile() { if (filePath != null && fileName != null) { BufferedWriter writer = null; try { File directory = new File(filePath); if (!directory.exists()){ directory.mkdir(); } File profilerFile = new File(filePath+fileName); writer = new BufferedWriter(new FileWriter(profilerFile, true)); for (String line : queue) { writer.write(line); queue.remove(line); } } catch (Exception e) { e.printStackTrace(); } finally { try { writer.close(); } catch (Exception e) { e.printStackTrace(); } } } } public class CodeletTrack { String mindId; String time; String codeletName; String threadName; double activation; double threshold; boolean isLoop; String timeStep; boolean isProfiling; String separator; List<Memory> mInputs; List<Memory> mOutputs; List<Memory> mBroadcasts; public String codeletClass; public CodeletTrack(Codelet c) { mindId = mindIdentifier; time = TimeStamp.getStringTimeStamp(System.currentTimeMillis(),"dd/MM/yyyy HH:mm:ss.SSS"); codeletName = c.getName(); threadName = c.getThreadName(); activation = c.getActivation(); threshold = c.getThreshold(); isLoop = c.isLoop(); timeStep = TimeStamp.getStringTimeStamp(c.getTimeStep(),"dd/MM/yyyy HH:mm:ss.SSS"); isProfiling = c.isProfiling(); separator = System.getProperty("line.separator"); mInputs = c.getInputs(); mOutputs = c.getOutputs(); mBroadcasts = c.getBroadcast(); codeletClass = c.getClass().getCanonicalName(); } } private void addJsonText(Codelet c) { String textBlock = gson.toJson(new CodeletTrack(c)); queue.add(lineSeparator + textBlock + comma); } private void addCSVText(Codelet c) { String textBlock = mindIdentifier +csvSeparator+System.currentTimeMillis()+csvSeparator+c.getName()+csvSeparator+c.getThreadName()+csvSeparator+c.getActivation()+";"+ c.getThreshold()+csvSeparator+c.isLoop()+csvSeparator+c.getTimeStep()+csvSeparator+c.isProfiling()+csvSeparator+csvSeparator+csvSeparator+csvSeparator+lineSeparator; queue.add(textBlock); } private void addTextToQueue(Codelet c) { switch(fileFormat) { case CSV: addCSVText(c); break; case JSON: addJsonText(c); break; default: addJsonText(c); } } private void finalizeJSONFile() { BufferedWriter writer = null; try { File profilerFile = new File(filePath+fileName); writer = new BufferedWriter(new FileWriter(profilerFile, true)); writer.write(closeJSONList); } catch (Exception e) { e.printStackTrace(); } finally { try { // Close the writer regardless of what happens... writer.close(); } catch (Exception e) { e.printStackTrace(); } } } private void fillQueue(Codelet c) { this.addTextToQueue(c); //If the one of the the variables is met, will write in file long currentTime = System.currentTimeMillis(); if (queueSize != null && intervalTimeMillis != null) { if (queue.size() > queueSize.intValue() || (currentTime - lastTimeMillis) > intervalTimeMillis.longValue()) { this.createFile(); lastTimeMillis = System.currentTimeMillis(); } } else if (queueSize != null && queue.size() > queueSize.intValue()) { this.createFile(); } else if (intervalTimeMillis != null && (currentTime - lastTimeMillis) > intervalTimeMillis.longValue()) { this.createFile(); lastTimeMillis = System.currentTimeMillis(); } } public void profile(Codelet c) { fillQueue(c); } public void finishProfile(Codelet c) { addTextToQueue(c); createFile(); if (fileFormat == FileFormat.JSON) { finalizeJSONFile(); } } }
8,921
33.183908
180
java
cst
cst-master/src/main/java/br/unicamp/cst/support/ExecutionTimeWriter.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.support; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.List; /** * @author andre * */ public class ExecutionTimeWriter implements Runnable { private String codeletName; private List<ProfileInfo> profileInfo; public String path = ""; /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { if(codeletName!=null && profileInfo!=null && profileInfo.size()>0){ BufferedWriter writer = null; try { File directory = new File(path); if (! directory.exists()){ directory.mkdir(); // If you require it to make the entire directory path including parents, // use directory.mkdirs(); here instead. } File logFile = new File(path+codeletName+"_profile.csv"); // This will output the full path where the file will be written to... //System.out.println("Creating log with profile at ... "+logFile.getCanonicalPath()); writer = new BufferedWriter(new FileWriter(logFile, true)); for(ProfileInfo profile : profileInfo){ //writer.write(profile.executionTime+" "+profile.callingTime+" "+profile.lastCallingTime+" "+(profile.callingTime-profile.lastCallingTime)+"\n"); // We will be profiling just the proc() execution time and the codelet calling interval writer.write(TimeStamp.getStringTimeStamp(profile.callingTime, "dd/MM/yyyy HH:mm:ss.SSS")+" "+profile.executionTime+" "+(profile.callingTime-profile.lastCallingTime)+"\n"); } } catch (Exception e) { e.printStackTrace(); } finally { try { // Close the writer regardless of what happens... writer.close(); } catch (Exception e) { } } } } /** * @param codeletName the codeletName to set */ public void setCodeletName(String codeletName) { this.codeletName = codeletName; } /** * @param cPath the path to set */ public void setPath(String cPath) { this.path = cPath; } /** * @param profileInfo the list of profile info collected */ public void setProfileInfo(List<ProfileInfo> profileInfo) { this.profileInfo = profileInfo; } }
3,176
30.77
196
java