Esempio n. 1
0
 /**
  * Generate a new random number.
  *
  * @exception IllegalActionException If parameter values are incorrect.
  */
 @Override
 protected void _generateRandomNumber() throws IllegalActionException {
   double meanValue = ((DoubleToken) mean.getToken()).doubleValue();
   double standardDeviationValue = ((DoubleToken) standardDeviation.getToken()).doubleValue();
   double rawNum = _random.nextGaussian();
   _current = rawNum * standardDeviationValue + meanValue;
 }
Esempio n. 2
0
 /**
  * Send a random number with a Gaussian distribution to the output. This number is only changed in
  * the prefire() method, so it will remain constant throughout an iteration.
  *
  * @exception IllegalActionException If there is no director.
  */
 @Override
 public void fire() throws IllegalActionException {
   mean.update();
   standardDeviation.update();
   super.fire();
   output.send(0, new DoubleToken(_current));
 }
Esempio n. 3
0
 /**
  * If either the <i>impulse</i> or <i>initialState</i> input is unknown, then return false.
  * Otherwise, return true.
  *
  * @return True If the actor is ready to fire.
  * @throws IllegalActionException If the superclass throws it.
  */
 public boolean prefire() throws IllegalActionException {
   boolean result = super.prefire();
   if ((impulse.getWidth() == 0 || impulse.isKnown(0))
       && (initialState.getPort().getWidth() == 0 || initialState.getPort().isKnown(0))) {
     return result;
   }
   return false;
 }
Esempio n. 4
0
 /**
  * Construct an actor with the given container and name.
  *
  * @param container The container.
  * @param name The name of this actor.
  * @exception IllegalActionException If the actor cannot be contained by the proposed container.
  * @exception NameDuplicationException If the container already has an actor with this name.
  */
 public Gaussian(CompositeEntity container, String name)
     throws NameDuplicationException, IllegalActionException {
   super(container, name);
   output.setTypeEquals(BaseType.DOUBLE);
   mean = new PortParameter(this, "mean", new DoubleToken(0.0));
   mean.setTypeEquals(BaseType.DOUBLE);
   new Parameter(mean.getPort(), "_showName", BooleanToken.TRUE);
   standardDeviation = new PortParameter(this, "standardDeviation");
   standardDeviation.setExpression("1.0");
   standardDeviation.setTypeEquals(BaseType.DOUBLE);
   new Parameter(standardDeviation.getPort(), "_showName", BooleanToken.TRUE);
 }
  /**
   * Initialize particle filter parameters.
   *
   * @exception IllegalActionException
   * @exception NameDuplicationException
   */
  private void _init() throws IllegalActionException, NameDuplicationException {

    StringToken[] stateNames = new StringToken[2];
    stateNames[0] = new StringToken("x");
    stateNames[1] = new StringToken("y");
    stateVariableNames.setToken(new ArrayToken(BaseType.STRING, stateNames));
    stateVariableNames.setVisibility(Settable.EXPERT);

    observerPosition = new PortParameter(this, "observerPosition");
    observerPosition.setExpression("{0.0,0.0}");
    SingletonParameter showName =
        (SingletonParameter) observerPosition.getPort().getAttribute("_showName");
    if (showName == null) {
      showName = new SingletonParameter(observerPosition.getPort(), "_showName");
      showName.setToken("true");
    } else {
      showName.setToken("true");
    }

    // The input port for range measurements.
    z_m = new TypedIOPort(this, "z_m", true, false);
    z_m.setTypeEquals(BaseType.DOUBLE);
    showName = (SingletonParameter) z_m.getAttribute("_showName");
    z_m.setDisplayName("rangeMeasurement");
    if (showName == null) {
      showName = new SingletonParameter(z_m, "_showName");
      showName.setToken("true");
    } else {
      showName.setToken("true");
    }

    // The parameter that contains the measurement expression.
    z = new Parameter(this, "z");
    z.setExpression("sqrt((x-observerPosition(0))^2 + (y-observerPosition(1))^2)");
    z.setVisibility(Settable.EXPERT);

    x_update = new Parameter(this, "x_update");
    x_update.setExpression("x");

    y_update = new Parameter(this, "y_update");
    y_update.setExpression("y");

    measurementCovariance.setExpression("[2.0]");
    prior.setExpression("{random()*200-100,random()*200-100}");

    processNoise.setExpression("multivariateGaussian({0.0,0.0},[3.0,0.0;0.0,3.0])");

    particleCount.setExpression("2000");

    bootstrap.setVisibility(Settable.EXPERT);
    lowVarianceSampler.setVisibility(Settable.EXPERT);
  }
Esempio n. 6
0
  /**
   * Initialize the integrator. Check for the existence of a director and an ODE solver. Set the
   * state to the value given by <i>initialState</i>.
   *
   * @exception IllegalActionException If there is no director, or the director has no ODE solver,
   *     or the initialState parameter does not contain a valid token, or the superclass throws it.
   */
  public void initialize() throws IllegalActionException {
    ContinuousDirector dir = (ContinuousDirector) getDirector();

    if (dir == null) {
      throw new IllegalActionException(this, " no director available");
    }

    ContinuousODESolver solver = dir._getODESolver();

    if (solver == null) {
      throw new IllegalActionException(this, " no ODE solver available");
    }

    super.initialize();
    _lastRound = -1;
    _tentativeState = ((DoubleToken) initialState.getToken()).doubleValue();
    _state = _tentativeState;

    if (_debugging) {
      _debug("Initialize: initial state = " + _tentativeState);
    }

    // The number of auxiliary variables that are used depends on
    // the solver.
    int n = solver.getIntegratorAuxVariableCount();
    if ((_auxVariables == null) || (_auxVariables.length != n)) {
      _auxVariables = new double[n];
    }
  }
Esempio n. 7
0
 /**
  * If the specified attribute is <i>initialState</i>, then reset the state of the integrator to
  * its value.
  *
  * @param attribute The attribute that has changed.
  * @exception IllegalActionException If the new parameter value is not valid.
  */
 public void attributeChanged(Attribute attribute) throws IllegalActionException {
   if (attribute == initialState) {
     _tentativeState = ((DoubleToken) initialState.getToken()).doubleValue();
     _state = _tentativeState;
   } else {
     super.attributeChanged(attribute);
   }
 }
Esempio n. 8
0
  /**
   * Read multiple arrays of XMLTokens from the input and combine them according to the specified
   * template. If the template contains invalid delimiters, then return the template file with the
   * valid ones replaced and the invalid ones unmodified.
   *
   * @exception IllegalActionException If thrown by the parent class, while reading a parameter or
   *     while reading the input.
   */
  @Override
  public void fire() throws IllegalActionException {
    super.fire();
    template.update();
    String outputString = removeHeader(template.getToken());
    String all = "";
    for (int j = 0; j < input.getWidth(); j++) {
      ArrayToken a = (ArrayToken) input.get(j);

      // FIXME: use StringBuffer instead of concatenating a String.
      String allInArray = "";
      int i;
      for (i = 0; i < a.length(); i++) {
        String elemInArray = removeHeader(a.getElement(i));
        if (i == 0) {
          allInArray = allInArray.concat(elemInArray);
        } else {
          allInArray = allInArray.concat('\n' + elemInArray);
        }
        String elemTag = "$input" + Integer.toString(j) + ',' + Integer.toString(i);
        outputString = outputString.replace(elemTag, elemInArray);
      }
      String arrayTag = "$input" + Integer.toString(j) + ",n";
      outputString = outputString.replace(arrayTag, allInArray);
      if (j == 0) {
        all = all.concat(allInArray);
      } else {
        all = all.concat('\n' + allInArray);
      }
    }
    outputString = outputString.replace("$inputn", all);
    String ADDheader = headerParameter.stringValue() + "\n";
    ADDheader = ADDheader.concat(outputString);
    try {
      XMLToken out = new XMLToken(ADDheader);
      output.broadcast(out);
    } catch (Exception e) {
      // FIXME: throw an exception that uses "this" so we
      // know in which actor the error is located
      throw new InternalErrorException(e);
    }
  }
Esempio n. 9
0
 /**
  * Override the base class to compile a regular expression when it is changed.
  *
  * @param attribute The attribute that changed.
  * @exception IllegalActionException If the specified attribute is <i>pattern</i> and the regular
  *     expression fails to compile.
  */
 public void attributeChanged(Attribute attribute) throws IllegalActionException {
   if (attribute == pattern) {
     _patternValue = ((StringToken) pattern.getToken()).stringValue();
     // FIXME: What is the following about???
     if (_patternValue.equals("\\r")) {
       _patternValue = "\r";
     }
     _pattern = null;
   } else {
     super.attributeChanged(attribute);
   }
 }
Esempio n. 10
0
  /**
   * Perform pattern matching and substring replacement, and output the modified string. If no match
   * is found, output the unmodified stringToEdit string.
   *
   * @exception IllegalActionException If there is no director.
   */
  public void fire() throws IllegalActionException {
    super.fire();

    replacement.update();
    stringToEdit.update();
    pattern.update();

    String replacementValue = ((StringToken) replacement.getToken()).stringValue();
    String stringToEditValue = ((StringToken) stringToEdit.getToken()).stringValue();
    boolean replaceAllTokens = ((BooleanToken) replaceAll.getToken()).booleanValue();
    boolean regularExpressionValue = ((BooleanToken) regularExpression.getToken()).booleanValue();

    if (regularExpressionValue) {
      if (_pattern == null) {
        try {
          String patternValue = ((StringToken) pattern.getToken()).stringValue();
          _pattern = Pattern.compile(patternValue);
        } catch (PatternSyntaxException ex) {
          String patternValue = ((StringToken) pattern.getToken()).stringValue();
          throw new IllegalActionException(
              this, ex, "Failed to compile regular expression \"" + patternValue + "\"");
        }
      }
      Matcher match = _pattern.matcher(stringToEditValue);
      String outputString = "";

      // Unfortunately, the String class throws runtime exceptions
      // if something goes wrong, so we have to catch them.
      try {
        if (replaceAllTokens) {
          outputString = match.replaceAll(replacementValue);
        } else {
          outputString = match.replaceFirst(replacementValue);
        }
      } catch (Exception ex) {
        throw new IllegalActionException(this, ex, "String replace failed.");
      }

      output.send(0, new StringToken(outputString));
    } else {
      // No regular expression.
      String outputString;
      if (replaceAllTokens) {
        outputString = stringToEditValue.replaceAll(_patternValue, replacementValue);
      } else {
        outputString = stringToEditValue.replace(_patternValue, replacementValue);
      }
      output.send(0, new StringToken(outputString));
    }
  }
Esempio n. 11
0
  /**
   * Read the control token input, transfer input tokens, and invoke prefire() of the selected
   * refinement.
   *
   * @exception IllegalActionException If there is no director, or if the director's prefire()
   *     method throws it, or if this actor is not opaque.
   */
  public boolean prefire() throws IllegalActionException {
    if (_debugging) {
      _debug("Calling prefire()");
    }

    try {
      _workspace.getReadAccess();
      super.prefire();

      Case container = (Case) getContainer();
      // Read from port parameters, including the control port.
      Iterator portParameters = container.attributeList(PortParameter.class).iterator();
      while (portParameters.hasNext()) {
        PortParameter portParameter = (PortParameter) portParameters.next();
        portParameter.update();
      }

      String controlValue = container.control.getToken().toString();
      ComponentEntity refinement = container.getEntity(controlValue);
      if (!(refinement instanceof Refinement)) {
        refinement = container._default;
      }
      container._current = (Refinement) refinement;

      // Transfer input tokens.
      for (Iterator inputPorts = container.inputPortList().iterator();
          inputPorts.hasNext() && !_stopRequested; ) {
        IOPort port = (IOPort) inputPorts.next();

        if (!(port instanceof ParameterPort)) {
          Receiver[][] insideReceivers = port.deepGetReceivers();
          for (int i = 0; i < port.getWidth(); i++) {
            if (port.hasToken(i)) {
              Token token = port.get(i);
              if ((insideReceivers != null) && (insideReceivers[i] != null)) {
                for (int j = 0; j < insideReceivers[i].length; j++) {
                  if (insideReceivers[i][j].getContainer().getContainer() == refinement) {
                    insideReceivers[i][j].put(token);
                    if (_debugging) {
                      _debug(
                          getFullName(),
                          "transferring input from "
                              + port.getFullName()
                              + " to "
                              + (insideReceivers[i][j]).getContainer().getFullName());
                    }
                  }
                }
              }
            }
          }
        }
      }
      if (_stopRequested) {
        return false;
      }
      return container._current.prefire();
    } finally {
      _workspace.doneReading();
    }
  }
Esempio n. 12
0
  /**
   * Consume at most one array from the input ports and produce the index of the first bin that
   * breaks the threshold.
   *
   * @exception IllegalActionException If there is no director.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    start.update();

    if (array.hasToken(0)) {
      ArrayToken inputArray = (ArrayToken) array.get(0);
      int inputSize = inputArray.length();

      int startValue = ((IntToken) start.getToken()).intValue();

      if ((startValue >= inputSize) || (startValue < 0)) {
        throw new IllegalActionException(this, "start is out of range: " + startValue);
      }

      int increment = -1;

      if (((BooleanToken) forwards.getToken()).booleanValue()) {
        increment = 1;
      }

      double reference = ((DoubleToken) inputArray.getElement(startValue)).doubleValue();

      double thresholdValue = ((DoubleToken) threshold.getToken()).doubleValue();

      String scaleValue = scale.stringValue();

      boolean aboveValue = ((BooleanToken) above.getToken()).booleanValue();

      if (scaleValue.equals("relative amplitude decibels")) {
        if (aboveValue) {
          thresholdValue = reference * Math.pow(10.0, (thresholdValue / 20));
        } else {
          thresholdValue = reference * Math.pow(10.0, (-thresholdValue / 20));
        }
      } else if (scaleValue.equals("relative power decibels")) {
        if (aboveValue) {
          thresholdValue = reference * Math.pow(10.0, (thresholdValue / 10));
        } else {
          thresholdValue = reference * Math.pow(10.0, (-thresholdValue / 10));
        }
      } else if (scaleValue.equals("relative linear")) {
        if (aboveValue) {
          thresholdValue = reference + thresholdValue;
        } else {
          thresholdValue = reference - thresholdValue;
        }
      }

      // Default output if we don't find a crossing.
      int bin = -1;

      for (int i = startValue; (i < inputSize) && (i >= 0); i += increment) {
        double currentValue = ((DoubleToken) inputArray.getElement(i)).doubleValue();

        if (aboveValue) {
          // Searching for values above the threshold.
          if (currentValue > thresholdValue) {
            bin = i;
            break;
          }
        } else {
          // Searching for values below the threshold.
          if (currentValue < thresholdValue) {
            bin = i;
            break;
          }
        }
      }

      output.send(0, new IntToken(bin));
    }
  }
Esempio n. 13
0
  /**
   * If the value at the <i>derivative</i> port is known, and the current step size is bigger than
   * 0, perform an integration. If the <i>impulse</i> port is known and has data, then add the value
   * provided to the state; if the <i>initialState</i> port is known and has data, then reset the
   * state to the provided value. If both <i>impulse</i> and <i>initialState</i> have data, then
   * <i>initialState</i> dominates. If either is unknown, then simply return, leaving the output
   * unknown. Note that the signals provided at these two ports are required to be purely discrete.
   * This is enforced by throwing an exception if the current microstep is zero when they have input
   * data.
   *
   * @exception IllegalActionException If the input is infinite or not a number, or if thrown by the
   *     solver, or if data is present at either <i>impulse</i> or <i>initialState</i> and the step
   *     size is greater than zero.
   */
  public void fire() throws IllegalActionException {
    ContinuousDirector dir = (ContinuousDirector) getDirector();
    double stepSize = dir.getCurrentStepSize();
    int microstep = dir.getIndex();

    if (_debugging) {
      Time currentTime = dir.getModelTime();
      _debug(
          "Fire at time "
              + currentTime
              + " and microstep "
              + microstep
              + " with step size "
              + stepSize);
    }
    // First handle the impulse input.
    if (impulse.getWidth() > 0 && impulse.hasToken(0)) {
      double impulseValue = ((DoubleToken) impulse.get(0)).doubleValue();
      if (_debugging) {
        _debug("-- impulse input received with value " + impulseValue);
      }
      if (impulseValue != 0.0) {
        if (microstep == 0) {
          throw new IllegalActionException(
              this, "Signal at the impulse port is not purely discrete.");
        }
        double currentState = getState() + impulseValue;
        setTentativeState(currentState);
        if (_debugging) {
          _debug("-- Due to impulse input, set state to " + currentState);
        }
      }
    }
    // Next handle the initialState port.
    ParameterPort initialStatePort = initialState.getPort();
    if (initialStatePort.getWidth() > 0 && initialStatePort.hasToken(0)) {
      double initialValue = ((DoubleToken) initialStatePort.get(0)).doubleValue();
      if (_debugging) {
        _debug("-- initialState input received with value " + initialValue);
      }
      if (microstep == 0.0) {
        throw new IllegalActionException(
            this, "Signal at the initialState port is not purely discrete.");
      }
      setTentativeState(initialValue);
      if (_debugging) {
        _debug("-- Due to initialState input, set state to " + initialValue);
      }
    }

    // Produce the current _tentativeState as output, if it
    // has not already been produced.
    if (!state.isKnown()) {
      double tentativeOutput = getTentativeState();
      // If the round has not updated since the last output, then
      // just produce the same output as last time.
      int currentRound = dir._getODESolver()._getRound();
      if (_lastRound == currentRound) {
        tentativeOutput = _lastOutput;
      }

      if (_debugging) {
        _debug("** Sending output " + tentativeOutput);
      }
      _lastOutput = tentativeOutput;
      state.broadcast(new DoubleToken(tentativeOutput));
    }

    // The _tentativeSate is committed only in postfire(),
    // but multiple rounds will occur before postfire() is called.
    // At each round, this fire() method may be called multiple
    // times, and we want to make sure that the integration step
    // only runs once in the step.
    if (derivative.isKnown() && derivative.hasToken(0)) {
      int currentRound = dir._getODESolver()._getRound();
      if (_lastRound < currentRound) {
        // This is the first fire() in a new round
        // where the derivative input is known and present.
        // Update the tentative state. Note that we will
        // have already produced an output, and so we
        // will not read the updated _tentativeState
        // again in subsequent invocations of fire()
        // in this round. So it is safe to update
        // _tentativeState.
        _lastRound = currentRound;
        double currentDerivative = getDerivative();
        if (Double.isNaN(currentDerivative) || Double.isInfinite(currentDerivative)) {
          throw new IllegalActionException(
              this, "The provided derivative input is invalid: " + currentDerivative);
        }
        if (stepSize > 0.0) {
          // The following method changes the tentative state.
          dir._getODESolver().integratorIntegrate(this);
        }
      }
    }
  }