Ejemplo n.º 1
0
  public weka.core.Instances toWekaInstances() {
    // attributes
    FastVector wattrs = new FastVector();
    Iterator itr = attributes.iterator();
    while (itr.hasNext()) {
      Attribute attr = (Attribute) itr.next();
      wattrs.addElement(attr.toWekaAttribute());
    }
    // data instances
    weka.core.Instances winsts = new weka.core.Instances(name, wattrs, instances.size());
    itr = instances.iterator();

    while (itr.hasNext()) {
      Instance inst = (Instance) itr.next();
      Iterator itrval = inst.getValues().iterator();
      Iterator itrmis = inst.getMissing().iterator();
      double[] vals = new double[wattrs.size()];
      for (int i = 0; i < wattrs.size(); i++) {
        double val = (Double) itrval.next();
        if ((Boolean) itrmis.next()) {
          vals[i] = weka.core.Instance.missingValue();
        } else {
          vals[i] = val;
        }
      }
      weka.core.Instance winst = new weka.core.Instance(1, vals);
      winst.setDataset(winsts);
      winsts.add(winst);
    }
    winsts.setClassIndex(this.class_index);
    return winsts;
  }
Ejemplo n.º 2
0
  protected void startNode()
      throws IMTPException, ProfileException, ServiceException, JADESecurityException,
          NotFoundException {
    // Initialize all services (without activating them)
    List services = new ArrayList();
    initMandatoryServices(services);

    List l = myProfile.getSpecifiers(Profile.SERVICES);
    myProfile.setSpecifiers(Profile.SERVICES, l); // Avoid parsing services twice
    initAdditionalServices(l.iterator(), services);

    // Register with the platform
    ServiceDescriptor[] descriptors = new ServiceDescriptor[services.size()];
    for (int i = 0; i < descriptors.length; ++i) {
      descriptors[i] = (ServiceDescriptor) services.get(i);
    }
    if (theBEManager != null) {
      myNodeDescriptor.setParentNode(theBEManager.getNode());
    }
    // Actually join the platform (this call can modify the name of this container)
    getServiceManager().addNode(myNodeDescriptor, descriptors);
    if (theBEManager != null) {
      theBEManager.register(myNodeDescriptor);
    }

    // Once we are connected, boot all services
    bootAllServices(services);
  }
Ejemplo n.º 3
0
 /**
  * Get the current child
  *
  * @see CompositeBehaviour#getCurrent
  */
 protected Behaviour getCurrent() {
   Behaviour b = null;
   if (subBehaviours.size() > current) {
     b = (Behaviour) subBehaviours.get(current);
   }
   return b;
 }
Ejemplo n.º 4
0
  protected void handleInform(ACLMessage msg) {
    try {
      notYetReady = false;
      lastMsg = (ACLMessage) msg.clone();
      if (this.action.equalsIgnoreCase(DFAppletVocabulary.FEDERATE)) {
        gui.showStatusMsg("Request processed. Ready for new  request.");
        gui.addParent(this.parent);
      } else if (this.action.equalsIgnoreCase(DFAppletVocabulary.GETDESCRIPTION)) {
        // UPDATE the thisDf variable.
        try {
          List result = getResult();
          dfApplet.setDescription((DFAgentDescription) result.get(0));
        } catch (NotYetReady nyr) {
          // FIXME: what should happen in this case ?
          nyr.printStackTrace();
        }
      } else if (this.action.equalsIgnoreCase(DFAppletVocabulary.GETPARENTS))
        gui.showStatusMsg("Request processed. Ready for new Request.");
      else if (this.action.equalsIgnoreCase(DFAppletVocabulary.DEREGISTERFROM)) {
        gui.showStatusMsg("Request processed. Ready for a new request");
        gui.removeParent(this.parent);
      } else if (this.action.equalsIgnoreCase(DFAppletVocabulary.REGISTERWITH))
        gui.showStatusMsg("Request processed. Ready for new request.");
      else if (this.action.equalsIgnoreCase(DFAppletVocabulary.SEARCHON)) {
        gui.refreshLastSearchResults(getResult(), (AID) parent);
        gui.showStatusMsg("Request processed. Ready for new request.");
      } else if (this.action.equalsIgnoreCase(DFAppletVocabulary.MODIFYON))
        gui.showStatusMsg("Request processed. Ready for new request.");

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 5
0
  private pikater.ontology.messages.Option convertOption(MyWekaOption _weka_opt) {
    pikater.ontology.messages.Option opt = new pikater.ontology.messages.Option();
    Interval interval = null;
    opt.setMutable(_weka_opt.mutable);

    interval = new Interval();
    interval.setMin(_weka_opt.lower);
    interval.setMax(_weka_opt.upper);
    opt.setRange(interval);

    if (_weka_opt.set != null) {
      // copy array to List
      List set = new ArrayList();
      for (int i = 0; i < _weka_opt.set.length; i++) {
        set.add(_weka_opt.set[i]);
      }
      opt.setSet(set);
    }

    opt.setIs_a_set(_weka_opt.isASet);

    interval = new Interval();
    interval.setMin(_weka_opt.numArgsMin);
    interval.setMax(_weka_opt.numArgsMax);
    opt.setNumber_of_args(interval);

    opt.setData_type(_weka_opt.type.toString());
    opt.setDescription(_weka_opt.description);
    opt.setName(_weka_opt.name);
    opt.setSynopsis(_weka_opt.synopsis);
    opt.setDefault_value(_weka_opt.default_value);
    opt.setValue(_weka_opt.default_value);
    return opt;
  }
Ejemplo n.º 6
0
  public List removePendingMessages(MessageTemplate template) {
    synchronized (pendingCommands) {
      List messages = new ArrayList();
      List commands = new ArrayList();
      Enumeration e = pendingCommands.elements();
      while (e.hasMoreElements()) {
        PostponedCommand pc = (PostponedCommand) e.nextElement();
        Command c = pc.getCommand();
        if (c.getCode() == FrontEndSkel.MESSAGE_IN) {
          ACLMessage msg = (ACLMessage) c.getParamAt(0);
          if (template.match(msg)) {
            Object[] oo = new Object[] {msg, c.getParamAt(1)};
            messages.add(oo);
            commands.add(c);
          }
        }
      }
      // Remove all the commands carrying matching messages
      Iterator it = commands.iterator();
      while (it.hasNext()) {
        pendingCommands.remove(it.next());
      }

      // Return the list of matching messages
      return messages;
    }
  }
Ejemplo n.º 7
0
 void initMandatoryServices(List services) throws ServiceException {
   ServiceDescriptor dsc = startService("jade.core.management.BEAgentManagementService", false);
   dsc.setMandatory(true);
   services.add(dsc);
   dsc = startService("jade.core.messaging.MessagingService", false);
   dsc.setMandatory(true);
   services.add(dsc);
 }
Ejemplo n.º 8
0
  public void doNotSniff(String agentName) {
    String realName = checkString(agentName);
    agent = new Agent(realName);

    noSniffedAgents.add(agent);
    mainPanel.panelcan.canvAgent.removeAgent(agent.agentName);
    mainPanel.panelcan.canvAgent.repaintNoSniffedAgent(agent);
    mySniffer.sniffMsg(noSniffedAgents, Sniffer.SNIFF_OFF); // Sniff the Agents
    noSniffedAgents.clear();
  }
Ejemplo n.º 9
0
  /** returns the results of an action requested. */
  public List getResult() throws FIPAException, NotYetReady {
    if (notYetReady) throw new NotYetReady();
    if (lastMsg.getPerformative() != ACLMessage.INFORM) throw new FIPAException(lastMsg);

    Result r = AppletRequestProto.extractContent(lastMsg.getContent(), (SLCodec) c, o);
    Iterator i = r.getItems().iterator(); // this is the set of DFAgentDescription
    List l = new ArrayList();
    while (i.hasNext()) l.add(i.next());
    return l;
  }
    private String checkAskedDiscreteDomain(Attribute askedAttribute, String value) {
      List askedValues = askedAttribute.getDiscreteDomain();
      for (int i = 0; i < askedValues.size(); i++) {
        if (askedValues.get(i).equals(value)) {
          return value;
        }
      }

      return String.valueOf(askedValues.get((int) (askedValues.size() * Math.random())));
    }
Ejemplo n.º 11
0
 /* returns a value in the table on the row and index */
 public String toString(int row, int index) {
   if (instances == null) {
     return "";
   }
   Instance inst = (Instance) instances.get(row);
   return inst.toString(this, index);
 }
Ejemplo n.º 12
0
 /** Remove a sub behaviour from this <code>SequentialBehaviour</code> */
 public void removeSubBehaviour(Behaviour b) {
   boolean rc = subBehaviours.remove(b);
   if (rc) {
     b.setParent(null);
   } else {
     // The specified behaviour was not found. Do nothing
   }
 }
Ejemplo n.º 13
0
  private String[] parseAddressList(String toParse) {

    StringTokenizer lexer = new StringTokenizer(toParse, ADDR_LIST_DELIMITERS);
    List addresses = new ArrayList();
    while (lexer.hasMoreTokens()) {
      String tok = lexer.nextToken();
      addresses.add(tok);
    }

    Object[] objs = addresses.toArray();
    String[] result = new String[objs.length];
    for (int i = 0; i < result.length; i++) {
      result[i] = (String) objs[i];
    }

    return result;
  }
Ejemplo n.º 14
0
  // For persistence service
  private Behaviour[] getSubBehaviours() {
    Object[] objs = subBehaviours.toArray();
    Behaviour[] result = new Behaviour[objs.length];
    for (int i = 0; i < objs.length; i++) {
      result[i] = (Behaviour) objs[i];
    }

    return result;
  }
Ejemplo n.º 15
0
 private void notifySynchronized() {
   synchronized (frontEndSynchLock) {
     Iterator it = fronEndSynchBuffer.iterator();
     while (it.hasNext()) {
       try {
         MessageSenderPair msp = (MessageSenderPair) it.next();
         messageOut(msp.getMessage(), msp.getSender());
       } catch (NotFoundException nfe) {
         // The sender does not exist --> nothing to notify
         nfe.printStackTrace();
       } catch (IMTPException imtpe) {
         // Should never happen since this is a local call
         imtpe.printStackTrace();
       }
     }
     fronEndSynchBuffer.clear();
     synchronizing = false;
   }
 }
Ejemplo n.º 16
0
  Object processInformation(Information info) {
    // -------------------------------------------

    Account acc = (Account) accounts.get(info.getAccountId());
    if (acc == null) return newProblem(ACCOUNT_NOT_FOUND);

    java.util.Date date = new java.util.Date();
    Operation op = new Operation(); // <-- Apply admin charge
    op.setType(ADMIN);
    op.setAmount(info.getType() == BALANCE ? BAL_CHARGE : OPER_CHARGE);
    acc.setBalance(acc.getBalance() - op.getAmount());
    op.setBalance(acc.getBalance());
    op.setAccountId(acc.getId());
    op.setDate(date);
    List l = (List) operations.get(acc.getId());
    l.add(op);
    operations.put(acc.getId(), l);

    if (info.getType() == BALANCE) return acc;
    if (info.getType() == OPERATIONS) return l;
    return null;
  }
Ejemplo n.º 17
0
  Object processOperation(MakeOperation mo) {
    // -------------------------------------------

    Account acc = (Account) accounts.get(mo.getAccountId());
    if (acc == null) return newProblem(ACCOUNT_NOT_FOUND);
    if (mo.getAmount() <= 0) return newProblem(ILLEGAL_OPERATION);

    if (mo.getType() != DEPOSIT && mo.getType() != WITHDRAWAL) return null;
    if (mo.getType() == DEPOSIT) acc.setBalance(acc.getBalance() + mo.getAmount());
    else if (mo.getType() == WITHDRAWAL) {
      if (mo.getAmount() > acc.getBalance()) return newProblem(NOT_ENOUGH_MONEY);
      acc.setBalance(acc.getBalance() - mo.getAmount());
    }
    Operation op = new Operation();
    op.setType(mo.getType());
    op.setAmount(mo.getAmount());
    op.setAccountId(acc.getId());
    op.setDate(new java.util.Date());
    List l = (List) operations.get(acc.getId());
    l.add(op);
    operations.put(acc.getId(), l);
    return acc;
  }
Ejemplo n.º 18
0
 /*
  * returns all instances as a multi-line string
  */
 @Override
 public String toString() {
   if (instances == null) {
     return "";
   }
   StringBuffer text = new StringBuffer();
   Iterator institr = instances.iterator();
   while (institr.hasNext()) {
     Instance inst = (Instance) institr.next();
     text.append(inst.toString(this));
     text.append('\n');
   }
   return text.toString();
 }
Ejemplo n.º 19
0
  public void fillWekaInstances(weka.core.Instances winsts) {
    // set name
    setName(winsts.relationName());
    // set attributes
    List onto_attrs = new ArrayList();
    for (int i = 0; i < winsts.numAttributes(); i++) {
      Attribute a = new Attribute();
      a.fillWekaAttribute(winsts.attribute(i));
      onto_attrs.add(a);
    }
    setAttributes(onto_attrs);

    // set instances
    List onto_insts = new ArrayList();
    for (int i = 0; i < winsts.numInstances(); i++) {
      Instance inst = new Instance();
      weka.core.Instance winst = winsts.instance(i);

      List instvalues = new ArrayList();
      List instmis = new ArrayList();
      for (int j = 0; j < winst.numValues(); j++) {
        if (winst.isMissing(j)) {
          instvalues.add(new Double(0.0));
          instmis.add(new Boolean(true));
        } else {
          instvalues.add(new Double(winst.value(j)));
          instmis.add(new Boolean(false));
        }
      }

      inst.setValues(instvalues);
      inst.setMissing(instmis);
      onto_insts.add(inst);
    }
    setInstances(onto_insts);
    setClass_index(winsts.classIndex());
  }
Ejemplo n.º 20
0
 public List removePendingMessages(MessageTemplate template, boolean notifyFailure) {
   List pendingMsg = ((jade.imtp.leap.FrontEndStub) myFrontEnd).removePendingMessages(template);
   if (pendingMsg.size() > 0) {
     myLogger.log(
         Logger.INFO, "Removed " + pendingMsg.size() + " pending messages from BackEnd queue.");
   }
   if (notifyFailure) {
     Iterator it = pendingMsg.iterator();
     while (it.hasNext()) {
       try {
         Object[] removed = (Object[]) it.next();
         ACLMessage msg = (ACLMessage) removed[0];
         AID receiver = new AID((String) removed[1], AID.ISLOCALNAME);
         ServiceFinder myFinder = getServiceFinder();
         MessagingService msgSvc = (MessagingService) myFinder.findService(MessagingSlice.NAME);
         msgSvc.notifyFailureToSender(
             new GenericMessage(msg), receiver, new InternalError("Agent dead"));
       } catch (Exception e) {
         myLogger.log(Logger.WARNING, "Cannot send AMS FAILURE. " + e);
       }
     }
   }
   return pendingMsg;
 }
Ejemplo n.º 21
0
  @Override
  protected Agent chooseBestAgent(Data data) {

    Metadata metadata = data.getMetadata();

    GetAllMetadata gm = new GetAllMetadata();
    gm.setResults_required(true);

    // 1. choose the nearest training data
    List allMetadata = DataManagerService.getAllMetadata(this, gm);

    // set the min, max instances and attributes first
    Iterator itr = allMetadata.iterator();
    while (itr.hasNext()) {
      Metadata next_md = (Metadata) itr.next();

      int na = next_md.getNumber_of_attributes();
      minAttributes = Math.min(minAttributes, na);
      maxAttributes = Math.max(maxAttributes, na);

      int ni = next_md.getNumber_of_instances();
      minInstances = Math.min(ni, minInstances);
      maxInstances = Math.max(ni, maxInstances);
    }

    ArrayList<MetadataDistancePair> distances = new ArrayList<MetadataDistancePair>();

    itr = allMetadata.iterator();
    while (itr.hasNext()) {
      Metadata next_md = (Metadata) itr.next();
      double dNew = distance(metadata, next_md);

      distances.add(new MetadataDistancePair(next_md, dNew));
    }

    Collections.sort(distances);

    List agents = new LinkedList();
    for (int i = 0; i < M; i++) {
      log(distances.get(i).m.getExternal_name() + ": " + distances.get(i).d);
      List ag = DataManagerService.getTheBestAgents(this, distances.get(i).m.getInternal_name(), N);
      Iterator it = ag.iterator();
      while (it.hasNext()) {
        agents.add(it.next());
      }
    }

    HashMap<String, Integer> counts = new HashMap<String, Integer>();

    Iterator it = agents.iterator();
    while (it.hasNext()) {
      Agent a = (Agent) it.next();

      if (counts.containsKey(a.getType())) {
        counts.put(a.getType(), counts.get(a.getType()) + 1);
      } else {
        counts.put(a.getType(), 1);
      }
    }

    int maxCount = 0;
    String bestAgentType = null;
    for (String s : counts.keySet()) {
      log(s + ": " + counts.get(s));
      if (counts.get(s) > maxCount) {
        maxCount = counts.get(s);
        bestAgentType = s;
      }
    }

    log("Best agent: " + bestAgentType);

    ArrayList<Agent> bestAgentOptions = new ArrayList<Agent>();

    it = agents.iterator();
    while (it.hasNext()) {
      Agent a = (Agent) it.next();

      if (a.getType().equals(bestAgentType)) {
        bestAgentOptions.add(a);
      }
    }

    List optionSamples = getAgentOptions(bestAgentType);
    List options = new LinkedList();
    it = optionSamples.iterator();
    while (it.hasNext()) {
      Option o = (Option) it.next();

      Option newOpt = o.copyOption();

      // ignore boolean and set options for now, set their value to the one of the best agent on
      // closest file
      if (o.getData_type().equals("BOOLEAN") || o.getData_type().equals("MIXED")) {
        if (bestAgentOptions.get(0).getOptionByName(o.getName()) == null) {
          continue;
        }
        newOpt.setValue(bestAgentOptions.get(0).getOptionByName(o.getName()).getValue());
      } else {
        double sum = 0;
        int count = 0;
        String optionName = o.getName();
        for (Agent a : bestAgentOptions) {
          if (a.getOptionByName(optionName) != null) {
            sum += Double.parseDouble(a.getOptionByName(optionName).getValue());
          }
          count++;
        }
        double avg = sum / count;

        double stdDev = 0;
        for (Agent a : bestAgentOptions) {
          if (a.getOptionByName(optionName) != null) {
            stdDev +=
                Math.pow(Double.parseDouble(a.getOptionByName(optionName).getValue()) - avg, 2);
          }
        }

        stdDev = Math.sqrt(stdDev / count);

        if (stdDev > 0) {
          newOpt.setValue("?");
          newOpt.setUser_value("?");
          newOpt.setMutable(true);
          Interval range = new Interval();
          range.setMin((float) Math.max(avg - 2 * stdDev, o.getRange().getMin()));
          range.setMax((float) Math.min(avg + 2 * stdDev, o.getRange().getMax()));
          newOpt.setRange(range);
        } else {
          if (o.getData_type().equals("FLOAT")) {
            newOpt.setValue(Double.toString(avg));
          }
          if (o.getData_type().equals("INT")) {
            newOpt.setValue(Integer.toString((int) avg));
          }
        }
      }
      options.add(newOpt);
    }

    Agent agent = new Agent();
    agent.setName(null);
    agent.setType(bestAgentType);
    agent.setOptions(options);

    return agent;
  }
Ejemplo n.º 22
0
 private void postponeAfterFrontEndSynch(ACLMessage msg, String sender) {
   // No need for synchronization since this is called within a synchronized block
   fronEndSynchBuffer.add(new MessageSenderPair(msg, sender));
 }
Ejemplo n.º 23
0
 public Iterator getAllDescribedBy() {
   return describedBy.iterator();
 }
Ejemplo n.º 24
0
 public void clearAllDescribedBy() {
   describedBy.clear();
 }
Ejemplo n.º 25
0
 public boolean removeDescribedBy(Object elem) {
   boolean result = describedBy.remove(elem);
   return result;
 }
Ejemplo n.º 26
0
 public void addDescribedBy(Object elem) {
   describedBy.add(elem);
 }
Ejemplo n.º 27
0
 public Iterator getAllApliesTo() {
   return apliesTo.iterator();
 }
Ejemplo n.º 28
0
 public void clearAllApliesTo() {
   apliesTo.clear();
 }
Ejemplo n.º 29
0
 public boolean removeApliesTo(Object elem) {
   boolean result = apliesTo.remove(elem);
   return result;
 }
Ejemplo n.º 30
0
 public void addApliesTo(Object elem) {
   apliesTo.add(elem);
 }