コード例 #1
0
 public double exactSolution(double asset, double time) {
   setup(asset, time);
   return -asset * Math.exp(-dividend * (maturityTime - time)) * SpecialFunctions.normalCdf(-d[0])
       + strike
           * Math.exp(-interestRate * (maturityTime - time))
           * SpecialFunctions.normalCdf(-d[1]);
 }
コード例 #2
0
  private double modelLevyAsian(double S, double K, double r, double div, double sig, double T) {
    double valueLevy = 0.0;
    double se = 0.0;
    double m = 0.0;
    double d = 0.0;
    double sv = 0.0;
    double xStar = 0.0;
    double d1, d2 = 0.0;
    double b = r - div; // cost of carry rate
    double t2 = T; // remaining time to maturity
    double sa = S; // Arithmetic Average price

    se = S / (T * b) * (Math.exp((b - r) * t2) - Math.exp(-r * t2));

    m =
        2
            * Math.pow(S, 2)
            / (b + Math.pow(sig, 2))
            * ((Math.exp((2 * b + Math.pow(sig, 2)) * t2) - 1) / (2 * b + Math.pow(sig, 2))
                - (Math.exp(b * t2) - 1) / b);
    d = m / Math.pow(T, 2);
    sv = Math.log(d) - 2 * (r * t2 + Math.log(se));
    xStar = K - ((T - t2) / T) * sa;
    d1 = 1 / Math.sqrt(sv) * (Math.log(d) / 2 - Math.log(xStar));
    d2 = d1 - Math.sqrt(sv);

    valueLevy = se * CND(d1) - xStar * Math.exp(-r * t2) * CND(d2);
    return valueLevy;
  }
コード例 #3
0
  // loss = add( w[i] * log(1+exp(-y[i]* weightT * x[i])) ) + 0.5 * lbfgs_l2_c * ||weight||2
  @Override
  public void map(AvroKey<lbfgsdata> key, NullWritable nullvalue, Context context) {
    lbfgsdata data = key.datum();

    float w = data.getWeight();
    float offset = data.getOffset();
    int y = data.getResponse();
    List<entry> l = data.getFeatures();

    double decision_value = 0.0;
    for (entry e : l) {
      decision_value += e.getValue() * weight[e.getIndex()];
    }
    decision_value += offset;

    double loss_temp;
    loss_temp = y * decision_value;
    if (loss_temp > 0) {
      loss_temp = Math.log(1 + Math.exp(-loss_temp));
    } else {
      loss_temp = ((-loss_temp) + Math.log(1 + Math.exp(loss_temp)));
    }
    loss += w * loss_temp;

    double gradient_temp = (1 / (1 + Math.exp(-y * decision_value)) - 1) * y * w;
    for (entry e : l) {
      gradient[e.getIndex()] += gradient_temp * e.getValue();
    }
  }
コード例 #4
0
  /**
   * Compute theta price of cash-or-nothing option
   *
   * @param spot The spot
   * @param strike The strike
   * @param timeToExpiry The time to expiry
   * @param lognormalVol The log-normal volatility
   * @param interestRate The interest rate
   * @param costOfCarry The cost-of-carry
   * @param isCall True for calls, false for puts
   * @return The option price
   */
  public static double theta(
      final double spot,
      final double strike,
      final double timeToExpiry,
      final double lognormalVol,
      final double interestRate,
      final double costOfCarry,
      final boolean isCall) {
    ArgumentChecker.isTrue(spot > 0.0, "negative/NaN spot; have {}", spot);
    ArgumentChecker.isTrue(strike > 0.0, "negative/NaN strike; have {}", strike);
    ArgumentChecker.isTrue(timeToExpiry > 0.0, "negative/NaN timeToExpiry; have {}", timeToExpiry);
    ArgumentChecker.isTrue(lognormalVol > 0.0, "negative/NaN lognormalVol; have {}", lognormalVol);
    ArgumentChecker.isFalse(Double.isNaN(interestRate), "interestRate is NaN");
    ArgumentChecker.isFalse(Double.isNaN(costOfCarry), "costOfCarry is NaN");

    final double d =
        (Math.log(spot / strike) + (costOfCarry - 0.5 * lognormalVol * lognormalVol) * timeToExpiry)
            / lognormalVol
            / Math.sqrt(timeToExpiry);
    final double sign = isCall ? 1. : -1.;
    final double div =
        0.5
            * (-Math.log(spot / strike) / Math.pow(timeToExpiry, 1.5)
                + (costOfCarry - 0.5 * lognormalVol * lognormalVol) / Math.pow(timeToExpiry, 0.5))
            / lognormalVol;
    return interestRate * Math.exp(-interestRate * timeToExpiry) * NORMAL.getCDF(sign * d)
        - sign * Math.exp(-interestRate * timeToExpiry) * NORMAL.getPDF(d) * div;
  }
コード例 #5
0
  private void getnegphase() {
    /*
     * It does the negative phase of unsupervised RBM training algorithm
     *
     * For details, please refer to Dr. Hinton's paper:
     * Reducing the dimensionality of data with neural networks. Science, Vol. 313. no. 5786, pp. 504 - 507, 28 July 2006.
     */

    // start calculate the negative phase
    // calculate the curved value of v1,h1
    // find the vector of v1
    Matrix negdata = poshidstates.times(vishid.transpose());
    // (1 * numhid) * (numhid * numdims) = (1 * numdims)
    negdata.plusEquals(visbiases);
    // poshidstates*vishid' + visbiases
    double[][] tmp1 = negdata.getArray();
    int i1 = 0;
    while (i1 < numdims) {
      tmp1[0][i1] = 1 / (1 + Math.exp(-tmp1[0][i1]));
      i1++;
    }

    // find the vector of h1
    neghidprobs = negdata.times(vishid);
    // (1 * numdims) * (numdims * numhid) = (1 * numhid)
    neghidprobs.plusEquals(hidbiases);
    double[][] tmp2 = neghidprobs.getArray();
    int i2 = 0;
    while (i2 < numhid) {
      tmp2[0][i2] = 1 / (1 + Math.exp(-tmp2[0][i2]));
      i2++;
    }
    negprods = negdata.transpose().times(neghidprobs);
    // (numdims * 1) *(1 * numhid) = (numdims * numhid)
  }
コード例 #6
0
    public Double eval(Double gamma) {
      double c = 1.0 / (double) Math.sqrt(variance);
      double sum = 0.0;
      for (Integer i : transcripts.get(gammat)) {
        double pi = 0.0;

        for (int t = 0; t < fiveprime.length; t++) {
          if (transcripts.get(t).contains(i)) {
            double gammai = gammat == t ? gamma : gammas[t][gammak];
            double dit = delta(i, t);

            double pit = gammai * Math.exp(-lambda * dit);
            pi += pit;
          }
        }

        double zi = Math.log(pi);
        double err = data.values(i)[channels[gammak]] - zi;
        double ratio = (Math.exp(-lambda * delta(i, gammat))) / pi;
        double termi = (err * ratio);

        sum += termi;
      }

      return c * sum;
    }
コード例 #7
0
ファイル: GLRMModel.java プロジェクト: vijaykiran/h2o-3
 public final double lgrad(double u, double a, Loss loss) {
   assert loss.isForNumeric() : "Loss function " + loss + " not applicable to numerics";
   switch (loss) {
     case Quadratic:
       return 2 * (u - a);
     case Absolute:
       return Math.signum(u - a);
     case Huber:
       return Math.abs(u - a) <= 1 ? u - a : Math.signum(u - a);
     case Poisson:
       assert a >= 0 : "Poisson loss L(u,a) requires variable a >= 0";
       return Math.exp(u) - a;
     case Hinge:
       // return a*u <= 1 ? -a : 0;
       return a == 0
           ? (-u <= 1 ? 1 : 0)
           : (u <= 1 ? -1 : 0); // Booleans are coded as {0,1} instead of {-1,1}
     case Logistic:
       // return -a/(1+Math.exp(a*u));
       return a == 0
           ? 1 / (1 + Math.exp(-u))
           : -1 / (1 + Math.exp(u)); // Booleans are coded as {0,1} instead of {-1,1}
     case Periodic:
       return ((2 * Math.PI) / _period) * Math.sin((a - u) * (2 * Math.PI) / _period);
     default:
       throw new RuntimeException("Unknown loss function " + loss);
   }
 }
コード例 #8
0
ファイル: IBDReporter.java プロジェクト: benb/beast-mcmc
  public void forwardIBD() {
    int numNodes = treeModel.getNodeCount();
    int stateCount = substitutionModel.getStateCount();
    getDiagonalRates(diag);
    for (int nodeId = 0; nodeId < numNodes; ++nodeId) {
      NodeRef node = treeModel.getNode(nodeId);
      NodeRef parent = treeModel.getParent(node);
      if (parent == null) { // handle the root

      } else if (treeModel.isExternal(node)) { // Handle the tip
        double branchTime =
            branchRateModel.getBranchRate(treeModel, node)
                * (treeModel.getNodeHeight(parent) - treeModel.getNodeHeight(node));

        for (int state = 0; state < stateCount; ++state) {
          ibdForward[nodeId][state] = Math.exp(-diag[state] * branchTime);
        }
      } else { // Handle internal node
        double branchTime =
            branchRateModel.getBranchRate(treeModel, node)
                * (treeModel.getNodeHeight(parent) - treeModel.getNodeHeight(node));

        int childCount = treeModel.getChildCount(node);
        for (int state = 0; state < stateCount; ++state) {
          ibdForward[nodeId][state] = 0;
          for (int child = 0; child < childCount; ++child) {
            int childNodeId = treeModel.getChild(node, child).getNumber();
            ibdForward[nodeId][state] += ibdForward[childNodeId][state];
          }
          ibdForward[nodeId][state] *= Math.exp(-diag[state] * branchTime);
        }
      }
    }
  }
コード例 #9
0
ファイル: GLRMModel.java プロジェクト: vijaykiran/h2o-3
 public final double loss(double u, double a, Loss loss) {
   assert loss.isForNumeric() : "Loss function " + loss + " not applicable to numerics";
   switch (loss) {
     case Quadratic:
       return (u - a) * (u - a);
     case Absolute:
       return Math.abs(u - a);
     case Huber:
       return Math.abs(u - a) <= 1 ? 0.5 * (u - a) * (u - a) : Math.abs(u - a) - 0.5;
     case Poisson:
       assert a >= 0 : "Poisson loss L(u,a) requires variable a >= 0";
       return Math.exp(u)
           + (a == 0 ? 0 : -a * u + a * Math.log(a) - a); // Since \lim_{a->0} a*log(a) = 0
     case Hinge:
       // return Math.max(1-a*u,0);
       return Math.max(1 - (a == 0 ? -u : u), 0); // Booleans are coded {0,1} instead of {-1,1}
     case Logistic:
       // return Math.log(1 + Math.exp(-a * u));
       return Math.log(
           1 + Math.exp(a == 0 ? u : -u)); // Booleans are coded {0,1} instead of {-1,1}
     case Periodic:
       return 1 - Math.cos((a - u) * (2 * Math.PI) / _period);
     default:
       throw new RuntimeException("Unknown loss function " + loss);
   }
 }
コード例 #10
0
  public void printChildTopWords(int k, String childBetaFile) {
    try {
      System.out.println("child beta file");
      PrintWriter childBetaOut = new PrintWriter(new File(childBetaFile));

      for (int i = 0; i < m_childTopicTermProb.length; i++) {
        MyPriorityQueue<_RankItem> fVector = new MyPriorityQueue<_RankItem>(k);
        for (int j = 0; j < vocabulary_size; j++)
          fVector.add(new _RankItem(m_corpus.getFeature(j), m_childTopicTermProb[i][j]));

        childBetaOut.format("Topic %d(%.3f):\t", i, m_childSstat[i]);
        System.out.format("Topic %d(%.3f):\t", i, m_childSstat[i]);
        for (_RankItem it : fVector) {
          childBetaOut.format(
              "%s(%.3f)\t", it.m_name, m_logSpace ? Math.exp(it.m_value) : it.m_value);
          System.out.format(
              "%s(%.3f)\t", it.m_name, m_logSpace ? Math.exp(it.m_value) : it.m_value);
        }
        childBetaOut.println();
        System.out.println();
      }

      childBetaOut.flush();
      childBetaOut.close();
    } catch (Exception ex) {
      System.err.print("File Not Found");
    }
  }
コード例 #11
0
  public void printTopWords(int k, String betaFile) {
    Arrays.fill(m_parentSstat, 0);
    Arrays.fill(m_childSstat, 0);

    System.out.println("print top words");
    for (_Doc d : m_trainSet) {
      if (d instanceof _ParentDoc2) {
        // print out topic assignment of parent
        printParentTopicAssignment((_ParentDoc2) d);
        for (int i = 0; i < number_of_topics; i++)
          m_parentSstat[i] += m_logSpace ? Math.exp(d.m_topics[i]) : d.m_topics[i];
      } else if (d instanceof _ChildDoc2) {
        // print out topic assignment of child
        printChildTopicAssignment((_ChildDoc2) d);
        for (int i = 0; i < number_of_topics; i++)
          m_childSstat[i] += m_logSpace ? Math.exp(d.m_topics[i]) : d.m_topics[i];
      }
    }

    Utils.L1Normalization(m_parentSstat);
    Utils.L1Normalization(m_childSstat);

    String parentBetaFile = betaFile.replace(".txt", "parent.txt");
    String childBetaFile = betaFile.replace(".txt", "child.txt");

    printParentTopWords(k, parentBetaFile);
    printChildTopWords(k, childBetaFile);

    String parentParameterFile = parentBetaFile.replace("beta", "parameter");
    String childParameterFile = childBetaFile.replace("beta", "parameter");
    printParameter(parentParameterFile, childParameterFile);
  }
  @Override
  public PerformanceVector evaluateIndividual(Individual individual) {
    double[] beta = individual.getValues();

    double fitness = 0.0d;
    for (Example example : exampleSet) {
      double eta = 0.0d;
      int i = 0;
      for (Attribute attribute : example.getAttributes()) {
        double value = example.getValue(attribute);
        eta += beta[i] * value;
        i++;
      }
      if (addIntercept) {
        eta += beta[beta.length - 1];
      }
      double pi = Math.exp(eta) / (1 + Math.exp(eta));

      double classValue = example.getValue(label);
      double currentFitness = classValue * Math.log(pi) + (1 - classValue) * Math.log(1 - pi);
      double weightValue = 1.0d;
      if (weight != null) weightValue = example.getValue(weight);
      fitness += weightValue * currentFitness;
    }

    PerformanceVector performanceVector = new PerformanceVector();
    performanceVector.addCriterion(
        new EstimatedPerformance("log_reg_fitness", fitness, exampleSet.size(), false));
    return performanceVector;
  }
コード例 #13
0
ファイル: LDAPrintTopics.java プロジェクト: tdunning/mahout
 private static List<Queue<Pair<String, Double>>> topWordsForTopics(
     String dir, Configuration job, List<String> wordList, int numWordsToPrint) {
   List<Queue<Pair<String, Double>>> queues = Lists.newArrayList();
   Map<Integer, Double> expSums = Maps.newHashMap();
   for (Pair<IntPairWritable, DoubleWritable> record :
       new SequenceFileDirIterable<IntPairWritable, DoubleWritable>(
           new Path(dir, "part-*"), PathType.GLOB, null, null, true, job)) {
     IntPairWritable key = record.getFirst();
     int topic = key.getFirst();
     int word = key.getSecond();
     ensureQueueSize(queues, topic);
     if (word >= 0 && topic >= 0) {
       double score = record.getSecond().get();
       if (expSums.get(topic) == null) {
         expSums.put(topic, 0.0);
       }
       expSums.put(topic, expSums.get(topic) + Math.exp(score));
       String realWord = wordList.get(word);
       maybeEnqueue(queues.get(topic), realWord, score, numWordsToPrint);
     }
   }
   for (int i = 0; i < queues.size(); i++) {
     Queue<Pair<String, Double>> queue = queues.get(i);
     Queue<Pair<String, Double>> newQueue = new PriorityQueue<Pair<String, Double>>(queue.size());
     double norm = expSums.get(i);
     for (Pair<String, Double> pair : queue) {
       newQueue.add(new Pair<String, Double>(pair.getFirst(), Math.exp(pair.getSecond()) / norm));
     }
     queues.set(i, newQueue);
   }
   return queues;
 }
コード例 #14
0
ファイル: Complex.java プロジェクト: RichardMyers/fiji-1
  public Complex tanh() {
    double scalar;
    double temp1Re, temp1Im;
    double temp2Re, temp2Im;
    Complex sinRes, cosRes;
    //  tanh(z)  =  sinh(z) / cosh(z)

    scalar = Math.exp(re);
    temp1Re = scalar * Math.cos(im);
    temp1Im = scalar * Math.sin(im);

    scalar = Math.exp(-re);
    temp2Re = scalar * Math.cos(-im);
    temp2Im = scalar * Math.sin(-im);

    temp1Re -= temp2Re;
    temp1Im -= temp2Im;

    sinRes = new Complex(0.5 * temp1Re, 0.5 * temp1Im);

    scalar = Math.exp(re);
    temp1Re = scalar * Math.cos(im);
    temp1Im = scalar * Math.sin(im);

    scalar = Math.exp(-re);
    temp2Re = scalar * Math.cos(-im);
    temp2Im = scalar * Math.sin(-im);

    temp1Re += temp2Re;
    temp1Im += temp2Im;

    cosRes = new Complex(0.5 * temp1Re, 0.5 * temp1Im);

    return sinRes.div(cosRes);
  }
コード例 #15
0
  private void validateMedian(double rake, double[][] table) {
    String[] columnDescr = TABLE_HEADER_MEDIAN[0].trim().split("\\s+");
    // check for SA
    for (int i = 3; i < columnDescr.length - 1; i++) {
      for (int j = 0; j < table.length; j++) {
        int iper = i - 2;
        double mag = table[j][0];
        double rJB = table[j][1];
        double expectedMedian = table[j][i];
        double computedMedian = Math.exp(toro2002SHARE.getMean(iper, mag, rJB, rake));
        computedMedian =
            computedMedian
                / (AdjustFactorsSHARE.AFrock_TORO2002[iper]
                    * toro2002SHARE.computeStyleOfFaultingTerm(iper, rake)[2]);
        assertEquals(expectedMedian, computedMedian, TOLERANCE);
      }
    }
    // check for PGA
    for (int j = 0; j < table.length; j++) {
      double mag = table[j][0];
      double rJB = table[j][1];
      double expectedMedian = table[j][columnDescr.length - 1];
      double computedMedian = Math.exp(toro2002SHARE.getMean(0, mag, rJB, rake));
      computedMedian =
          computedMedian
              / (AdjustFactorsSHARE.AFrock_TORO2002[0]
                  * toro2002SHARE.computeStyleOfFaultingTerm(0, rake)[2]);

      assertEquals(expectedMedian, computedMedian, TOLERANCE);
    }
  }
コード例 #16
0
ファイル: Complex.java プロジェクト: RichardMyers/fiji-1
  /** Returns the sine of this complex number. */
  public Complex sin() {
    double izRe, izIm;
    double temp1Re, temp1Im;
    double temp2Re, temp2Im;
    double scalar;

    //  sin(z)  =  ( exp(i*z) - exp(-i*z) ) / (2*i)
    izRe = -im;
    izIm = re;

    // first exp
    scalar = Math.exp(izRe);
    temp1Re = scalar * Math.cos(izIm);
    temp1Im = scalar * Math.sin(izIm);

    // second exp
    scalar = Math.exp(-izRe);
    temp2Re = scalar * Math.cos(-izIm);
    temp2Im = scalar * Math.sin(-izIm);

    temp1Re -= temp2Re;
    temp1Im -= temp2Im;

    return new Complex(0.5 * temp1Im, -0.5 * temp1Re);
  }
コード例 #17
0
ファイル: Complex.java プロジェクト: RichardMyers/fiji-1
  /** Returns the cosine of this complex number. */
  public Complex cos() {
    double izRe, izIm;
    double temp1Re, temp1Im;
    double temp2Re, temp2Im;
    double scalar;

    //  cos(z)  =  ( exp(i*z) + exp(-i*z) ) / 2
    izRe = -im;
    izIm = re;

    // first exp
    scalar = Math.exp(izRe);
    temp1Re = scalar * Math.cos(izIm);
    temp1Im = scalar * Math.sin(izIm);

    // second exp
    scalar = Math.exp(-izRe);
    temp2Re = scalar * Math.cos(-izIm);
    temp2Im = scalar * Math.sin(-izIm);

    temp1Re += temp2Re;
    temp1Im += temp2Im;

    return new Complex(0.5 * temp1Re, 0.5 * temp1Im);
  }
コード例 #18
0
 /**
  * Return the probability density for a particular point.
  *
  * @param x The point at which the density should be computed.
  * @return The pdf at point x.
  */
 public double density(Double x) {
   if (x < 0) return 0;
   return Math.pow(x / getBeta(), getAlpha() - 1)
       / getBeta()
       * Math.exp(-x / getBeta())
       / Math.exp(Gamma.logGamma(getAlpha()));
 }
コード例 #19
0
ファイル: NeuralNetwork.java プロジェクト: geomois/ciex2
 private ArrayList<Double> forwardProp(Double[] input) {
   for (int i = 0; i < hiddenLNo; i++) {
     for (int j = 0; j < inputSize + 1; j++) {
       if (j == inputSize) {
         hiddenNodes.set(i, hiddenNodes.get(i) + w1[j][i] * bias);
       } else {
         hiddenNodes.set(i, hiddenNodes.get(i) + w1[j][i] * input[j]);
       }
     }
     double temp = (1.0 / (1.0 + Math.exp(-hiddenNodes.get(i))));
     hiddenNodes.set(i, temp);
   }
   for (int i = 0; i < outputLNo; i++) {
     for (int j = 0; j < hiddenLNo + 1; j++) {
       if (j == hiddenNodes.size()) {
         outputNodes.set(i, outputNodes.get(i) + w2[j][i] * bias);
       } else {
         outputNodes.set(i, outputNodes.get(i) + w2[j][i] * hiddenNodes.get(j));
       }
     }
     //			double temp1 = (1.0 / (1.0 + Math.exp(-outputNodes.get(i))));
     outputNodes.set(i, (1.0 / (1.0 + Math.exp(-outputNodes.get(i)))));
   }
   return outputNodes;
 }
コード例 #20
0
  @Test
  public void meanShift() {
    int w = 32;

    CirculantTracker<ImageFloat32> alg =
        new CirculantTracker<ImageFloat32>(1f / 16, 0.2, 1e-2, 0.075, 1.0, w, 255, interp);

    int peakX = 13;
    int peakY = 17;

    alg.getResponse().reshape(w, w);
    for (int i = 0; i < w; i++) {
      double b = Math.exp(-(i - peakY) * (i - peakY) / 3.0);
      for (int j = 0; j < w; j++) {
        double a = Math.exp(-(j - peakX) * (j - peakX) / 3.0);

        alg.getResponse().set(j, i, a * b);
      }
    }

    alg.subpixelPeak(peakX - 2, peakY + 1);

    assertEquals(2, alg.offX, 0.3);
    assertEquals(-1, alg.offY, 0.3);
  }
コード例 #21
0
    public double protectionLeg(IsdaCompliantCreditCurve creditCurve) {

      double ht0 = creditCurve.getRT(_proLegIntPoints[0]);
      double rt0 = _proYieldCurveRT[0];
      double b0 = _proDF[0] * Math.exp(-ht0);

      double pv = 0.0;

      for (int i = 1; i < _nProPoints; ++i) {
        double ht1 = creditCurve.getRT(_proLegIntPoints[i]);
        double rt1 = _proYieldCurveRT[i];
        double b1 = _proDF[i] * Math.exp(-ht1);
        double dht = ht1 - ht0;
        double drt = rt1 - rt0;
        double dhrt = dht + drt;

        // this is equivalent to the ISDA code without explicitly calculating the time step - it
        // also handles the limit
        double dPV;
        if (Math.abs(dhrt) < 1e-5) {
          dPV = dht * b0 * epsilon(-dhrt);
        } else {
          dPV = (b0 - b1) * dht / dhrt;
        }
        pv += dPV;
        ht0 = ht1;
        rt0 = rt1;
        b0 = b1;
      }
      pv *= _lgdDF; // multiply by LGD and adjust to valuation date

      return pv;
    }
コード例 #22
0
  /**
   * Perform the mutation strength strategy vector mutation for Evolution Strategies (Chapter 30) as
   * specified in Algorithm 30.8.
   *
   * @param g the existing genotype in the search space from which a slightly modified copy should
   *     be created
   * @param r the random number generator
   * @return a new genotype
   */
  @Override
  public final double[] mutate(final double[] g, final Random r) {
    final double[] gnew;
    final double t0, t, c, nu;
    int i;
    double x;

    i = g.length;

    c = 1d;

    // set tau0 according to Equation 30.12
    t0 = (c / Math.sqrt(2 * i));

    // set tau according to Equation 30.13
    t = (c / Math.sqrt(2 * Math.sqrt(i)));

    nu = Math.exp(t0 * r.nextGaussian());
    gnew = g.clone();

    // set each gene Definition D4.3 of gnew to ...
    for (; (--i) >= 0; ) {
      do {
        x = gnew[i] * nu * Math.exp(t * r.nextGaussian());
      } while ((x < this.min) || (x > this.max));
      gnew[i] = x;
    }

    return gnew;
  }
コード例 #23
0
ファイル: RandomEngine.java プロジェクト: hanbei/liblda
 public synchronized double nextGamma(double alpha, double beta) {
   double gamma = 0;
   if (alpha <= 0 || beta <= 0) {
     throw new IllegalArgumentException("alpha and beta must be strictly positive.");
   }
   if (alpha < 1) {
     double b, p;
     boolean flag = false;
     b = 1 + alpha * Math.exp(-1);
     while (!flag) {
       p = b * random.nextDouble();
       if (p > 1) {
         gamma = -Math.log((b - p) / alpha);
         if (random.nextDouble() <= Math.pow(gamma, alpha - 1)) flag = true;
       } else {
         gamma = Math.pow(p, 1 / alpha);
         if (random.nextDouble() <= Math.exp(-gamma)) flag = true;
       }
     }
   } else if (alpha == 1) {
     gamma = -Math.log(random.nextDouble());
   } else {
     double y = -Math.log(random.nextDouble());
     while (random.nextDouble() > Math.pow(y * Math.exp(1 - y), alpha - 1))
       y = -Math.log(random.nextDouble());
     gamma = alpha * y;
   }
   return beta * gamma;
 }
コード例 #24
0
  /**
   * Calculate fine fuel moisture: moisture of litter measured in %.
   *
   * @param dryBulbTemperature
   * @param wetBulbTemperature
   * @param herbstate
   * @return double
   */
  private double calculateFineFuelMoisture(
      double dryBulbTemperature, double wetBulbTemperature, HerbState herbstate) {

    double deltaT = dryBulbTemperature - wetBulbTemperature;
    double ffm = 0.; // fine fuel moisture

    if (deltaT <= diffTemperature[0]) {
      ffm = constantsFineFuelMoisture[0][0] * Math.exp(constantsFineFuelMoisture[1][0] * deltaT);
    } else if (deltaT <= diffTemperature[1]) {
      ffm = constantsFineFuelMoisture[0][1] * Math.exp(constantsFineFuelMoisture[1][1] * deltaT);
    } else if (deltaT <= diffTemperature[2]) {
      ffm = constantsFineFuelMoisture[0][2] * Math.exp(constantsFineFuelMoisture[1][2] * deltaT);
    } else {
      ffm = constantsFineFuelMoisture[0][3] * Math.exp(constantsFineFuelMoisture[1][3] * deltaT);
    }

    /** if ffm is smaller than one, set it to one */
    if (ffm < 1.) {
      ffm = 1.;
    }

    /** adjust fine fuel moisture according to herb state */
    if (herbstate == HerbState.TRANSITION) {
      ffm = ffm + 5.;
    } else if (herbstate == HerbState.GREEN) {
      ffm = ffm + 10.;
    }

    return ffm;
  }
コード例 #25
0
  public String classifyWhole(File file) {
    double[] probabilities = new double[genres.length]; // array of initial probabilities.
    int current = 0; // array counter.
    for (MarkovModel mm : mms) // for every MarkovModel in the array.
    {
      probabilities[current] =
          mm.probabilityWhole(file); // get initial probability from the Markov Model.
      ++current;
    }

    double[] realProbabilities = new double[genres.length]; // Array of calculated probabilities.
    int max = 0; // Pointer to maximum probability.
    for (int i = 0; i < genres.length; ++i) // Calculate probability for each genre.
    {
      double sum = 0;
      for (int j = 0; j < genres.length; ++j) // Sum of the probabilities in different genres.
      {
        sum += Math.exp(probabilities[j]);
      }
      realProbabilities[i] = Math.exp(probabilities[i]) / sum; // Calculating final probability.
      if (realProbabilities[i] > realProbabilities[max]) // recalculating max probability.
      {
        max = i;
      }
    }

    for (int i = 0; i < genres.length; ++i) {
      System.out.println(genres[i] + " : " + probabilities[i]);
    }

    return genres[max]; // returning corresponding genre.
  }
コード例 #26
0
  /**
   * Creates an undirected model that corresponds to a Boltzmann machine with the given weights and
   * biases.
   *
   * @param weights
   * @param biases
   * @return An appropriate UndirectedModel.
   */
  public static UndirectedModel createBoltzmannMachine(double[][] weights, double[] biases) {
    if (weights.length != biases.length)
      throw new IllegalArgumentException(
          "Number of weights "
              + weights.length
              + " not equal to number of biases "
              + biases.length);

    int numV = weights.length;
    Variable vars[] = new Variable[numV];
    for (int i = 0; i < numV; i++) vars[i] = new Variable(2);

    UndirectedModel mdl = new UndirectedModel(vars);
    for (int i = 0; i < numV; i++) {
      Factor nodePtl = new TableFactor(vars[i], new double[] {1, Math.exp(biases[i])});
      mdl.addFactor(nodePtl);
      for (int j = i + 1; j < numV; j++) {
        if (weights[i][j] != 0) {
          double[] ptl = new double[] {1, 1, 1, Math.exp(weights[i][j])};
          mdl.addFactor(vars[i], vars[j], ptl);
        }
      }
    }

    return mdl;
  }
コード例 #27
0
  private double modelTurnbullWakemanAsian(
      double S, double K, double r, double div, double sig, double T) {

    // constant
    double b = r - div; // cost of carry rate
    double tau = 0.0; // time to the begining of the average period

    double m1 = 0.0;
    double m2 = 0.0;

    double optionValue = 0.0;
    double x = 0.0;
    m1 = ((Math.exp(b * T) - Math.exp(b * tau)) / (b * (T - tau))) * S;
    m2 =
        Math.pow(S, 2)
                * 2
                * Math.exp((2 * b + Math.pow(sig, 2)) * T)
                / ((b + Math.pow(sig, 2)) * (2 * b + Math.pow(sig, 2)) * Math.pow(T - tau, 2))
            + (Math.pow(S, 2)
                    * 2
                    * Math.exp((2 * b + Math.pow(sig, 2)) * tau)
                    / (b * Math.pow(T - tau, 2)))
                * (1 / (2 * b + Math.pow(sig, 2))
                    - (Math.exp(b * (T - tau))) / (b + Math.pow(sig, 2)));
    System.out.println("M:" + m2);
    double modVol = Math.sqrt((1 / T) * Math.log(m2 / Math.pow(m1, 2))) * 100;

    optionValue = modelBlack76(K, m1, modVol, T, r);
    return optionValue;
  }
コード例 #28
0
 public static double[] getExpData(double[] axis, double scale) {
   double fraction = Math.exp(-axis[0]);
   double[] buffer = new double[axis.length];
   for (int loop = 0; loop < axis.length; loop++) {
     buffer[loop] = scale * Math.exp(-axis[loop]) / fraction;
   }
   return buffer;
 }
コード例 #29
0
  /**
   * Computes x + y without losing precision using ln(x) and ln(y).
   *
   * @param lna Value.
   * @param lnc Value.
   * @return Result.
   */
  public static double LogSum(float lna, float lnc) {
    if (lna == Float.NEGATIVE_INFINITY) return lnc;
    if (lnc == Float.NEGATIVE_INFINITY) return lna;

    if (lna > lnc) return lna + Special.Log1p(Math.exp(lnc - lna));

    return lnc + Special.Log1p(Math.exp(lna - lnc));
  }
コード例 #30
0
 private void process(int op, double value) {
   float c, v1, v2;
   boolean resetMinMax = roiWidth == width && roiHeight == height && !(op == FILL);
   c = (float) value;
   for (int y = roiY; y < (roiY + roiHeight); y++) {
     int i = y * width + roiX;
     for (int x = roiX; x < (roiX + roiWidth); x++) {
       v1 = pixels[i];
       switch (op) {
         case INVERT:
           v2 = max - (v1 - min);
           break;
         case FILL:
           v2 = fillColor;
           break;
         case ADD:
           v2 = v1 + c;
           break;
         case MULT:
           v2 = v1 * c;
           break;
         case GAMMA:
           if (v1 <= 0f) v2 = 0f;
           else v2 = (float) Math.exp(c * Math.log(v1));
           break;
         case LOG:
           if (v1 <= 0f) v2 = 0f;
           else v2 = (float) Math.log(v1);
           break;
         case EXP:
           v2 = (float) Math.exp(v1);
           break;
         case SQR:
           v2 = v1 * v1;
           break;
         case SQRT:
           if (v1 <= 0f) v2 = 0f;
           else v2 = (float) Math.sqrt(v1);
           break;
         case ABS:
           v2 = (float) Math.abs(v1);
           break;
         case MINIMUM:
           if (v1 < value) v2 = (float) value;
           else v2 = v1;
           break;
         case MAXIMUM:
           if (v1 > value) v2 = (float) value;
           else v2 = v1;
           break;
         default:
           v2 = v1;
       }
       pixels[i++] = v2;
     }
   }
   if (resetMinMax) findMinAndMax();
 }