Exemple #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;
  }
 // #APIDOC_EXCLUDE_BEGIN
 public static void notifyFailureToSender(ACLMessage msg, String sender, String error) {
   if (myFrontEnd != null) {
     // Send back a failure message
     try {
       Iterator it = msg.getAllReceiver();
       while (it.hasNext()) {
         AID receiver = (AID) it.next();
         // If this receiver is local, the message has certainly been delivered
         // successfully --> Do not send any FAILURE back for this receiver
         if (myFrontEnd.getLocalAgent(receiver.getLocalName()) == null) {
           ACLMessage failure = msg.createReply();
           failure.setPerformative(ACLMessage.FAILURE);
           failure.setSender(myFrontEnd.getAMS());
           failure.setLanguage(FIPANames.ContentLanguage.FIPA_SL);
           String content = "( (action " + sender;
           content = content + " (ACLMessage) ) (MTS-error " + receiver + " \"" + error + "\") )";
           failure.setContent(content);
           myFrontEnd.messageIn(failure, sender);
         }
       }
     } catch (Exception e1) {
       logger.log(Logger.SEVERE, "Error delivering FAILURE message.", e1);
     }
   }
 }
Exemple #3
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;
    }
  }
Exemple #4
0
 /**
  * create a new ACLMessage that is a reply to this message. In particular, it sets the following
  * parameters of the new message: receiver, language, ontology, protocol, conversation-id,
  * in-reply-to, reply-with. The programmer needs to set the communicative-act and the content. Of
  * course, if he wishes to do that, he can reset any of the fields.
  *
  * @return the ACLMessage to send as a reply
  */
 public ACLMessage createReply() {
   ACLMessage m = new ACLMessage(getPerformative());
   Iterator it = getAllReplyTo();
   while (it.hasNext()) m.addReceiver((AID) it.next());
   if ((reply_to == null) || reply_to.isEmpty()) m.addReceiver(getSender());
   m.setLanguage(getLanguage());
   m.setOntology(getOntology());
   m.setProtocol(getProtocol());
   m.setInReplyTo(getReplyWith());
   if (source != null) m.setReplyWith(source.getName() + java.lang.System.currentTimeMillis());
   else m.setReplyWith("X" + java.lang.System.currentTimeMillis());
   m.setConversationId(getConversationId());
   // Copy only well defined user-def-params
   String trace = getUserDefinedParameter(TRACE);
   if (trace != null) {
     m.addUserDefinedParameter(TRACE, trace);
   }
   // #CUSTOM_EXCLUDE_BEGIN
   // Set the Aclrepresentation of the reply message to the aclrepresentation of the sent message
   if (messageEnvelope != null) {
     m.setDefaultEnvelope();
     String aclCodec = messageEnvelope.getAclRepresentation();
     if (aclCodec != null) m.getEnvelope().setAclRepresentation(aclCodec);
   } else m.setEnvelope(null);
   // #CUSTOM_EXCLUDE_END
   return m;
 }
Exemple #5
0
 /**
  * Translates <code>Map</code> object from <i>Messaging<i> ontology into Java <code>Map</code>
  * form.
  *
  * @param inMap is Map object from the ontology
  * @return Java Map form of <code>inMap</code>
  */
 public static Map<String, String> getMap(ibspan.tss.messaging.ontology.Map inMap) {
   HashMap<String, String> outMap = new HashMap<String, String>();
   for (Iterator it = inMap.getAllHasEntry(); it.hasNext(); ) {
     MapEntry entry = (MapEntry) it.next();
     outMap.put(entry.getKey(), entry.getValue());
   }
   return outMap;
 }
 public void action() {
   // Receives information about people joining and leaving
   // the chat from the ChatManager agent
   ACLMessage msg = myAgent.receive(template);
   if (msg != null) {
     if (msg.getPerformative() == ACLMessage.INFORM) {
       try {
         AbsPredicate p = (AbsPredicate) myAgent.getContentManager().extractAbsContent(msg);
         if (p.getTypeName().equals(ChatOntology.JOINED)) {
           // Get new participants, add them to the list of participants
           // and notify the gui
           AbsAggregate agg = (AbsAggregate) p.getAbsTerm(ChatOntology.JOINED_WHO);
           if (agg != null) {
             Iterator it = agg.iterator();
             while (it.hasNext()) {
               AbsConcept c = (AbsConcept) it.next();
               participants.add(BasicOntology.getInstance().toObject(c));
             }
           }
           myGui.notifyParticipantsChanged(getParticipantNames());
         }
         if (p.getTypeName().equals(ChatOntology.LEFT)) {
           // Get old participants, remove them from the list of participants
           // and notify the gui
           AbsAggregate agg = (AbsAggregate) p.getAbsTerm(ChatOntology.JOINED_WHO);
           if (agg != null) {
             Iterator it = agg.iterator();
             while (it.hasNext()) {
               AbsConcept c = (AbsConcept) it.next();
               participants.remove(BasicOntology.getInstance().toObject(c));
             }
           }
           myGui.notifyParticipantsChanged(getParticipantNames());
         }
       } catch (Exception e) {
         Logger.println(e.toString());
         e.printStackTrace();
       }
     } else {
       handleUnexpected(msg);
     }
   } else {
     block();
   }
 }
 private boolean isExplicitReceiver(ACLMessage msg, AID receiver) {
   Iterator it = msg.getAllIntendedReceiver();
   while (it.hasNext()) {
     if (receiver.equals(it.next())) {
       return true;
     }
   }
   return false;
 }
  /** 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 utility methods
 //////////////////////////
 private String[] getParticipantNames() {
   String[] pp = new String[participants.size()];
   Iterator it = participants.iterator();
   int i = 0;
   while (it.hasNext()) {
     AID id = (AID) it.next();
     pp[i++] = id.getLocalName();
   }
   return pp;
 }
 protected void resetChildren() {
   Collection c = getChildren();
   if (c != null) {
     Iterator it = c.iterator();
     while (it.hasNext()) {
       Behaviour b = (Behaviour) it.next();
       b.reset();
     }
   }
 }
 public void action() {
   spokenMsg.clearAllReceiver();
   Iterator it = participants.iterator();
   while (it.hasNext()) {
     spokenMsg.addReceiver((AID) it.next());
   }
   spokenMsg.setContent(sentence);
   myGui.notifySpoken(myAgent.getLocalName(), sentence);
   send(spokenMsg);
 }
Exemple #12
0
  // #MIDP_EXCLUDE_BEGIN
  public synchronized Object clone() {

    ACLMessage result;

    try {
      result = (ACLMessage) super.clone();
      result.persistentID = null;
      if (source != null) {
        result.source = (AID) source.clone();
      }

      // Deep clone receivers
      if (dests != null) {
        result.dests = new ArrayList(dests.size());
        Iterator it = dests.iterator();
        while (it.hasNext()) {
          AID id = (AID) it.next();
          result.dests.add(id.clone());
        }
      }

      // Deep clone reply_to
      if (reply_to != null) {
        result.reply_to = new ArrayList(reply_to.size());
        Iterator it = reply_to.iterator();
        while (it.hasNext()) {
          AID id = (AID) it.next();
          result.reply_to.add(id.clone());
        }
      }

      // Deep clone user-def-properties if present
      if (userDefProps != null) result.userDefProps = (Properties) userDefProps.clone();
      // Deep clone envelope if present
      if (messageEnvelope != null) result.messageEnvelope = (Envelope) messageEnvelope.clone();
    } catch (CloneNotSupportedException cnse) {
      throw new InternalError(); // This should never happen
    }

    return result;
  }
  /**
   * Associates this behaviour with the agent it belongs to. Overrides the method in the base class
   * to propagate the setting to all children.
   *
   * @param a The agent this behaviour belongs to.
   * @see Behaviour#setAgent(Agent a)
   */
  public void setAgent(Agent a) {
    Collection c = getChildren();
    if (c != null) {
      Iterator it = c.iterator();
      while (it.hasNext()) {
        Behaviour b = (Behaviour) it.next();
        b.setAgent(a);
      }
    }

    super.setAgent(a);
  }
Exemple #14
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();
 }
Exemple #15
0
 /**
  * Writes the message envelope for this message, using the <code>:sender</code> and <code>
  * :receiver</code> message slots to fill in the envelope.
  *
  * @see jade.lang.acl#setEnvelope(Envelope e)
  * @see jade.lang.acl#getEnvelope()
  */
 public void setDefaultEnvelope() {
   messageEnvelope = new Envelope();
   messageEnvelope.setFrom(source);
   // #MIDP_EXCLUDE_BEGIN
   Iterator it = dests.iterator();
   // #MIDP_EXCLUDE_END
   /*#MIDP_INCLUDE_BEGIN
   Iterator it = new EnumIterator(dests.elements());
   #MIDP_INCLUDE_END*/
   while (it.hasNext()) messageEnvelope.addTo((AID) it.next());
   // #MIDP_EXCLUDE_BEGIN
   messageEnvelope.setAclRepresentation(StringACLCodec.NAME);
   // #MIDP_EXCLUDE_END
   messageEnvelope.setDate(new Date());
 }
 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;
   }
 }
  /**
   * Utility method that updates the contact list extracting contact info and location from DF
   * descriptions.
   *
   * @param onlineContactsDescs array of {@link DFAgentDescription} objects that define services as
   *     results of a DF query
   */
  private void updateContactList(DFAgentDescription[] onlineContactsDescs) {

    for (int i = 0; i < onlineContactsDescs.length; i++) {
      Iterator serviceDescIt = onlineContactsDescs[i].getAllServices();

      if (serviceDescIt.hasNext()) {
        ServiceDescription desc = (ServiceDescription) serviceDescIt.next();

        Iterator propertyIt = desc.getAllProperties();
        Location loc = Helper.extractLocation(propertyIt);

        AID cId = onlineContactsDescs[i].getName();
        if (!cId.equals(myAgent.getAID())) {
          // Create an online contact (or update it)
          String phoneNumber = cId.getLocalName();
          ContactManager.getInstance().addOrUpdateOnlineContact(phoneNumber, loc);
        }
      }
    }
  }
  private Location parseAMSResponse(ACLMessage response) {
    Result results = null;

    try {
      results = (Result) getContentManager().extractContent(response);
    } catch (UngroundedException e) {
      e.printStackTrace();
    } catch (CodecException e) {
      e.printStackTrace();
    } catch (OntologyException e) {
      e.printStackTrace();
    }

    Iterator it = results.getItems().iterator();

    Location loc = null;

    if (it.hasNext()) loc = (Location) it.next();

    return loc;
  }
    /**
     * Extract a Location from a list of properties from a Service description
     *
     * @param it iterator over the list of properties
     * @return the location on the map described by this set of properties
     */
    public static Location extractLocation(Iterator it) {
      Location loc = new Location("mygps");

      while (it.hasNext()) {
        Property p = (Property) it.next();

        String propertyName = p.getName();

        if (propertyName.equals(DFUpdaterBehaviour.PROPERTY_NAME_LOCATION_ALT)) {
          double altitude = Double.parseDouble((String) p.getValue());
          loc.setAltitude(altitude);
        } else if (propertyName.equals(DFUpdaterBehaviour.PROPERTY_NAME_LOCATION_LAT)) {
          double latitude = Double.parseDouble((String) p.getValue());
          loc.setLatitude(latitude);
        } else if (propertyName.equals(DFUpdaterBehaviour.PROPERTY_NAME_LOCATION_LONG)) {
          double longitude = Double.parseDouble((String) p.getValue());
          loc.setLongitude(longitude);
        }
      }

      return loc;
    }
 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;
 }
Exemple #21
0
  @Override
  protected DataInstances getPredictions(Instances test, DataInstances onto_test) {

    Evaluation eval = test();
    double pre[] = new double[test.numInstances()];
    for (int i = 0; i < test.numInstances(); i++) {
      try {
        pre[i] = eval.evaluateModelOnce((Classifier) getModelObject(), test.instance(i));
      } catch (Exception e) {
        pre[i] = Integer.MAX_VALUE;
      }
    }

    // copy results to the DataInstancs
    int i = 0;
    Iterator itr = onto_test.getInstances().iterator();
    while (itr.hasNext()) {
      Instance next_instance = (Instance) itr.next();
      next_instance.setPrediction(pre[i]);
      i++;
    }

    return onto_test;
  }
    /**
     * Overrides SubscriptionInitiator.handleInform(), defining what to do each time the DF is
     * modified by a contact Basically it adds/removes/updates contacts from ContactList according
     * to what has happened to DF. It also fires events on the GUI any time a view refresh is
     * needed.
     *
     * @param inform the message from DF containing a list of changes
     */
    protected void handleInform(ACLMessage inform) {

      myLogger.log(
          Logger.FINE,
          "Thread " + Thread.currentThread().getId() + ": Notification received from DF");
      ContactManager.getInstance().resetModifications();

      try {

        DFAgentDescription[] results = DFService.decodeNotification(inform.getContent());

        if (results.length > 0) {

          for (int i = 0; i < results.length; ++i) {
            DFAgentDescription dfd = results[i];
            AID contactAID = dfd.getName();
            // Do something only if the notification deals with an agent different from the current
            // one
            if (!contactAID.equals(myAgent.getAID())) {

              myLogger.log(
                  Logger.INFO,
                  "Thread "
                      + Thread.currentThread().getId()
                      + ":df says that agent "
                      + myAgent.getAID().getLocalName()
                      + " updates or registers");
              Iterator serviceIter = dfd.getAllServices();

              // Registered or updated
              if (serviceIter.hasNext()) {
                ServiceDescription serviceDesc = (ServiceDescription) serviceIter.next();
                Iterator propertyIt = serviceDesc.getAllProperties();
                Location loc = Helper.extractLocation(propertyIt);
                String phoneNum = contactAID.getLocalName();
                ContactManager.getInstance().addOrUpdateOnlineContact(phoneNum, loc);
              } else {
                myLogger.log(
                    Logger.INFO,
                    "Thread "
                        + Thread.currentThread().getId()
                        + ":df says that agent "
                        + myAgent.getAID().getLocalName()
                        + " deregisters");
                String phoneNumber = contactAID.getLocalName();
                Contact c = ContactManager.getInstance().getContact(phoneNumber);
                ContactManager.getInstance().setContactOffline(phoneNumber);
                MsnEvent event =
                    MsnEventMgr.getInstance().createEvent(MsnEvent.CONTACT_DISCONNECT_EVENT);
                event.addParam(MsnEvent.CONTACT_DISCONNECT_PARAM_CONTACTNAME, c.getName());
                MsnEventMgr.getInstance().fireEvent(event);
              }

              MsnEvent event = MsnEventMgr.getInstance().createEvent(MsnEvent.VIEW_REFRESH_EVENT);
              ContactListChanges changes = ContactManager.getInstance().getModifications();
              Map<String, Contact> cMap = ContactManager.getInstance().getAllContacts();
              Map<String, ContactLocation> cLocMap =
                  ContactManager.getInstance().getAllContactLocations();

              myLogger.log(
                  Logger.FINE,
                  "Thread "
                      + Thread.currentThread().getId()
                      + ":Adding to VIEW_REFRESH_EVENT this list of changes: "
                      + changes.toString());
              event.addParam(MsnEvent.VIEW_REFRESH_PARAM_LISTOFCHANGES, changes);
              event.addParam(MsnEvent.VIEW_REFRESH_CONTACTSMAP, cMap);
              event.addParam(MsnEvent.VIEW_REFRESH_PARAM_LOCATIONMAP, cLocMap);
              MsnEventMgr.getInstance().fireEvent(event);
            }
          }
        }

      } catch (Exception e) {
        myLogger.log(Logger.WARNING, "See printstack for Exception.", e);
        e.printStackTrace();
      }
    }
  @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;
  }