Esempio n. 1
0
  /** Inicialization of the population */
  public void Initialize() {
    int i, j;

    last = (int) ((prob_cruce * long_poblacion) - 0.5);

    Trials = 0;

    if (prob_mutacion < 1.0) {
      Mu_next = (int) (Math.log(Randomize.Rand()) / Math.log(1.0 - prob_mutacion));
      Mu_next++;
    } else {
      Mu_next = 1;
    }

    for (j = 0; j < n_genes; j++) {
      New[0].GeneSel[j] = '1';
    }
    New[0].n_e = 1;

    for (i = 1; i < long_poblacion; i++) {
      for (j = 0; j < n_genes; j++) {
        if (Randomize.RandintClosed(0, 1) == 0) {
          New[i].GeneSel[j] = '0';
        } else {
          New[i].GeneSel[j] = '1';
        }
      }

      New[i].n_e = 1;
    }
  }
  @Override
  public boolean setNodeValue(final int iNodeIndex, final double dblNodeDF) {
    if (!org.drip.quant.common.NumberUtil.IsValid(dblNodeDF)) return false;

    int iNumDate = _adblDate.length;

    if (iNodeIndex > iNumDate) return false;

    if (0 == iNodeIndex) {
      _dblLeftFlatForwardRate =
          -365.25 * java.lang.Math.log(_dblLeftNodeDF = dblNodeDF) / (_adblDate[0] - _dblEpochDate);

      return true;
    }

    if (1 == iNodeIndex)
      return _msr.setLeftNode(_dblLeftNodeDF, _dblLeftNodeDFSlope, dblNodeDF, null);

    if (iNumDate - 1 == iNodeIndex) {
      try {
        _dblRightFlatForwardRate =
            -365.25
                * java.lang.Math.log(_msr.responseValue(_adblDate[iNodeIndex]))
                / (_adblDate[iNodeIndex] - _dblEpochDate);
      } catch (java.lang.Exception e) {
        e.printStackTrace();

        return false;
      }
    }

    return _msr.resetNode(iNodeIndex, dblNodeDF);
  }
Esempio n. 3
0
  /* Operador de Mutacion Uniforme */
  void Mutacion_Uniforme() {
    int posiciones, i, j;
    double m;

    posiciones = n_genes * long_poblacion;

    if (prob_mutacion > 0) {
      while (Mu_next < posiciones) {
        /* we determinate the chromosome and the gene */
        i = Mu_next / n_genes;
        j = Mu_next % n_genes;

        /* we mutate the gene */
        if (New[i].Gene[j] == '0') New[i].Gene[j] = '1';
        else New[i].Gene[j] = '0';

        New[i].n_e = 1;

        /* we calculate the next position */
        if (prob_mutacion < 1) {
          m = Randomize.Rand();
          Mu_next += (int) (Math.log(m) / Math.log(1.0 - prob_mutacion)) + 1;
        } else Mu_next += 1;
      }
    }

    Mu_next -= posiciones;
  }
Esempio n. 4
0
  /**
   * Compute P(O|Theta), the probability of the observation sequence given the model, by forward
   * recursion with scaling.
   *
   * @param O an observation sequence
   * @return P(O|Theta)
   */
  public double evaluate(int[] O) {

    // Forward Recursion with Scaling

    int T = O.length;
    double[] c = allocateVector(T);
    double[] alpha_hat_t = allocateVector(N);
    double[] alpha_hat_t_plus_1 = allocateVector(N);
    double[] temp_alpha = null;
    double log_likelihood = 0;

    for (int t = 0; t < T; t++) {
      if (t == 0) {
        for (int i = 0; i < N; i++) {
          alpha_hat_t[i] = pi[i] * B[i][O[0]];
        }
      } else {
        clearVector(alpha_hat_t_plus_1);
        for (int j = 0; j < N; j++) {
          for (int i = 0; i < N; i++) {
            alpha_hat_t_plus_1[j] += alpha_hat_t[i] * A[i][j] * B[j][O[t]];
          }
        }
        temp_alpha = alpha_hat_t;
        alpha_hat_t = alpha_hat_t_plus_1;
        alpha_hat_t_plus_1 = temp_alpha;
      }
      c[t] = 1.0 / sum(alpha_hat_t);
      timesAssign(alpha_hat_t, c[t]);
      log_likelihood -= Math.log(c[t]);
    }

    return Math.exp(log_likelihood);
  }
 public static List<Double> log(List<Double> data) {
   List<Double> t_list = new ArrayList<Double>(data.size());
   for (double i : data) {
     t_list.add(Math.log(i));
   }
   return t_list;
 }
 public static double logSumOfExponentials(double[] xs) {
   if (xs.length == 1) return xs[0];
   double max = maximum(xs);
   double sum = 0.0;
   for (int i = 0; i < xs.length; ++i)
     if (xs[i] != Double.NEGATIVE_INFINITY) sum += java.lang.Math.exp(xs[i] - max);
   return max + java.lang.Math.log(sum);
 }
  @Override
  public double zero(final double dblDate) throws java.lang.Exception {
    if (!org.drip.quant.common.NumberUtil.IsValid(dblDate))
      throw new java.lang.Exception("NonlinearDiscountFactorDiscountCurve::zero => Invalid Date");

    double dblStartDate = epoch().julian();

    if (dblDate < dblStartDate) return 0.;

    return -365.25 / (dblDate - dblStartDate) * java.lang.Math.log(df(dblDate));
  }
  @Override
  public double forward(final double dblDate1, final double dblDate2) throws java.lang.Exception {
    if (!org.drip.quant.common.NumberUtil.IsValid(dblDate1)
        || !org.drip.quant.common.NumberUtil.IsValid(dblDate2))
      throw new java.lang.Exception(
          "NonlinearDiscountFactorDiscountCurve::forward => Invalid input");

    double dblStartDate = epoch().julian();

    if (dblDate1 < dblStartDate || dblDate2 < dblStartDate) return 0.;

    return 365.25 / (dblDate2 - dblDate1) * java.lang.Math.log(df(dblDate1) / df(dblDate2));
  }
Esempio n. 9
0
 public void calculateEntropy(int pos) {
   for (int i = 0; i < dataSeq.length(); i++) {
     if (i == pos || i == (pos - 1) || (i == (pos + 1))) {
       entropy[i] = 0;
       continue;
     }
     for (int j = 0; j < numY; j++) {
       entropy[i] += -margPr[i][j] * Math.log(margPr[i][j]);
       // if (i==58)
       // System.out.print("marginal "+i+" "+margPr[i][j]+" "+Math.log(margPr[i][j])+" | ");
     }
   }
 }
Esempio n. 10
0
  private double sampleAndComputeLogWeight(VarWithDistrib var, WorldWithBlock curWorld) {
    DependencyModel.Distrib distrib =
        var.getDistrib(new BlockInstantiatingEvalContextImpl(curWorld));
    Util.debug("Instantiating: ", var);
    Type varType = var.getType();
    CondProbDistrib cpd = distrib.getCPD();
    cpd.setParams(distrib.getArgValues());
    Region r = curWorld.getSatisfyingRegion(var);

    double logWeight = Double.NEGATIVE_INFINITY;
    if (r.isEmpty()) return -1;
    Object value = null;
    if (r.isSingleton()) {
      value = r.getOneValue();
      logWeight = java.lang.Math.log(cpd.getProb(value));
    } else {
      do {
        value = cpd.sampleVal();
      } while (!r.contains(value));
      logWeight = java.lang.Math.log(computeCPD(cpd, r));
    }
    curWorld.setValue(var, value);
    return logWeight;
  }
Esempio n. 11
0
 // rate is avg x pkt/sec and 1/exponential = actual packet size
 // @return 1/(time until next event aka actual pkt size)
 private double exponential(double rate) {
   /*
   if(n < 0)
   {
   	return 0;
   }
   return rate*Math.exp(-rate*n);
   */
   Random rand = new Random();
   double U = rand.nextDouble();
   if (U < .00001) {
     U = .00001;
   }
   return -Math.log(U) / rate;
 }
Esempio n. 12
0
  /** Outputs the association rules. */
  public String toString() {

    StringBuffer text = new StringBuffer();

    if (m_allTheRules[0].size() == 0) return "\nNo large itemsets and rules found!\n";
    text.append("\nPredictiveApriori\n===================\n\n");
    text.append("\nBest rules found:\n\n");

    for (int i = 0; i < m_allTheRules[0].size(); i++) {
      text.append(
          Utils.doubleToString((double) i + 1, (int) (Math.log(m_numRules) / Math.log(10) + 1), 0)
              + ". "
              + ((ItemSet) m_allTheRules[0].elementAt(i)).toString(m_instances)
              + " ==> "
              + ((ItemSet) m_allTheRules[1].elementAt(i)).toString(m_instances)
              + "    acc:("
              + Utils.doubleToString(((Double) m_allTheRules[2].elementAt(i)).doubleValue(), 5)
              + ")");

      text.append('\n');
    }

    return text.toString();
  }
Esempio n. 13
0
  /**
   * Calculates a standardized normal distributed value (using the polar method).
   *
   * @return The value
   */
  public double standNormalDistrDouble() {

    double q = Double.MAX_VALUE;
    double u1 = 0;
    double u2;

    while (q >= 1d || q == 0) {
      u1 = randomDouble();
      u2 = randomDouble();

      q = java.lang.Math.pow(u1, 2) + java.lang.Math.pow(u2, 2);
    }

    double p = java.lang.Math.sqrt((-2d * (java.lang.Math.log(q))) / q);
    return u1 * p; // or u2 * p
  }
  /**
   * Create a CreditCurve instance from the input array of survival probabilities
   *
   * @param dblStartDate Start Date
   * @param strName Credit Curve Name
   * @param strCurrency Currency
   * @param adblSurvivalDate Array of dates
   * @param adblSurvivalProbability Array of survival probabilities
   * @param dblRecovery Recovery
   * @return CreditCurve instance
   */
  public static final org.drip.analytics.definition.ExplicitBootCreditCurve FromSurvival(
      final double dblStartDate,
      final java.lang.String strName,
      final java.lang.String strCurrency,
      final double[] adblSurvivalDate,
      final double[] adblSurvivalProbability,
      final double dblRecovery) {
    if (!org.drip.quant.common.NumberUtil.IsValid(dblRecovery)) return null;

    try {
      double dblSurvivalBegin = 1.;
      double dblPeriodBegin = dblStartDate;
      double[] adblHazard = new double[adblSurvivalProbability.length];
      double[] adblRecovery = new double[1];
      double[] adblRecoveryDate = new double[1];
      adblRecovery[0] = dblRecovery;
      adblRecoveryDate[0] = dblStartDate;

      for (int i = 0; i < adblSurvivalProbability.length; ++i) {
        if (!org.drip.quant.common.NumberUtil.IsValid(adblSurvivalProbability[i])
            || adblSurvivalDate[i] <= dblPeriodBegin
            || dblSurvivalBegin <= adblSurvivalProbability[i]) return null;

        adblHazard[i] =
            365.25
                / (adblSurvivalDate[i] - dblPeriodBegin)
                * java.lang.Math.log(dblSurvivalBegin / adblSurvivalProbability[i]);

        dblPeriodBegin = adblSurvivalDate[i];
        dblSurvivalBegin = adblSurvivalProbability[i];
      }

      return new org.drip.state.curve.ForwardHazardCreditCurve(
          dblStartDate,
          org.drip.state.identifier.CreditLabel.Standard(strName),
          strCurrency,
          adblHazard,
          adblSurvivalDate,
          adblRecovery,
          adblRecoveryDate,
          java.lang.Double.NaN);
    } catch (java.lang.Exception e) {
      e.printStackTrace();
    }

    return null;
  }
Esempio n. 15
0
    @Override
    public void reduce(Text key, Iterable<DoublePair> values, Context context)
        throws IOException, InterruptedException {
      // YOUR CODE HERE
      // Add DoublePair values(distance, ocurrences) for the whole corpus
      Double total_distance = new Double(0.0);
      Double total_ocu = new Double(0.0);
      for (DoublePair value : values) {
        total_distance += value.getDouble1();
        total_ocu += value.getDouble2();
      }

      // Calculate occurrence rate
      Double result = new Double(0.0);
      if (total_distance != 0)
        result = ((total_distance * Math.pow(Math.log(total_distance), 3)) / total_ocu) * -1;

      context.write(new DoubleWritable(result), key);
    }
Esempio n. 16
0
  // ---------------------------------------------------------------------------
  private String Calculate1(String oper, String str1) throws Exception {
    double n1 = Values.StringToDouble(str1);
    double val = 0;

    if (oper.equalsIgnoreCase("SEN")) val = java.lang.Math.sin(n1);
    else if (oper.equalsIgnoreCase("COS")) val = java.lang.Math.cos(n1);
    else if (oper.equalsIgnoreCase("TAN")) val = java.lang.Math.tan(n1);
    else if (oper.equalsIgnoreCase("CTG")) val = 1.0 / java.lang.Math.tan(n1);
    else if (oper.equalsIgnoreCase("ASEN")) val = java.lang.Math.asin(n1);
    else if (oper.equalsIgnoreCase("ACOS")) val = java.lang.Math.acos(n1);
    else if (oper.equalsIgnoreCase("ATAN")) val = java.lang.Math.atan(n1);
    else if (oper.equalsIgnoreCase("ACTG")) val = 1.0 / java.lang.Math.atan(n1);
    else if (oper.equalsIgnoreCase("SENH")) val = java.lang.Math.sinh(n1);
    else if (oper.equalsIgnoreCase("COSH")) val = java.lang.Math.cosh(n1);
    else if (oper.equalsIgnoreCase("TANH")) val = java.lang.Math.tanh(n1);
    else if (oper.equalsIgnoreCase("CTGH")) val = 1.0 / java.lang.Math.tanh(n1);
    else if (oper.equalsIgnoreCase("EXP")) val = java.lang.Math.exp(n1);
    // valor absoluto de inteiros s�o inteiros
    else if (oper.equalsIgnoreCase("ABS")) {
      val = java.lang.Math.abs(n1);
      if (Values.IsInteger(str1)) return Values.IntegerToString(val);
    } else if (oper.equalsIgnoreCase("RAIZ")) val = java.lang.Math.sqrt(n1);
    else if (oper.equalsIgnoreCase("LOG")) val = java.lang.Math.log10(n1);
    else if (oper.equalsIgnoreCase("LN")) val = java.lang.Math.log(n1);
    // parte inteira do numeros
    else if (oper.equalsIgnoreCase("INT")) {
      return Values.IntegerToString(n1);
    }
    // parte real
    else if (oper.equalsIgnoreCase("FRAC")) {
      String num = Values.DoubleToString(n1);
      return num.substring(num.indexOf('.') + 1);
    }

    // parte real
    else if (oper.equalsIgnoreCase("ARRED")) {
      double vm = java.lang.Math.ceil(n1);
      if (n1 - vm >= 0.5) return Values.IntegerToString((int) n1 + 1);
      return Values.IntegerToString((int) n1);
    } else throw new Exception("ERRO fun��o Desconhecida 1 [" + oper + "]");
    return Values.DoubleToString(val);
  }
  /**
   * Compute the Karp/Hagerup/Rub Pivot Departure Bounds outlined below:
   *
   * <p>- Karp, R. M. (1988): Probabilistic Analysis of Algorithms, University of California,
   * Berkeley. - Hagerup, T., and C. Rub (1990): A Guided Tour of Chernoff Bounds, Information
   * Processing Letters, 33:305-308.
   *
   * @param dblLevel The Level at which the Bound is sought
   * @return The Karp/Hagerup/Rub Pivot Departure Bounds
   */
  public org.drip.sequence.metrics.PivotedDepartureBounds karpHagerupRubBounds(
      final double dblLevel) {
    if (!org.drip.quant.common.NumberUtil.IsValid(dblLevel) || 1. < dblLevel) return null;

    int iNumEntry = sequence().length;

    double dblPopulationMean =
        org.drip.quant.common.NumberUtil.IsValid(_dblPopulationMean)
            ? _dblPopulationMean
            : empiricalExpectation();

    double dblScaledLevel = dblLevel / dblPopulationMean;

    double dblLowerBound =
        java.lang.Math.exp(-0.5 * dblPopulationMean * iNumEntry * dblScaledLevel * dblScaledLevel);

    if (!org.drip.quant.common.NumberUtil.IsValid(dblLowerBound)) dblLowerBound = 0.;

    double dblUpperBound =
        java.lang.Math.exp(
            -1.
                    * dblPopulationMean
                    * iNumEntry
                    * (1. + dblScaledLevel)
                    * java.lang.Math.log(1. + dblScaledLevel)
                - dblScaledLevel);

    if (!org.drip.quant.common.NumberUtil.IsValid(dblUpperBound)) dblUpperBound = 0.;

    try {
      return new org.drip.sequence.metrics.PivotedDepartureBounds(
          org.drip.sequence.metrics.PivotedDepartureBounds.PIVOT_ANCHOR_TYPE_MEAN,
          java.lang.Double.NaN,
          dblLowerBound > 1. ? 1. : dblLowerBound,
          dblUpperBound > 1. ? 1. : dblUpperBound);
    } catch (java.lang.Exception e) {
      e.printStackTrace();
    }

    return null;
  }
Esempio n. 18
0
 /* Returns the natural logarithm (base e) of a value
  */
 public static SchemaTypeNumber log(SchemaTypeNumber value) {
   switch (value.numericType()) {
     case SchemaTypeNumber.NUMERIC_VALUE_INT:
       return new SchemaInt((int) java.lang.Math.log(value.doubleValue()));
     case SchemaTypeNumber.NUMERIC_VALUE_LONG:
       return new SchemaLong((long) java.lang.Math.log(value.doubleValue()));
     case SchemaTypeNumber.NUMERIC_VALUE_BIGINTEGER:
       return new SchemaInteger(
           (long) java.lang.Math.log(value.doubleValue())); // note: possible loss of precision
     case SchemaTypeNumber.NUMERIC_VALUE_FLOAT:
       return new SchemaFloat((float) java.lang.Math.log(value.doubleValue()));
     case SchemaTypeNumber.NUMERIC_VALUE_DOUBLE:
       return new SchemaDouble(java.lang.Math.log(value.doubleValue()));
   }
   return new SchemaDecimal(java.lang.Math.log(value.doubleValue()));
 }
Esempio n. 19
0
 private LogMath(final double base) {
   this.base = base;
   this.log_of_base = Math.log(base);
 }
Esempio n. 20
0
 /**
  * @param prob the probability of success for the geometric distribution.
  * @return a random number generated from the geometric distribution.
  */
 private static long randomGeometricDist(double prob) {
   assert (prob > 0.0 && prob < 1.0);
   return (long) (Math.log(Math.random()) / Math.log(1.0 - prob));
 }
Esempio n. 21
0
 public static double log2(final double theValue) {
   return java.lang.Math.log(theValue) / java.lang.Math.log(2);
 }
Esempio n. 22
0
  private Object interpretFunction(Functions function, Sprite sprite) {
    Object left = null;
    Object right = null;

    Double doubleValueOfLeftChild = null;
    Double doubleValueOfRightChild = null;

    if (leftChild != null) {
      left = leftChild.interpretRecursive(sprite);
      if (left instanceof String) {
        try {
          doubleValueOfLeftChild = Double.valueOf((String) left);
        } catch (NumberFormatException numberFormatException) {
          Log.d(getClass().getSimpleName(), "Couldn't parse String", numberFormatException);
        }
      } else {
        doubleValueOfLeftChild = (Double) left;
      }
    }

    if (rightChild != null) {
      right = rightChild.interpretRecursive(sprite);
      if (right instanceof String) {
        try {
          doubleValueOfRightChild = Double.valueOf((String) right);
        } catch (NumberFormatException numberFormatException) {
          Log.d(getClass().getSimpleName(), "Couldn't parse String", numberFormatException);
        }
      } else {
        doubleValueOfRightChild = (Double) right;
      }
    }

    switch (function) {
      case SIN:
        return doubleValueOfLeftChild == null
            ? 0d
            : java.lang.Math.sin(Math.toRadians(doubleValueOfLeftChild));
      case COS:
        return doubleValueOfLeftChild == null
            ? 0d
            : java.lang.Math.cos(Math.toRadians(doubleValueOfLeftChild));
      case TAN:
        return doubleValueOfLeftChild == null
            ? 0d
            : java.lang.Math.tan(Math.toRadians(doubleValueOfLeftChild));
      case LN:
        return doubleValueOfLeftChild == null ? 0d : java.lang.Math.log(doubleValueOfLeftChild);
      case LOG:
        return doubleValueOfLeftChild == null ? 0d : java.lang.Math.log10(doubleValueOfLeftChild);
      case SQRT:
        return doubleValueOfLeftChild == null ? 0d : java.lang.Math.sqrt(doubleValueOfLeftChild);
      case RAND:
        return (doubleValueOfLeftChild == null || doubleValueOfRightChild == null)
            ? 0d
            : interpretFunctionRand(doubleValueOfLeftChild, doubleValueOfRightChild);
      case ABS:
        return doubleValueOfLeftChild == null ? 0d : java.lang.Math.abs(doubleValueOfLeftChild);
      case ROUND:
        return doubleValueOfLeftChild == null
            ? 0d
            : (double) java.lang.Math.round(doubleValueOfLeftChild);
      case PI:
        return java.lang.Math.PI;
      case MOD:
        return (doubleValueOfLeftChild == null || doubleValueOfRightChild == null)
            ? 0d
            : interpretFunctionMod(doubleValueOfLeftChild, doubleValueOfRightChild);
      case ARCSIN:
        return doubleValueOfLeftChild == null
            ? 0d
            : java.lang.Math.toDegrees(Math.asin(doubleValueOfLeftChild));
      case ARCCOS:
        return doubleValueOfLeftChild == null
            ? 0d
            : java.lang.Math.toDegrees(Math.acos(doubleValueOfLeftChild));
      case ARCTAN:
        return doubleValueOfLeftChild == null
            ? 0d
            : java.lang.Math.toDegrees(Math.atan(doubleValueOfLeftChild));
      case EXP:
        return doubleValueOfLeftChild == null ? 0d : java.lang.Math.exp(doubleValueOfLeftChild);
      case POWER:
        return (doubleValueOfLeftChild == null || doubleValueOfRightChild == null)
            ? 0d
            : java.lang.Math.pow(doubleValueOfLeftChild, doubleValueOfRightChild);
      case FLOOR:
        return doubleValueOfLeftChild == null ? 0d : java.lang.Math.floor(doubleValueOfLeftChild);
      case CEIL:
        return doubleValueOfLeftChild == null ? 0d : java.lang.Math.ceil(doubleValueOfLeftChild);
      case MAX:
        return (doubleValueOfLeftChild == null || doubleValueOfRightChild == null)
            ? 0d
            : java.lang.Math.max(doubleValueOfLeftChild, doubleValueOfRightChild);
      case MIN:
        return (doubleValueOfLeftChild == null || doubleValueOfRightChild == null)
            ? 0d
            : java.lang.Math.min(doubleValueOfLeftChild, doubleValueOfRightChild);
      case TRUE:
        return 1d;
      case FALSE:
        return 0d;
      case LETTER:
        return interpretFunctionLetter(right, left);
      case LENGTH:
        return interpretFunctionLength(left, sprite);
      case JOIN:
        return interpretFunctionJoin(sprite);
      case ARDUINODIGITAL:
        Arduino arduinoDigital =
            ServiceProvider.getService(CatroidService.BLUETOOTH_DEVICE_SERVICE)
                .getDevice(BluetoothDevice.ARDUINO);
        if (arduinoDigital != null && left != null) {
          if (doubleValueOfLeftChild < 0 || doubleValueOfLeftChild > 13) {
            return 0d;
          }
          return arduinoDigital.getDigitalArduinoPin(doubleValueOfLeftChild.intValue());
        }
        break;
      case ARDUINOANALOG:
        Arduino arduinoAnalog =
            ServiceProvider.getService(CatroidService.BLUETOOTH_DEVICE_SERVICE)
                .getDevice(BluetoothDevice.ARDUINO);
        if (arduinoAnalog != null && left != null) {
          if (doubleValueOfLeftChild < 0 || doubleValueOfLeftChild > 5) {
            return 0d;
          }
          return arduinoAnalog.getAnalogArduinoPin(doubleValueOfLeftChild.intValue());
        }
        break;
      case RASPIDIGITAL:
        RPiSocketConnection connection = RaspberryPiService.getInstance().connection;
        int pin = doubleValueOfLeftChild.intValue();
        try {
          return connection.getPin(pin) ? 1d : 0d;
        } catch (Exception e) {
          Log.e(getClass().getSimpleName(), "RPi: exception during getPin: " + e);
        }
        break;
      case MULTI_FINGER_TOUCHED:
        return TouchUtil.isFingerTouching(doubleValueOfLeftChild.intValue()) ? 1d : 0d;
      case MULTI_FINGER_X:
        return Double.valueOf(TouchUtil.getX(doubleValueOfLeftChild.intValue()));
      case MULTI_FINGER_Y:
        return Double.valueOf(TouchUtil.getY(doubleValueOfLeftChild.intValue()));
      case LIST_ITEM:
        return interpretFunctionListItem(left, sprite);
      case CONTAINS:
        return interpretFunctionContains(right, sprite);
      case NUMBER_OF_ITEMS:
        return interpretFunctionNumberOfItems(left, sprite);
    }
    return 0d;
  }
Esempio n. 23
0
  /**
   * Returns the logarithm of a for base 2.
   *
   * @param a a double
   */
  public static double log2(double a) {

    return Math.log(a) / log2;
  }
Esempio n. 24
0
/** Class implementing some simple utility methods. */
public final class M5StaticUtils {

  /** The natural logarithm of 2. */
  public static double log2 = Math.log(2);

  /** The small deviation allowed in double comparisons */
  public static double SMALL = 1e-6;

  /**
   * Reads properties that inherit from three locations. Properties are first defined in the system
   * resource location (i.e. in the CLASSPATH). These default properties must exist. Properties
   * defined in the users home directory (optional) override default settings. Properties defined in
   * the current directory (optional) override all these settings.
   *
   * @param resourceName the location of the resource that should be loaded.
   * @return the Properties
   * @exception Exception if no default properties are defined, or if an error occurs reading the
   *     properties files.
   */
  public static Properties readProperties(String resourceName) throws Exception {

    Properties defaultProps = new Properties();
    try {
      // Apparently hardcoded slashes are OK here
      // jdk1.1/docs/guide/misc/resources.html
      defaultProps.load(ClassLoader.getSystemResourceAsStream(resourceName));
    } catch (Exception ex) {
      /*      throw new Exception("Problem reading default properties: "
      + ex.getMessage()); */
      System.err.println(
          "Warning, unable to load properties file from " + "system resource (M5StaticUtils.java)");
    }

    // Hardcoded slash is OK here
    // eg: see jdk1.1/docs/guide/misc/resources.html
    int slInd = resourceName.lastIndexOf('/');
    if (slInd != -1) {
      resourceName = resourceName.substring(slInd + 1);
    }

    // Allow a properties file in the home directory to override
    Properties userProps = new Properties(defaultProps);
    File propFile =
        new File(
            System.getProperties().getProperty("user.home") + File.separatorChar + resourceName);
    if (propFile.exists()) {
      try {
        userProps.load(new FileInputStream(propFile));
      } catch (Exception ex) {
        throw new Exception("Problem reading user properties: " + propFile);
      }
    }

    // Allow a properties file in the current directory to override
    Properties localProps = new Properties(userProps);
    propFile = new File(resourceName);
    if (propFile.exists()) {
      try {
        localProps.load(new FileInputStream(propFile));
      } catch (Exception ex) {
        throw new Exception("Problem reading local properties: " + propFile);
      }
    }

    return localProps;
  }

  /**
   * Returns the correlation coefficient of two double vectors.
   *
   * @param y1 double vector 1
   * @param y2 double vector 2
   * @param n the length of two double vectors
   * @return the correlation coefficient
   */
  public static final double correlation(double y1[], double y2[], int n) {

    int i;
    double av1 = 0.0, av2 = 0.0, y11 = 0.0, y22 = 0.0, y12 = 0.0, c;

    if (n <= 1) {
      return 1.0;
    }
    for (i = 0; i < n; i++) {
      av1 += y1[i];
      av2 += y2[i];
    }
    av1 /= (double) n;
    av2 /= (double) n;
    for (i = 0; i < n; i++) {
      y11 += (y1[i] - av1) * (y1[i] - av1);
      y22 += (y2[i] - av2) * (y2[i] - av2);
      y12 += (y1[i] - av1) * (y2[i] - av2);
    }
    if (y11 * y22 == 0.0) {
      c = 1.0;
    } else {
      c = y12 / Math.sqrt(Math.abs(y11 * y22));
    }

    return c;
  }

  /**
   * Removes all occurrences of a string from another string.
   *
   * @param inString the string to remove substrings from.
   * @param substring the substring to remove.
   * @return the input string with occurrences of substring removed.
   */
  public static String removeSubstring(String inString, String substring) {

    StringBuffer result = new StringBuffer();
    int oldLoc = 0, loc = 0;
    while ((loc = inString.indexOf(substring, oldLoc)) != -1) {
      result.append(inString.substring(oldLoc, loc));
      oldLoc = loc + substring.length();
    }
    result.append(inString.substring(oldLoc));
    return result.toString();
  }

  /**
   * Replaces with a new string, all occurrences of a string from another string.
   *
   * @param inString the string to replace substrings in.
   * @param substring the substring to replace.
   * @param replaceString the replacement substring
   * @return the input string with occurrences of substring replaced.
   */
  public static String replaceSubstring(String inString, String subString, String replaceString) {

    StringBuffer result = new StringBuffer();
    int oldLoc = 0, loc = 0;
    while ((loc = inString.indexOf(subString, oldLoc)) != -1) {
      result.append(inString.substring(oldLoc, loc));
      result.append(replaceString);
      oldLoc = loc + subString.length();
    }
    result.append(inString.substring(oldLoc));
    return result.toString();
  }

  /**
   * Pads a string to a specified length, inserting spaces on the left as required. If the string is
   * too long, characters are removed (from the right).
   *
   * @param inString the input string
   * @param length the desired length of the output string
   * @return the output string
   */
  public static String padLeft(String inString, int length) {

    return fixStringLength(inString, length, false);
  }

  /**
   * Pads a string to a specified length, inserting spaces on the right as required. If the string
   * is too long, characters are removed (from the right).
   *
   * @param inString the input string
   * @param length the desired length of the output string
   * @return the output string
   */
  public static String padRight(String inString, int length) {

    return fixStringLength(inString, length, true);
  }

  /**
   * Pads a string to a specified length, inserting spaces as required. If the string is too long,
   * characters are removed (from the right).
   *
   * @param inString the input string
   * @param length the desired length of the output string
   * @param right true if inserted spaces should be added to the right
   * @return the output string
   */
  private static String fixStringLength(String inString, int length, boolean right) {

    if (inString.length() < length) {
      while (inString.length() < length) {
        inString = (right ? inString.concat(" ") : " ".concat(inString));
      }
    } else if (inString.length() > length) {
      inString = inString.substring(0, length);
    }
    return inString;
  }

  /**
   * Rounds a double and converts it into String.
   *
   * @param value the double value
   * @param afterDecimalPoint the (maximum) number of digits permitted after the decimal point
   * @return the double as a formatted string
   */
  public static String doubleToString(double value, int afterDecimalPoint) {

    StringBuffer stringBuffer;
    double temp;
    int i, dotPosition;
    long precisionValue;

    temp = value * Math.pow(10.0, afterDecimalPoint);
    if (Math.abs(temp) < Long.MAX_VALUE) {
      precisionValue = (temp > 0) ? (long) (temp + 0.5) : -(long) (Math.abs(temp) + 0.5);
      if (precisionValue == 0) {
        stringBuffer = new StringBuffer(String.valueOf(0));
      } else {
        stringBuffer = new StringBuffer(String.valueOf(precisionValue));
      }
      if (afterDecimalPoint == 0) {
        return stringBuffer.toString();
      }
      dotPosition = stringBuffer.length() - afterDecimalPoint;
      while (((precisionValue < 0) && (dotPosition < 1)) || (dotPosition < 0)) {
        if (precisionValue < 0) {
          stringBuffer.insert(1, 0);
        } else {
          stringBuffer.insert(0, 0);
        }
        dotPosition++;
      }
      stringBuffer.insert(dotPosition, '.');
      if ((precisionValue < 0) && (stringBuffer.charAt(1) == '.')) {
        stringBuffer.insert(1, 0);
      } else if (stringBuffer.charAt(0) == '.') {
        stringBuffer.insert(0, 0);
      }
      int currentPos = stringBuffer.length() - 1;
      while ((currentPos > dotPosition) && (stringBuffer.charAt(currentPos) == '0')) {
        stringBuffer.setCharAt(currentPos--, ' ');
      }
      if (stringBuffer.charAt(currentPos) == '.') {
        stringBuffer.setCharAt(currentPos, ' ');
      }

      return stringBuffer.toString().trim();
    }
    return new String("" + value);
  }

  /**
   * Rounds a double and converts it into a formatted decimal-justified String. Trailing 0's are
   * replaced with spaces.
   *
   * @param value the double value
   * @param width the width of the string
   * @param afterDecimalPoint the number of digits after the decimal point
   * @return the double as a formatted string
   */
  public static String doubleToString(double value, int width, int afterDecimalPoint) {

    String tempString = doubleToString(value, afterDecimalPoint);
    char[] result;
    int dotPosition;

    if ((afterDecimalPoint >= width) || (tempString.indexOf('E') != -1)) { // Protects sci notation
      return tempString;
    }

    // Initialize result
    result = new char[width];
    for (int i = 0; i < result.length; i++) {
      result[i] = ' ';
    }

    if (afterDecimalPoint > 0) {
      // Get position of decimal point and insert decimal point
      dotPosition = tempString.indexOf('.');
      if (dotPosition == -1) {
        dotPosition = tempString.length();
      } else {
        result[width - afterDecimalPoint - 1] = '.';
      }
    } else {
      dotPosition = tempString.length();
    }

    int offset = width - afterDecimalPoint - dotPosition;
    if (afterDecimalPoint > 0) {
      offset--;
    }

    // Not enough room to decimal align within the supplied width
    if (offset < 0) {
      return tempString;
    }

    // Copy characters before decimal point
    for (int i = 0; i < dotPosition; i++) {
      result[offset + i] = tempString.charAt(i);
    }

    // Copy characters after decimal point
    for (int i = dotPosition + 1; i < tempString.length(); i++) {
      result[offset + i] = tempString.charAt(i);
    }

    return new String(result);
  }

  /**
   * Tests if a is equal to b.
   *
   * @param a a double
   * @param b a double
   */
  public static boolean eq(double a, double b) {

    return (a - b < SMALL) && (b - a < SMALL);
  }

  /**
   * Checks if the given array contains any non-empty options.
   *
   * @param strings an array of strings
   * @exception Exception if there are any non-empty options
   */
  public static void checkForRemainingOptions(String[] options) throws Exception {

    int illegalOptionsFound = 0;
    StringBuffer text = new StringBuffer();

    if (options == null) {
      return;
    }
    for (int i = 0; i < options.length; i++) {
      if (options[i].length() > 0) {
        illegalOptionsFound++;
        text.append(options[i] + ' ');
      }
    }
    if (illegalOptionsFound > 0) {
      throw new Exception("Illegal options: " + text);
    }
  }

  /**
   * Checks if the given array contains the flag "-Char". Stops searching at the first marker "--".
   * If the flag is found, it is replaced with the empty string.
   *
   * @param flag the character indicating the flag.
   * @param strings the array of strings containing all the options.
   * @return true if the flag was found
   * @exception Exception if an illegal option was found
   */
  public static boolean getFlag(char flag, String[] options) throws Exception {

    if (options == null) {
      return false;
    }
    for (int i = 0; i < options.length; i++) {
      if ((options[i].length() > 1) && (options[i].charAt(0) == '-')) {
        try {
          Double dummy = Double.valueOf(options[i]);
        } catch (NumberFormatException e) {
          if (options[i].length() > 2) {
            throw new Exception("Illegal option: " + options[i]);
          }
          if (options[i].charAt(1) == flag) {
            options[i] = "";
            return true;
          }
          if (options[i].charAt(1) == '-') {
            return false;
          }
        }
      }
    }
    return false;
  }

  /**
   * Gets an option indicated by a flag "-Char" from the given array of strings. Stops searching at
   * the first marker "--". Replaces flag and option with empty strings.
   *
   * @param flag the character indicating the option.
   * @param options the array of strings containing all the options.
   * @return the indicated option or an empty string
   * @exception Exception if the option indicated by the flag can't be found
   */
  public static String getOption(char flag, String[] options) throws Exception {

    String newString;

    if (options == null) {
      return "";
    }
    for (int i = 0; i < options.length; i++) {
      if ((options[i].length() > 0) && (options[i].charAt(0) == '-')) {

        // Check if it is a negative number
        try {
          Double dummy = Double.valueOf(options[i]);
        } catch (NumberFormatException e) {
          if (options[i].length() > 2) {
            throw new Exception("Illegal option: " + options[i]);
          }
          if (options[i].charAt(1) == flag) {
            if (i + 1 == options.length) {
              throw new Exception("No value given for -" + flag + " option.");
            }
            options[i] = "";
            newString = new String(options[i + 1]);
            options[i + 1] = "";
            return newString;
          }
          if (options[i].charAt(1) == '-') {
            return "";
          }
        }
      }
    }
    return "";
  }

  /**
   * Quotes a string if it contains special characters.
   *
   * <p>The following rules are applied:
   *
   * <p>A character is backquoted version of it is one of <tt>" ' % \ \n \r \t</tt>.
   *
   * <p>A string is enclosed within single quotes if a character has been backquoted using the
   * previous rule above or contains <tt>{ }</tt> or is exactly equal to the strings <tt>, ? space
   * or ""</tt> (empty string).
   *
   * <p>A quoted question mark distinguishes it from the missing value which is represented as an
   * unquoted question mark.
   *
   * @param string the string to be quoted
   * @return the string (possibly quoted)
   */
  public static String quote(String string) {
    boolean quote = false;

    // backquote the following characters
    if ((string.indexOf('\n') != -1)
        || (string.indexOf('\r') != -1)
        || (string.indexOf('\'') != -1)
        || (string.indexOf('"') != -1)
        || (string.indexOf('\\') != -1)
        || (string.indexOf('\t') != -1)
        || (string.indexOf('%') != -1)) {
      string = backQuoteChars(string);
      quote = true;
    }

    // Enclose the string in 's if the string contains a recently added
    // backquote or contains one of the following characters.
    if ((quote == true)
        || (string.indexOf('{') != -1)
        || (string.indexOf('}') != -1)
        || (string.indexOf(',') != -1)
        || (string.equals("?"))
        || (string.indexOf(' ') != -1)
        || (string.equals(""))) {
      string = ("'".concat(string)).concat("'");
    }

    return string;
  }

  /**
   * Converts carriage returns and new lines in a string into \r and \n. Backquotes the following
   * characters: ` " \ \t and %
   *
   * @param string the string
   * @return the converted string
   */
  public static String backQuoteChars(String string) {

    int index;
    StringBuffer newStringBuffer;

    // replace each of the following characters with the backquoted version
    char charsFind[] = {'\\', '\'', '\t', '"', '%'};
    String charsReplace[] = {"\\\\", "\\'", "\\t", "\\\"", "\\%"};
    for (int i = 0; i < charsFind.length; i++) {
      if (string.indexOf(charsFind[i]) != -1) {
        newStringBuffer = new StringBuffer();
        while ((index = string.indexOf(charsFind[i])) != -1) {
          if (index > 0) {
            newStringBuffer.append(string.substring(0, index));
          }
          newStringBuffer.append(charsReplace[i]);
          if ((index + 1) < string.length()) {
            string = string.substring(index + 1);
          } else {
            string = "";
          }
        }
        newStringBuffer.append(string);
        string = newStringBuffer.toString();
      }
    }

    return M5StaticUtils.convertNewLines(string);
  }

  /**
   * Converts carriage returns and new lines in a string into \r and \n.
   *
   * @param string the string
   * @return the converted string
   */
  public static String convertNewLines(String string) {

    int index;

    // Replace with \n
    StringBuffer newStringBuffer = new StringBuffer();
    while ((index = string.indexOf('\n')) != -1) {
      if (index > 0) {
        newStringBuffer.append(string.substring(0, index));
      }
      newStringBuffer.append('\\');
      newStringBuffer.append('n');
      if ((index + 1) < string.length()) {
        string = string.substring(index + 1);
      } else {
        string = "";
      }
    }
    newStringBuffer.append(string);
    string = newStringBuffer.toString();

    // Replace with \r
    newStringBuffer = new StringBuffer();
    while ((index = string.indexOf('\r')) != -1) {
      if (index > 0) {
        newStringBuffer.append(string.substring(0, index));
      }
      newStringBuffer.append('\\');
      newStringBuffer.append('r');
      if ((index + 1) < string.length()) {
        string = string.substring(index + 1);
      } else {
        string = "";
      }
    }
    newStringBuffer.append(string);
    return newStringBuffer.toString();
  }

  /**
   * Returns the secondary set of options (if any) contained in the supplied options array. The
   * secondary set is defined to be any options after the first "--". These options are removed from
   * the original options array.
   *
   * @param options the input array of options
   * @return the array of secondary options
   */
  public static String[] partitionOptions(String[] options) {

    for (int i = 0; i < options.length; i++) {
      if (options[i].equals("--")) {
        options[i++] = "";
        String[] result = new String[options.length - i];
        for (int j = i; j < options.length; j++) {
          result[j - i] = options[j];
          options[j] = "";
        }
        return result;
      }
    }
    return new String[0];
  }

  /**
   * Split up a string containing options into an array of strings, one for each option.
   *
   * @param optionString the string containing the options
   * @return the array of options
   */
  public static String[] splitOptions(String optionString) {

    Vector optionsVec = new Vector();
    StringTokenizer st = new StringTokenizer(optionString);
    while (st.hasMoreTokens()) {
      optionsVec.addElement(st.nextToken());
    }

    String[] options = new String[optionsVec.size()];
    for (int i = 0; i < optionsVec.size(); i++) {
      options[i] = (String) optionsVec.elementAt(i);
    }
    return options;
  }

  /**
   * Joins all the options in an option array into a single string, as might be used on the command
   * line.
   *
   * @param optionArray the array of options
   * @return the string containing all options.
   */
  public static String joinOptions(String[] optionArray) {

    String optionString = "";
    for (int i = 0; i < optionArray.length; i++) {
      if (optionArray[i].equals("")) {
        continue;
      }
      if (optionArray[i].indexOf(' ') != -1) {
        optionString += '"' + optionArray[i] + '"';
      } else {
        optionString += optionArray[i];
      }
      optionString += " ";
    }
    return optionString.trim();
  }

  /**
   * Creates a new instance of an object given it's class name and (optional) arguments to pass to
   * it's setOptions method. If the object implements OptionHandler and the options parameter is
   * non-null, the object will have it's options set. Example use:
   *
   * <p><code> <pre>
   * String classifierName = M5StaticUtils.getOption('W', options);
   * Classifier c = (Classifier)M5StaticUtils.forName(Classifier.class,
   *                                          classifierName,
   *                                          options);
   * setClassifier(c);
   * </pre></code>
   *
   * @param classType the class that the instantiated object should be assignable to -- an exception
   *     is thrown if this is not the case
   * @param className the fully qualified class name of the object
   * @param options an array of options suitable for passing to setOptions. May be null. Any options
   *     accepted by the object will be removed from the array.
   * @return the newly created object, ready for use.
   * @exception Exception if the class name is invalid, or if the class is not assignable to the
   *     desired class type, or the options supplied are not acceptable to the object
   */
  public static Object forName(Class classType, String className, String[] options)
      throws Exception {

    Class c = null;
    try {
      c = Class.forName(className);
    } catch (Exception ex) {
      throw new Exception("Can't find class called: " + className);
    }
    if (!classType.isAssignableFrom(c)) {
      throw new Exception(classType.getName() + " is not assignable from " + className);
    }
    Object o = c.newInstance();
    if ((o instanceof M5) && (options != null)) {
      ((M5) o).setOptions(options);
      M5StaticUtils.checkForRemainingOptions(options);
    }
    return o;
  }

  /**
   * Computes entropy for an array of integers.
   *
   * @param counts array of counts
   * @returns - a log2 a - b log2 b - c log2 c + (a+b+c) log2 (a+b+c) when given array [a b c]
   */
  public static double info(int counts[]) {

    int total = 0;
    int c;
    double x = 0;
    for (int j = 0; j < counts.length; j++) {
      x -= xlogx(counts[j]);
      total += counts[j];
    }
    return x + xlogx(total);
  }

  /**
   * Tests if a is smaller or equal to b.
   *
   * @param a a double
   * @param b a double
   */
  public static boolean smOrEq(double a, double b) {

    return (a - b < SMALL);
  }

  /**
   * Tests if a is greater or equal to b.
   *
   * @param a a double
   * @param b a double
   */
  public static boolean grOrEq(double a, double b) {

    return (b - a < SMALL);
  }

  /**
   * Tests if a is smaller than b.
   *
   * @param a a double
   * @param b a double
   */
  public static boolean sm(double a, double b) {

    return (b - a > SMALL);
  }

  /**
   * Tests if a is smaller than b.
   *
   * @param a a double
   * @param b a double
   */
  public static boolean gr(double a, double b) {

    return (a - b > SMALL);
  }

  /**
   * Returns the logarithm of a for base 2.
   *
   * @param a a double
   */
  public static double log2(double a) {

    return Math.log(a) / log2;
  }

  /**
   * Returns index of maximum element in a given array of doubles. First maximum is returned.
   *
   * @param doubles the array of doubles
   * @return the index of the maximum element
   */
  public static int maxIndex(double[] doubles) {

    double maximum = 0;
    int maxIndex = 0;

    for (int i = 0; i < doubles.length; i++) {
      if ((i == 0) || (doubles[i] > maximum)) {
        maxIndex = i;
        maximum = doubles[i];
      }
    }

    return maxIndex;
  }

  /**
   * Returns index of maximum element in a given array of integers. First maximum is returned.
   *
   * @param ints the array of integers
   * @return the index of the maximum element
   */
  public static int maxIndex(int[] ints) {

    int maximum = 0;
    int maxIndex = 0;

    for (int i = 0; i < ints.length; i++) {
      if ((i == 0) || (ints[i] > maximum)) {
        maxIndex = i;
        maximum = ints[i];
      }
    }

    return maxIndex;
  }

  /**
   * Computes the mean for an array of doubles.
   *
   * @param vector the array
   * @return the mean
   */
  public static double mean(double[] vector) {

    double sum = 0;

    if (vector.length == 0) {
      return 0;
    }
    for (int i = 0; i < vector.length; i++) {
      sum += vector[i];
    }
    return sum / (double) vector.length;
  }

  /**
   * Returns index of minimum element in a given array of integers. First minimum is returned.
   *
   * @param ints the array of integers
   * @return the index of the minimum element
   */
  public static int minIndex(int[] ints) {

    int minimum = 0;
    int minIndex = 0;

    for (int i = 0; i < ints.length; i++) {
      if ((i == 0) || (ints[i] < minimum)) {
        minIndex = i;
        minimum = ints[i];
      }
    }

    return minIndex;
  }

  /**
   * Returns index of minimum element in a given array of doubles. First minimum is returned.
   *
   * @param doubles the array of doubles
   * @return the index of the minimum element
   */
  public static int minIndex(double[] doubles) {

    double minimum = 0;
    int minIndex = 0;

    for (int i = 0; i < doubles.length; i++) {
      if ((i == 0) || (doubles[i] < minimum)) {
        minIndex = i;
        minimum = doubles[i];
      }
    }

    return minIndex;
  }

  /**
   * Normalizes the doubles in the array by their sum.
   *
   * @param doubles the array of double
   * @exception IllegalArgumentException if sum is Zero or NaN
   */
  public static void normalize(double[] doubles) {

    double sum = 0;
    for (int i = 0; i < doubles.length; i++) {
      sum += doubles[i];
    }
    normalize(doubles, sum);
  }

  /**
   * Normalizes the doubles in the array using the given value.
   *
   * @param doubles the array of double
   * @param sum the value by which the doubles are to be normalized
   * @exception IllegalArgumentException if sum is zero or NaN
   */
  public static void normalize(double[] doubles, double sum) {

    if (Double.isNaN(sum)) {
      throw new IllegalArgumentException("Can't normalize array. Sum is NaN.");
    }
    if (sum == 0) {
      // Maybe this should just be a return.
      throw new IllegalArgumentException("Can't normalize array. Sum is zero.");
    }
    for (int i = 0; i < doubles.length; i++) {
      doubles[i] /= sum;
    }
  }

  /**
   * Rounds a double to the next nearest integer value. The JDK version of it doesn't work properly.
   *
   * @param value the double value
   * @return the resulting integer value
   */
  public static int round(double value) {

    int roundedValue = value > 0 ? (int) (value + 0.5) : -(int) (Math.abs(value) + 0.5);

    return roundedValue;
  }

  /**
   * Rounds a double to the given number of decimal places.
   *
   * @param value the double value
   * @param afterDecimalPoint the number of digits after the decimal point
   * @return the double rounded to the given precision
   */
  public static double roundDouble(double value, int afterDecimalPoint) {

    double mask = Math.pow(10.0, (double) afterDecimalPoint);

    return (double) (Math.round(value * mask)) / mask;
  }

  /**
   * Sorts a given array of integers in ascending order and returns an array of integers with the
   * positions of the elements of the original array in the sorted array. The sort is stable. (Equal
   * elements remain in their original order.)
   *
   * @param array this array is not changed by the method!
   * @return an array of integers with the positions in the sorted array.
   */
  public static int[] sort(int[] array) {

    int[] index = new int[array.length];
    int[] newIndex = new int[array.length];
    int[] helpIndex;
    int numEqual;

    for (int i = 0; i < index.length; i++) {
      index[i] = i;
    }
    quickSort(array, index, 0, array.length - 1);

    // Make sort stable
    int i = 0;
    while (i < index.length) {
      numEqual = 1;
      for (int j = i + 1; ((j < index.length) && (array[index[i]] == array[index[j]])); j++) {
        numEqual++;
      }
      if (numEqual > 1) {
        helpIndex = new int[numEqual];
        for (int j = 0; j < numEqual; j++) {
          helpIndex[j] = i + j;
        }
        quickSort(index, helpIndex, 0, numEqual - 1);
        for (int j = 0; j < numEqual; j++) {
          newIndex[i + j] = index[helpIndex[j]];
        }
        i += numEqual;
      } else {
        newIndex[i] = index[i];
        i++;
      }
    }
    return newIndex;
  }

  /**
   * Sorts a given array of doubles in ascending order and returns an array of integers with the
   * positions of the elements of the original array in the sorted array. NOTE THESE CHANGES: the
   * sort is no longer stable and it doesn't use safe floating-point comparisons anymore.
   * Occurrences of Double.NaN are treated as Double.MAX_VALUE
   *
   * @param array this array is not changed by the method!
   * @return an array of integers with the positions in the sorted array.
   */
  public static int[] sort(double[] array) {

    int[] index = new int[array.length];
    array = (double[]) array.clone();
    for (int i = 0; i < index.length; i++) {
      index[i] = i;
      if (Double.isNaN(array[i])) {
        array[i] = Double.MAX_VALUE;
      }
    }
    quickSort(array, index, 0, array.length - 1);
    return index;
  }

  /**
   * Sorts a given array of doubles in ascending order and returns an array of integers with the
   * positions of the elements of the original array in the sorted array. The sort is stable (Equal
   * elements remain in their original order.) Occurrences of Double.NaN are treated as
   * Double.MAX_VALUE
   *
   * @param array this array is not changed by the method!
   * @return an array of integers with the positions in the sorted array.
   */
  public static int[] stableSort(double[] array) {

    int[] index = new int[array.length];
    int[] newIndex = new int[array.length];
    int[] helpIndex;
    int numEqual;

    array = (double[]) array.clone();
    for (int i = 0; i < index.length; i++) {
      index[i] = i;
      if (Double.isNaN(array[i])) {
        array[i] = Double.MAX_VALUE;
      }
    }
    quickSort(array, index, 0, array.length - 1);

    // Make sort stable

    int i = 0;
    while (i < index.length) {
      numEqual = 1;
      for (int j = i + 1;
          ((j < index.length) && M5StaticUtils.eq(array[index[i]], array[index[j]]));
          j++) {
        numEqual++;
      }
      if (numEqual > 1) {
        helpIndex = new int[numEqual];
        for (int j = 0; j < numEqual; j++) {
          helpIndex[j] = i + j;
        }
        quickSort(index, helpIndex, 0, numEqual - 1);
        for (int j = 0; j < numEqual; j++) {
          newIndex[i + j] = index[helpIndex[j]];
        }
        i += numEqual;
      } else {
        newIndex[i] = index[i];
        i++;
      }
    }

    return newIndex;
  }

  /**
   * Computes the variance for an array of doubles.
   *
   * @param vector the array
   * @return the variance
   */
  public static double variance(double[] vector) {

    double sum = 0, sumSquared = 0;

    if (vector.length <= 1) {
      return 0;
    }
    for (int i = 0; i < vector.length; i++) {
      sum += vector[i];
      sumSquared += (vector[i] * vector[i]);
    }
    return (sumSquared - (sum * sum / (double) vector.length)) / (double) (vector.length - 1);
  }

  /**
   * Computes the sum of the elements of an array of doubles.
   *
   * @param doubles the array of double
   * @returns the sum of the elements
   */
  public static double sum(double[] doubles) {

    double sum = 0;

    for (int i = 0; i < doubles.length; i++) {
      sum += doubles[i];
    }
    return sum;
  }

  /**
   * Computes the sum of the elements of an array of integers.
   *
   * @param ints the array of integers
   * @returns the sum of the elements
   */
  public static int sum(int[] ints) {

    int sum = 0;

    for (int i = 0; i < ints.length; i++) {
      sum += ints[i];
    }
    return sum;
  }

  /**
   * Returns c*log2(c) for a given integer value c.
   *
   * @param c an integer value
   * @returns c*log2(c) (but is careful to return 0 if c is 0)
   */
  public static double xlogx(int c) {

    if (c == 0) {
      return 0.0;
    }
    return c * M5StaticUtils.log2((double) c);
  }

  /**
   * Implements quicksort for an array of indices.
   *
   * @param array the array of integers to be sorted
   * @param index the index which should contain the positions in the sorted array
   * @param lo0 the first index of the subset to be sorted
   * @param hi0 the last index of the subset to be sorted
   */
  private static void quickSort(int[] array, int[] index, int lo0, int hi0) {

    int lo = lo0;
    int hi = hi0;
    int mid;
    int help;

    if (hi0 > lo0) {

      // Arbitrarily establishing partition element as the midpoint of
      // the array.
      mid = array[index[(lo0 + hi0) / 2]];

      // loop through the array until indices cross
      while (lo <= hi) {

        // find the first element that is greater than or equal to
        // the partition element starting from the left Index.
        while ((array[index[lo]] < mid) && (lo < hi0)) {
          ++lo;
        }

        // find an element that is smaller than or equal to
        // the partition element starting from the right Index.
        while ((array[index[hi]] > mid) && (hi > lo0)) {
          --hi;
        }

        // if the indexes have not crossed, swap
        if (lo <= hi) {
          help = index[lo];
          index[lo] = index[hi];
          index[hi] = help;
          ++lo;
          --hi;
        }
      }

      // If the right index has not reached the left side of array
      // must now sort the left partition.
      if (lo0 < hi) {
        quickSort(array, index, lo0, hi);
      }

      // If the left index has not reached the right side of array
      // must now sort the right partition.
      if (lo < hi0) {
        quickSort(array, index, lo, hi0);
      }
    }
  }

  /**
   * Implements unsafe quicksort for an array of indices.
   *
   * @param array the array of doubles to be sorted
   * @param index the index which should contain the positions in the sorted array
   * @param lo0 the first index of the subset to be sorted
   * @param hi0 the last index of the subset to be sorted
   */
  private static void quickSort(double[] array, int[] index, int lo0, int hi0) {

    int lo = lo0;
    int hi = hi0;
    double mid;
    int help;

    if (hi0 > lo0) {

      // Arbitrarily establishing partition element as the midpoint of
      // the array.
      mid = array[index[(lo0 + hi0) / 2]];

      // loop through the array until indices cross
      while (lo <= hi) {

        // find the first element that is greater than or equal to
        // the partition element starting from the left Index.
        while ((array[index[lo]] < mid) && (lo < hi0)) {
          ++lo;
        }

        // find an element that is smaller than or equal to
        // the partition element starting from the right Index.
        while ((array[index[hi]] > mid) && (hi > lo0)) {
          --hi;
        }

        // if the indexes have not crossed, swap
        if (lo <= hi) {
          help = index[lo];
          index[lo] = index[hi];
          index[hi] = help;
          ++lo;
          --hi;
        }
      }

      // If the right index has not reached the left side of array
      // must now sort the left partition.
      if (lo0 < hi) {
        quickSort(array, index, lo0, hi);
      }

      // If the left index has not reached the right side of array
      // must now sort the right partition.
      if (lo < hi0) {
        quickSort(array, index, lo, hi0);
      }
    }
  }

  /**
   * Main method for testing this class.
   *
   * @param ops some dummy options
   */
  public static void main(String[] ops) {

    double[] doubles = {4.5, 6.7, Double.NaN, 3.4, 4.8, 1.2, 3.4};
    int[] ints = {12, 6, 2, 18, 16, 6, 7, 5};

    try {

      // Option handling
      System.out.println("First option split up:");
      if (ops.length > 0) {
        String[] firstOptionSplitUp = M5StaticUtils.splitOptions(ops[0]);
        for (int i = 0; i < firstOptionSplitUp.length; i++) {
          System.out.println(firstOptionSplitUp[i]);
        }
      }
      System.out.println("Partitioned options: ");
      String[] partitionedOptions = M5StaticUtils.partitionOptions(ops);
      for (int i = 0; i < partitionedOptions.length; i++) {
        System.out.println(partitionedOptions[i]);
      }
      System.out.println("Get flag -f: " + M5StaticUtils.getFlag('f', ops));
      System.out.println("Get option -o: " + M5StaticUtils.getOption('o', ops));
      System.out.println("Checking for remaining options... ");
      M5StaticUtils.checkForRemainingOptions(ops);

      // Statistics
      System.out.println("Original array (doubles): ");
      for (int i = 0; i < doubles.length; i++) {
        System.out.print(doubles[i] + " ");
      }
      System.out.println();
      System.out.println("Original array (ints): ");
      for (int i = 0; i < ints.length; i++) {
        System.out.print(ints[i] + " ");
      }
      System.out.println();
      System.out.println(
          "Correlation: " + M5StaticUtils.correlation(doubles, doubles, doubles.length));
      System.out.println("Mean: " + M5StaticUtils.mean(doubles));
      System.out.println("Variance: " + M5StaticUtils.variance(doubles));
      System.out.println("Sum (doubles): " + M5StaticUtils.sum(doubles));
      System.out.println("Sum (ints): " + M5StaticUtils.sum(ints));
      System.out.println("Max index (doubles): " + M5StaticUtils.maxIndex(doubles));
      System.out.println("Max index (ints): " + M5StaticUtils.maxIndex(ints));
      System.out.println("Min index (doubles): " + M5StaticUtils.minIndex(doubles));
      System.out.println("Min index (ints): " + M5StaticUtils.minIndex(ints));

      // Sorting and normalizing
      System.out.println("Sorted array (doubles): ");
      int[] sorted = M5StaticUtils.sort(doubles);
      for (int i = 0; i < doubles.length; i++) {
        System.out.print(doubles[sorted[i]] + " ");
      }
      System.out.println();
      System.out.println("Normalized array (doubles): ");
      M5StaticUtils.normalize(doubles);
      for (int i = 0; i < doubles.length; i++) {
        System.out.print(doubles[i] + " ");
      }
      System.out.println();
      System.out.println("Normalized again (doubles): ");
      M5StaticUtils.normalize(doubles, M5StaticUtils.sum(doubles));
      for (int i = 0; i < doubles.length; i++) {
        System.out.print(doubles[i] + " ");
      }
      System.out.println();

      // Pretty-printing
      System.out.println("-4.58: " + M5StaticUtils.doubleToString(-4.57826535, 2));
      System.out.println("-6.78: " + M5StaticUtils.doubleToString(-6.78214234, 6, 2));

      // Comparisons
      System.out.println("5.70001 == 5.7 ? " + M5StaticUtils.eq(5.70001, 5.7));
      System.out.println("5.70001 > 5.7 ? " + M5StaticUtils.gr(5.70001, 5.7));
      System.out.println("5.70001 >= 5.7 ? " + M5StaticUtils.grOrEq(5.70001, 5.7));
      System.out.println("5.7 < 5.70001 ? " + M5StaticUtils.sm(5.7, 5.70001));
      System.out.println("5.7 <= 5.70001 ? " + M5StaticUtils.smOrEq(5.7, 5.70001));

      // Math
      System.out.println("Info (ints): " + M5StaticUtils.info(ints));
      System.out.println("log2(4.6): " + M5StaticUtils.log2(4.6));
      System.out.println("5 * log(5): " + M5StaticUtils.xlogx(5));
      System.out.println("5.5 rounded: " + M5StaticUtils.round(5.5));
      System.out.println(
          "5.55555 rounded to 2 decimal places: " + M5StaticUtils.roundDouble(5.55555, 2));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Esempio n. 25
0
 public void calculateEntropy() {
   for (int i = 0; i < dataSeq.length(); i++) {
     for (int j = 0; j < numY; j++) entropy[i] += -margPr[i][j] * Math.log(margPr[i][j]);
   }
 }
  private static final Map<String, ForwardCurve> xM6MBasisSample(
      final JulianDate dtSpot,
      final String strCurrency,
      final DiscountCurve dc,
      final int iTenorInMonths,
      final String[] astrxM6MFwdTenor,
      final double[] adblxM6MBasisSwapQuote)
      throws Exception {
    System.out.println("------------------------------------------------------------");

    System.out.println(" SPL =>              n=4               |         |         |");

    System.out.println("---------------------------------------|  LOG DF |  LIBOR  |");

    System.out.println(" MSR =>  RECALC  |  REFEREN |  DERIVED |         |         |");

    System.out.println("------------------------------------------------------------");

    /*
     * Construct the 6M-xM float-float basis swap.
     */

    FloatFloatComponent[] aFFC =
        MakexM6MBasisSwap(dtSpot, strCurrency, astrxM6MFwdTenor, iTenorInMonths);

    String strBasisTenor = iTenorInMonths + "M";

    ValuationParams valParams = new ValuationParams(dtSpot, dtSpot, strCurrency);

    /*
     * Calculate the starting forward rate off of the discount curve.
     */

    double dblStartingFwd = dc.forward(dtSpot.julian(), dtSpot.addTenor(strBasisTenor).julian());

    /*
     * Set the discount curve based component market parameters.
     */

    CurveSurfaceQuoteSet mktParams =
        MarketParamsBuilder.Create(dc, null, null, null, null, null, null);

    Map<String, ForwardCurve> mapForward = new HashMap<String, ForwardCurve>();

    /*
     * Construct the shape preserving forward curve off of Quartic Polynomial Basis Spline.
     */

    ForwardCurve fcxMQuartic =
        ScenarioForwardCurveBuilder.ShapePreservingForwardCurve(
            "QUARTIC_FWD" + strBasisTenor,
            ForwardLabel.Create(strCurrency, strBasisTenor),
            valParams,
            null,
            mktParams,
            null,
            MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
            new PolynomialFunctionSetParams(5),
            aFFC,
            "ReferenceParBasisSpread",
            adblxM6MBasisSwapQuote,
            dblStartingFwd);

    mapForward.put(" QUARTIC_FWD" + strBasisTenor, fcxMQuartic);

    /*
     * Set the discount curve + quartic polynomial forward curve based component market parameters.
     */

    CurveSurfaceQuoteSet mktParamsQuarticFwd =
        MarketParamsBuilder.Create(dc, fcxMQuartic, null, null, null, null, null, null);

    int i = 0;
    int iFreq = 12 / iTenorInMonths;

    /*
     * Compute the following forward curve metrics for each of cubic polynomial forward, quartic
     * 	polynomial forward, and KLK Hyperbolic tension forward curves:
     * 	- Reference Basis Par Spread
     * 	- Derived Basis Par Spread
     *
     * Further compare these with a) the forward rate off of the discount curve, b) the LIBOR rate, and
     * 	c) Input Basis Swap Quote.
     */

    for (String strMaturityTenor : astrxM6MFwdTenor) {
      double dblFwdEndDate = dtSpot.addTenor(strMaturityTenor).julian();

      double dblFwdStartDate =
          dtSpot.addTenor(strMaturityTenor).subtractTenor(strBasisTenor).julian();

      FloatFloatComponent ffc = aFFC[i++];

      CaseInsensitiveTreeMap<Double> mapQuarticValue =
          ffc.value(valParams, null, mktParamsQuarticFwd, null);

      System.out.println(
          " "
              + strMaturityTenor
              + " =>  "
              + FormatUtil.FormatDouble(fcxMQuartic.forward(strMaturityTenor), 2, 2, 100.)
              + "  |  "
              + FormatUtil.FormatDouble(mapQuarticValue.get("ReferenceParBasisSpread"), 2, 2, 1.)
              + "  |  "
              + FormatUtil.FormatDouble(mapQuarticValue.get("DerivedParBasisSpread"), 2, 2, 1.)
              + "  |  "
              + FormatUtil.FormatDouble(
                  iFreq * java.lang.Math.log(dc.df(dblFwdStartDate) / dc.df(dblFwdEndDate)),
                  1,
                  2,
                  100.)
              + "  |  "
              + FormatUtil.FormatDouble(dc.libor(dblFwdStartDate, dblFwdEndDate), 1, 2, 100.)
              + "  |  ");
    }

    return mapForward;
  }
Esempio n. 27
0
  public RevSPIHT(int[][] srcimg, int imgsize) {
    // input parameters
    Imagesize = imgsize;
    size = 8;

    OriginImage = new int[Imagesize][Imagesize];
    DeImage = new int[Imagesize][Imagesize];
    int[][] tmp = new int[size][size];
    int[][] tmp1 = new int[size / 2][size / 2];
    int[][] tmp2 = new int[size / 4][size / 4];
    IdxTable = new int[Imagesize][Imagesize];

    // read images
    DeImage = srcimg;
    int incTemp = Imagesize / size;
    int p = 0, q = 0;
    System.out.println("Iterations:" + incTemp);
    // block division & SPIHT transformation
    for (int i = 0; i < incTemp; i++) {
      System.out.println("\nStart i:" + i + " @" + new java.util.Date());
      for (int j = 0; j < incTemp; j++) {
        System.out.print(j + ",");
        // max coefficient
        N = (int) (Math.log(DeImage[i * size][j * size]) / Math.log(2));
        // threshold
        T0 = (int) (Math.pow(2, N));

        // SPIHT for each block
        for (int m = 0; m < size * size; m++)
          tmp[m / size][m % size] =
              DeImage[i * size + ((int) m / size)][j * size + ((int) m % size)];

        R = (int) ((DeImage[i * size][j * size] + T0 + 0.5) / 2);
        R1 = (int) ((DeImage[i * size][j * size] + R + 0.5) / 2);
        R2 = (int) ((R + T0 + 0.5) / 2);

        // 1st SPIHT_transform transformation for each block
        finally_encoded += SPIHT_transform(tmp);

        // 再精煉的估測值
        R11 = (int) ((DeImage[i * size][j * size] + R1 + 0.5) / 2);
        R12 = (int) ((R1 + R + 0.5) / 2);
        R21 = (int) ((R2 + R + 0.5) / 2);
        R22 = (int) ((R2 + T0 + 0.5) / 2);

        // 1st精煉
        for (int m = 0; m < size * size; m++) {
          int tempvalue = DeImage[i * size + ((int) m / size)][j * size + ((int) m % size)];
          // 1st 精練
          if (Math.abs(tempvalue) >= R) {
            if (tempvalue >= 0)
              DeImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = R1;
            else DeImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = -R1;
            finally_encoded += "1";
          } else if (((Math.abs(tempvalue) < R)) && ((Math.abs(tempvalue) >= T0))) {
            if (tempvalue >= 0)
              DeImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = R2;
            else DeImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = -R2;
            finally_encoded += "0";
          }

          // 再精練
          if (Math.abs(tempvalue) >= R) {
            if (Math.abs(tempvalue) >= R1) {
              if (tempvalue >= 0) {
                OriginImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = R11;
                DeImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = tempvalue - R11;
              } else {
                OriginImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = -R11;
                DeImage[i * size + ((int) m / size)][j * size + ((int) m % size)] =
                    -(Math.abs(tempvalue) - R11);
              }
              finally_encoded += "1";
            } else {
              if (tempvalue >= 0) {
                OriginImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = R12;
                DeImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = tempvalue - R12;
              } else {
                OriginImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = -R12;
                DeImage[i * size + ((int) m / size)][j * size + ((int) m % size)] =
                    -(Math.abs(tempvalue) - R12);
              }
              finally_encoded += "0";
            }

          } else if (((Math.abs(tempvalue) < R)) && ((Math.abs(tempvalue) >= T0))) {
            if (Math.abs(tempvalue) >= R2) {
              if (tempvalue >= 0) {
                OriginImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = R21;
                DeImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = tempvalue - R21;
              } else {
                OriginImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = -R21;
                DeImage[i * size + ((int) m / size)][j * size + ((int) m % size)] =
                    -(Math.abs(tempvalue) - R21);
              }
              finally_encoded += "1";
            } else {
              if (tempvalue >= 0) {
                OriginImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = R12;
                DeImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = tempvalue - R12;
              } else {
                OriginImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = -R12;
                DeImage[i * size + ((int) m / size)][j * size + ((int) m % size)] =
                    -(Math.abs(tempvalue) - R12);
              }
              finally_encoded += "0";
            }
          } else {
            OriginImage[i * size + ((int) m / size)][j * size + ((int) m % size)] = 0;
          }
        } // for m

        // 2nd
        // N=N/2;
        // T0 = T0/2;
        // SPIHT for each block
        // for (int m=0;m<size*size;m++)
        //    tmp[m/size][m%size] = DeImage[i*size+((int)m/size)][j*size+((int)m%size)];
        // finally_encoded+=SPIHT_transform(tmp);

        // copy to DeImage
        // for (int m=0;m<size*size;m++)
        //    IdxTable[i*size+((int)m/size)][j*size+((int)m%size)] = tmpR [m/size][m%size];

      }
    }

    System.out.println("Successfully finish SPIHT compression!");
    //	System.out.println("The results are shown in file:"+"decoded-"+ls_filename+".raw");

  }
Esempio n. 28
0
 @Override
 public double getLogValue(final double nonLogValue) {
   return Math.log(nonLogValue);
 }
Esempio n. 29
0
 public Complex log() {
   float phase = arg();
   if (phase > Math.PI) phase -= 2.0f * Math.PI;
   return Complex.polar((float) Math.log(abs()), phase);
 }
Esempio n. 30
0
 /** Returns the log-representation of the provided decimal value. */
 public double getLogValue(final double nonLogValue) {
   return Math.log(nonLogValue) / log_of_base;
 }