List of usage examples for java.lang Math exp
@HotSpotIntrinsicCandidate public static double exp(double a)
From source file:com.itemanalysis.psychometrics.irt.model.Irm3PL.java
/** * Comute the probability of a correct response. This method uses a combination of stored * parameters and those passed in the iparam array. This arrangement allows for fixing * some item parameters during estimation. For example, instantiating this object as a 2PL * and setting the stored value of the guessing parameter will result in a 3PL with a fixed * guessing parameter. If you do not want to use the stored values of any parameter, then * the iparam array should be of length = 3 and contain the discrimination, difficulty, * and guessing parameters, respectively. * * The order of parameters in iparam is as follows: * 1. Rasch model: iparam[0] = difficulty * 2. 2PL: iparam[0] = discrimination, iparam[1] = difficulty * 3. 3PL: iparam[1] = discrimination, iparam[1] = difficulty, iparam[2] = guessing * * @param theta person ability parameter. * @param iparam item parameter array that is one to three in length. * @param D scaling constant./*from ww w . j a v a 2 s . c o m*/ * @return probability of a correct answer. */ private double probRight(double theta, double[] iparam, double D) { double z = 0; if (iparam.length == 1) { z = Math.exp(D * discrimination * (theta - iparam[0])); return guessing + (slipping - guessing) * z / (1 + z); } else if (iparam.length == 2) { z = Math.exp(D * iparam[0] * (theta - iparam[1])); return guessing + (slipping - guessing) * z / (1 + z); } else { z = Math.exp(D * iparam[0] * (theta - iparam[1])); return iparam[2] + (slipping - iparam[2]) * z / (1 + z); } }
From source file:eu.amidst.core.inference.MAPInferenceExperiments.java
/** * The class constructor./*w w w . jav a 2s .c o m*/ * @param args Array of options: "filename variable a b N useVMP" if variable is continuous or "filename variable w N useVMP" for discrete */ public static void main(String[] args) throws Exception { String filename = ""; //Filename with the Bayesian Network //filename = "networks/randomlyGeneratedBN.bn"; //BayesianNetworkGenerator.generateBNtoFile(nDiscrete, nStates, nContin, nLinks, seedNetwork, filename); //BayesianNetwork bn = BayesianNetworkLoader.loadFromFile(filename); // int seedNetwork = 61236719 + 123; // // int nDiscrete = 20; // int nStates = 2; // int nContin = 0; // int nLinks = (int)Math.round(1.3*(nDiscrete+nContin)); // // // BayesianNetworkGenerator.setSeed(seedNetwork); // BayesianNetworkGenerator.setNumberOfGaussianVars(nContin); // BayesianNetworkGenerator.setNumberOfMultinomialVars(nDiscrete, nStates); // BayesianNetworkGenerator.setNumberOfLinks(nLinks); // // BayesianNetwork bn = BayesianNetworkGenerator.generateBayesianNetwork(); // // // int seed = seedNetwork + 2315; // // // if (Main.VERBOSE) System.out.println(bn.getDAG()); // // if (Main.VERBOSE) System.out.println(bn.toString()); // // // // MAPInference mapInference = new MAPInference(); // mapInference.setModel(bn); // mapInference.setParallelMode(true); // mapInference.setSampleSize(1); // // List<Variable> causalOrder = Utils.getTopologicalOrder(mapInference.getOriginalModel().getDAG()); // // if (Main.VERBOSE) System.out.println("CausalOrder: " + Arrays.toString(Utils.getTopologicalOrder(mapInference.getOriginalModel().getDAG()).stream().map(Variable::getName).toArray())); // if (Main.VERBOSE) System.out.println(); // // // // int parallelSamples=20; // int samplingMethodSize=50000; // mapInference.setSampleSize(parallelSamples); // // // // long timeStart; // long timeStop; // double execTime; // Assignment mapEstimate; // // // /*********************************************** // * INCLUDING EVIDENCE // ************************************************/ // // double observedVariablesRate = 0.05; // Assignment evidence = randomEvidence(seed, observedVariablesRate, bn); // // mapInference.setEvidence(evidence); // //if (Main.VERBOSE) System.out.println(evidence.outputString()); // // // // /*********************************************** // * VARIABLES OF INTEREST // ************************************************/ // // Variable varInterest1 = causalOrder.get(6); // Variable varInterest2 = causalOrder.get(7); // // // List<Variable> varsInterest = new ArrayList<>(); // varsInterest.add(varInterest1); // varsInterest.add(varInterest2); // mapInference.setMAPVariables(varsInterest); // // if (Main.VERBOSE) System.out.println("MAP Variables of Interest: " + Arrays.toString(varsInterest.stream().map(Variable::getName).toArray())); // if (Main.VERBOSE) System.out.println(); // // // // // /*********************************************** // * SIMULATED ANNEALING // ************************************************/ // // // // MAP INFERENCE WITH SIMULATED ANNEALING, MOVING ALL VARIABLES EACH TIME // timeStart = System.nanoTime(); // mapInference.runInference(1); // // mapEstimate = mapInference.getMAPestimate(); // if (Main.VERBOSE) System.out.println("MAP estimate (SA.All): " + mapEstimate.outputString(varsInterest)); // if (Main.VERBOSE) System.out.println("with (unnormalized) probability: " + mapInference.getMAPestimateProbability()); // timeStop = System.nanoTime(); // execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().)); // if (Main.VERBOSE) System.out.println(); // // // // MAP INFERENCE WITH SIMULATED ANNEALING, SOME VARIABLES EACH TIME // timeStart = System.nanoTime(); // mapInference.runInference(0); // // mapEstimate = mapInference.getMAPestimate(); // if (Main.VERBOSE) System.out.println("MAP estimate (SA.Some): " + mapEstimate.outputString(varsInterest)); // if (Main.VERBOSE) System.out.println("with (unnormalized) probability: " + mapInference.getMAPestimateProbability()); // timeStop = System.nanoTime(); // execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().)); // if (Main.VERBOSE) System.out.println(); // // // /*********************************************** // * HILL CLIMBING // ************************************************/ // // // MAP INFERENCE WITH HILL CLIMBING, MOVING ALL VARIABLES EACH TIME // timeStart = System.nanoTime(); // mapInference.runInference(3); // // mapEstimate = mapInference.getMAPestimate(); // if (Main.VERBOSE) System.out.println("MAP estimate (HC.All): " + mapEstimate.outputString(varsInterest)); // if (Main.VERBOSE) System.out.println("with (unnormalized) probability: " + mapInference.getMAPestimateProbability()); // timeStop = System.nanoTime(); // execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // if (Main.VERBOSE) System.out.println(); // // // // // MAP INFERENCE WITH HILL CLIMBING, SOME VARIABLES EACH TIME // timeStart = System.nanoTime(); // mapInference.runInference(2); // // mapEstimate = mapInference.getMAPestimate(); // if (Main.VERBOSE) System.out.println("MAP estimate (HC.Some): " + mapEstimate.outputString(varsInterest)); // if (Main.VERBOSE) System.out.println("with (unnormalized) probability: " + mapInference.getMAPestimateProbability()); // timeStop = System.nanoTime(); // execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // if (Main.VERBOSE) System.out.println(); // // // /*********************************************** // * SAMPLING // ************************************************/ // // // MAP INFERENCE WITH SIMULATION AND PICKING MAX // mapInference.setSampleSize(samplingMethodSize); // timeStart = System.nanoTime(); // mapInference.runInference(-1); // // mapEstimate = mapInference.getMAPestimate(); // if (Main.VERBOSE) System.out.println("MAP estimate (SAMPLING): " + mapEstimate.outputString(varsInterest)); // if (Main.VERBOSE) System.out.println("with probability: " + mapInference.getMAPestimateProbability()); // timeStop = System.nanoTime(); // execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // if (Main.VERBOSE) System.out.println(); // // // // // // // // PROBABILITIES OF INDIVIDUAL CONFIGURATIONS // // // double s1 = mapInference.estimateProbabilityOfPartialAssignment(mapEstimate); // if (Main.VERBOSE) System.out.println(mapEstimate.outputString(varsInterest) + " with prob. " + s1); // // mapEstimate.setValue(varInterest2, 1); // double s2 = mapInference.estimateProbabilityOfPartialAssignment(mapEstimate); // if (Main.VERBOSE) System.out.println(mapEstimate.outputString(varsInterest) + " with prob. " + s2); // // mapEstimate.setValue(varInterest1, 1); // mapEstimate.setValue(varInterest2, 0); // double s3 = mapInference.estimateProbabilityOfPartialAssignment(mapEstimate); // if (Main.VERBOSE) System.out.println(mapEstimate.outputString(varsInterest) + " with prob. " + s3); // // mapEstimate.setValue(varInterest2, 1); // double s4 = mapInference.estimateProbabilityOfPartialAssignment(mapEstimate); // if (Main.VERBOSE) System.out.println(mapEstimate.outputString(varsInterest) + " with prob. " + s4); // // double sumNonStateless = s1+s2+s3+s4; // // if (Main.VERBOSE) System.out.println(); // if (Main.VERBOSE) System.out.println("Sum = " + sumNonStateless + "; Normalized probs: [V1=0,V2=0]=" + s1/sumNonStateless + ", [V1=0,V2=1]=" + s2/sumNonStateless + ", [V1=1,V2=0]=" + s3/sumNonStateless + ", [V1=1,V2=1]=" + s4/sumNonStateless ); int seedNetwork = 1253473; int nDiscrete = 50; int nStates = 2; int nContin = 50; int nLinks = (int) Math.round(1.3 * (nDiscrete + nContin)); BayesianNetworkGenerator.setSeed(seedNetwork); BayesianNetworkGenerator.setNumberOfGaussianVars(nContin); BayesianNetworkGenerator.setNumberOfMultinomialVars(nDiscrete, nStates); BayesianNetworkGenerator.setNumberOfLinks(nLinks); BayesianNetwork bn = BayesianNetworkGenerator.generateBayesianNetwork(); int seed = seedNetwork + 23715; if (Main.VERBOSE) System.out.println(bn.getDAG()); if (Main.VERBOSE) System.out.println(bn.toString()); MAPInference mapInference = new MAPInference(); mapInference.setModel(bn); mapInference.setParallelMode(true); mapInference.setSampleSize(1); List<Variable> causalOrder = Utils.getTopologicalOrder(mapInference.getOriginalModel().getDAG()); if (Main.VERBOSE) System.out.println("CausalOrder: " + Arrays.toString(Utils.getTopologicalOrder(mapInference.getOriginalModel().getDAG()).stream() .map(Variable::getName).toArray())); if (Main.VERBOSE) System.out.println(); int parallelSamples = 20; int samplingMethodSize = 100000; mapInference.setSampleSize(parallelSamples); long timeStart; long timeStop; double execTime; Assignment mapEstimate; /*********************************************** * INCLUDING EVIDENCE ************************************************/ double observedVariablesRate = 0.05; Assignment evidence = randomEvidence(seed, observedVariablesRate, bn); mapInference.setEvidence(evidence); //if (Main.VERBOSE) System.out.println(evidence.outputString()); /*********************************************** * VARIABLES OF INTEREST ************************************************/ Variable varInterest1 = causalOrder.get(6); Variable varInterest2 = causalOrder.get(7); Variable varInterest3 = causalOrder.get(60); List<Variable> varsInterest = new ArrayList<>(); varsInterest.add(varInterest1); varsInterest.add(varInterest2); varsInterest.add(varInterest3); mapInference.setMAPVariables(varsInterest); if (Main.VERBOSE) System.out.println("MAP Variables of Interest: " + Arrays.toString(varsInterest.stream().map(Variable::getName).toArray())); if (Main.VERBOSE) System.out.println(); /*********************************************** * SIMULATED ANNEALING ************************************************/ // MAP INFERENCE WITH SIMULATED ANNEALING, MOVING ALL VARIABLES EACH TIME timeStart = System.nanoTime(); mapInference.runInference(MAPInference.SearchAlgorithm.SA_GLOBAL); mapEstimate = mapInference.getEstimate(); if (Main.VERBOSE) System.out.println("MAP estimate (SA.All): " + mapEstimate.outputString(varsInterest)); if (Main.VERBOSE) System.out.println( "with (unnormalized) probability: " + Math.exp(mapInference.getLogProbabilityOfEstimate())); timeStop = System.nanoTime(); execTime = (double) (timeStop - timeStart) / 1000000000.0; if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().)); if (Main.VERBOSE) System.out.println(); // MAP INFERENCE WITH SIMULATED ANNEALING, MOVING SOME VARIABLES EACH TIME timeStart = System.nanoTime(); mapInference.runInference(MAPInference.SearchAlgorithm.SA_LOCAL); mapEstimate = mapInference.getEstimate(); if (Main.VERBOSE) System.out.println("MAP estimate (SA.Some): " + mapEstimate.outputString(varsInterest)); if (Main.VERBOSE) System.out.println( "with (unnormalized) probability: " + Math.exp(mapInference.getLogProbabilityOfEstimate())); timeStop = System.nanoTime(); execTime = (double) (timeStop - timeStart) / 1000000000.0; if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().)); if (Main.VERBOSE) System.out.println(); /*********************************************** * HILL CLIMBING ************************************************/ // MAP INFERENCE WITH HILL CLIMBING, MOVING ALL VARIABLES EACH TIME timeStart = System.nanoTime(); mapInference.runInference(MAPInference.SearchAlgorithm.HC_GLOBAL); mapEstimate = mapInference.getEstimate(); if (Main.VERBOSE) System.out.println("MAP estimate (HC.All): " + mapEstimate.outputString(varsInterest)); if (Main.VERBOSE) System.out.println( "with (unnormalized) probability: " + Math.exp(mapInference.getLogProbabilityOfEstimate())); timeStop = System.nanoTime(); execTime = (double) (timeStop - timeStart) / 1000000000.0; if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); if (Main.VERBOSE) System.out.println(); // MAP INFERENCE WITH HILL CLIMBING, MOVING SOME VARIABLES EACH TIME timeStart = System.nanoTime(); mapInference.runInference(MAPInference.SearchAlgorithm.HC_LOCAL); mapEstimate = mapInference.getEstimate(); if (Main.VERBOSE) System.out.println("MAP estimate (HC.Some): " + mapEstimate.outputString(varsInterest)); if (Main.VERBOSE) System.out.println( "with (unnormalized) probability: " + Math.exp(mapInference.getLogProbabilityOfEstimate())); timeStop = System.nanoTime(); execTime = (double) (timeStop - timeStart) / 1000000000.0; if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); if (Main.VERBOSE) System.out.println(); /*********************************************** * SAMPLING ************************************************/ // MAP INFERENCE WITH SIMULATION AND PICKING MAX mapInference.setSampleSize(samplingMethodSize); timeStart = System.nanoTime(); mapInference.runInference(MAPInference.SearchAlgorithm.SAMPLING); mapEstimate = mapInference.getEstimate(); if (Main.VERBOSE) System.out.println("MAP estimate (SAMPLING): " + mapEstimate.outputString(varsInterest)); if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getLogProbabilityOfEstimate())); timeStop = System.nanoTime(); execTime = (double) (timeStop - timeStart) / 1000000000.0; if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); if (Main.VERBOSE) System.out.println(); // PROBABILITIES OF INDIVIDUAL CONFIGURATIONS double s1 = mapInference.estimateProbabilityOfPartialAssignment(mapEstimate); if (Main.VERBOSE) System.out.println(mapEstimate.outputString(varsInterest) + " with prob. " + s1); mapEstimate.setValue(varInterest2, 1); double s2 = mapInference.estimateProbabilityOfPartialAssignment(mapEstimate); if (Main.VERBOSE) System.out.println(mapEstimate.outputString(varsInterest) + " with prob. " + s2); mapEstimate.setValue(varInterest1, 1); mapEstimate.setValue(varInterest2, 0); double s3 = mapInference.estimateProbabilityOfPartialAssignment(mapEstimate); if (Main.VERBOSE) System.out.println(mapEstimate.outputString(varsInterest) + " with prob. " + s3); mapEstimate.setValue(varInterest2, 1); double s4 = mapInference.estimateProbabilityOfPartialAssignment(mapEstimate); if (Main.VERBOSE) System.out.println(mapEstimate.outputString(varsInterest) + " with prob. " + s4); double sum = s1 + s2 + s3 + s4; if (Main.VERBOSE) System.out.println(); if (Main.VERBOSE) System.out.println("Sum = " + sum + "; Normalized probs: [V1=0,V2=0]=" + s1 / sum + ", [V1=0,V2=1]=" + s2 / sum + ", [V1=1,V2=0]=" + s3 / sum + ", [V1=1,V2=1]=" + s4 / sum); // long timeStart = System.nanoTime(); // mapInference.runInference(1); // // Assignment mapEstimate1 = mapInference.getMAPestimate(); // List<Variable> modelVariables = mapInference.getOriginalModel().getVariables().getListOfVariables(); // if (Main.VERBOSE) System.out.println("MAP estimate: " + mapEstimate1.toString()); //toString(modelVariables); // if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getOriginalModel().getLogProbabiltyOf(mapEstimate1))); // long timeStop = System.nanoTime(); // double execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getVariables().iterator().)); // // // // // // MAP INFERENCE WITH A BIG SAMPLE TO CHECK // mapInference.setSampleSize(50000); // timeStart = System.nanoTime(); // mapInference.runInference(-1); // // Assignment mapEstimate2 = mapInference.getMAPestimate(); // modelVariables = mapInference.getOriginalModel().getVariables().getListOfVariables(); // if (Main.VERBOSE) System.out.println("MAP estimate (huge sample): " + mapEstimate2.toString()); // if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getOriginalModel().getLogProbabiltyOf(mapEstimate2))); // timeStop = System.nanoTime(); // execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // // // // // DETERMINISTIC SEQUENTIAL SEARCH ON DISCRETE VARIABLES // timeStart = System.nanoTime(); // mapInference.runInference(-2); // // Assignment mapEstimate3 = mapInference.getMAPestimate(); // modelVariables = mapInference.getOriginalModel().getVariables().getListOfVariables(); // if (Main.VERBOSE) System.out.println("MAP estimate (sequential): " + mapEstimate3.toString()); // if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getOriginalModel().getLogProbabiltyOf(mapEstimate3))); // timeStop = System.nanoTime(); // execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // // if (Main.VERBOSE) System.out.println(); // if (Main.VERBOSE) System.out.println(); // if (Main.VERBOSE) System.out.println(); // if (Main.VERBOSE) System.out.println(); //mapInference.changeCausalOrder(bn,evidence); /*// AD-HOC MAP mapEstimate.setValue(bn.getVariables().getVariableByName("GaussianVar0"),-0.11819702417804305); mapEstimate.setValue(bn.getVariables().getVariableByName("GaussianVar1"),-1.706); mapEstimate.setValue(bn.getVariables().getVariableByName("GaussianVar2"),4.95); mapEstimate.setValue(bn.getVariables().getVariableByName("GaussianVar3"),14.33); mapEstimate.setValue(bn.getVariables().getVariableByName("GaussianVar4"),11.355); modelVariables = mapInference.getOriginalModel().getVariables().getListOfParamaterVariables(); if (Main.VERBOSE) System.out.println("Other estimate: " + mapEstimate.toString(modelVariables)); if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getOriginalModel().getLogProbabiltyOf(mapEstimate))); */ // // // // // // BayesianNetwork bn = BayesianNetworkLoader.loadFromFile("./networks/randomlyGeneratedBN.bn"); // //BayesianNetwork bn = BayesianNetworkLoader.loadFromFile("./networks/asia.bn"); // if (Main.VERBOSE) System.out.println(bn.getDAG()); // // if (Main.VERBOSE) System.out.println(bn.toString()); // // // MAPInference mapInference = new MAPInference(); // mapInference.setModel(bn); // mapInference.setParallelMode(true); // // // if (Main.VERBOSE) System.out.println("CausalOrder: " + Arrays.toString(mapInference.causalOrder.stream().map(v -> v.getName()).toArray())); // if (Main.VERBOSE) System.out.println(); // // // Including evidence: // Variable variable1 = mapInference.causalOrder.get(1); // causalOrder: A, S, L, T, E, X, B, D // Variable variable2 = mapInference.causalOrder.get(2); // //Variable variable3 = mapInference.causalOrder.get(11); // Variable variable3 = mapInference.causalOrder.get(4); // // int var1value=0; // int var2value=1; // //double var3value=1.27; // int var3value=1; // // if (Main.VERBOSE) System.out.println("Evidence: Variable " + variable1.getName() + " = " + var1value + ", Variable " + variable2.getName() + " = " + var2value + " and Variable " + variable3.getName() + " = " + var3value); // if (Main.VERBOSE) System.out.println(); // // HashMapAssignment evidenceAssignment = new HashMapAssignment(3); // // evidenceAssignment.setValue(variable1,var1value); // evidenceAssignment.setValue(variable2,var2value); // evidenceAssignment.setValue(variable3,var3value); // // mapInference.setEvidence(evidenceAssignment); // // List<Variable> modelVariables = mapInference.getOriginalModel().getVariables().getListOfVariables(); // //if (Main.VERBOSE) System.out.println(evidenceAssignment.outputString(modelVariables)); // // // // long timeStart; // long timeStop; // double execTime; // Assignment mapEstimate; // // // /* // // MAP INFERENCE WITH A SMALL SAMPLE AND SIMULATED ANNEALING // mapInference.setSampleSize(100); // timeStart = System.nanoTime(); // mapInference.runInference(1); // // // Assignment mapEstimate = mapInference.getMAPestimate(); // if (Main.VERBOSE) System.out.println("MAP estimate (SA): " + mapEstimate.outputString(modelVariables)); //toString(modelVariables) // if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getOriginalModel().getLogProbabiltyOf(mapEstimate))); // timeStop = System.nanoTime(); // execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().)); // if (Main.VERBOSE) System.out.println(); // // // // MAP INFERENCE WITH A BIG SAMPLE AND SIMULATED ANNEALING // mapInference.setSampleSize(100); // timeStart = System.nanoTime(); // mapInference.runInference(1); // // mapEstimate = mapInference.getMAPestimate(); // modelVariables = mapInference.getOriginalModel().getStaticVariables().getListOfVariables(); // if (Main.VERBOSE) System.out.println("MAP estimate (SA): " + mapEstimate.outputString(modelVariables)); // if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getOriginalModel().getLogProbabiltyOf(mapEstimate))); // timeStop = System.nanoTime(); // execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // if (Main.VERBOSE) System.out.println(); // // // // // // MAP INFERENCE WITH A BIG SAMPLE AND SIMULATED ANNEALING ON ONE VARIABLE EACH TIME // mapInference.setSampleSize(100); // timeStart = System.nanoTime(); // mapInference.runInference(0); // // // mapEstimate = mapInference.getMAPestimate(); // if (Main.VERBOSE) System.out.println("MAP estimate (SA.1V): " + mapEstimate.outputString(modelVariables)); //toString(modelVariables) // if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getOriginalModel().getLogProbabiltyOf(mapEstimate))); // timeStop = System.nanoTime(); // execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().)); // if (Main.VERBOSE) System.out.println(); // // // // // // MAP INFERENCE WITH A BIG SAMPLE AND HILL CLIMBING // mapInference.setSampleSize(100); // timeStart = System.nanoTime(); // mapInference.runInference(3); // // mapEstimate = mapInference.getMAPestimate(); // modelVariables = mapInference.getOriginalModel().getStaticVariables().getListOfVariables(); // if (Main.VERBOSE) System.out.println("MAP estimate (HC): " + mapEstimate.outputString(modelVariables)); // if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getOriginalModel().getLogProbabiltyOf(mapEstimate))); // timeStop = System.nanoTime(); // execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // if (Main.VERBOSE) System.out.println(); // // // // // // MAP INFERENCE WITH A BIG SAMPLE AND HILL CLIMBING ON ONE VARIABLE EACH TIME // mapInference.setSampleSize(100); // timeStart = System.nanoTime(); // mapInference.runInference(2); // // // mapEstimate = mapInference.getMAPestimate(); // if (Main.VERBOSE) System.out.println("MAP estimate (HC.1V): " + mapEstimate.outputString(modelVariables)); //toString(modelVariables) // if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getOriginalModel().getLogProbabiltyOf(mapEstimate))); // timeStop = System.nanoTime(); // execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().)); // if (Main.VERBOSE) System.out.println(); // // // // // // // MAP INFERENCE WITH SIMULATION AND PICKING MAX // mapInference.setSampleSize(100); // timeStart = System.nanoTime(); // mapInference.runInference(-1); // // mapEstimate = mapInference.getMAPestimate(); // modelVariables = mapInference.getOriginalModel().getStaticVariables().getListOfVariables(); // if (Main.VERBOSE) System.out.println("MAP estimate (SAMPLING): " + mapEstimate.outputString(modelVariables)); // if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getOriginalModel().getLogProbabiltyOf(mapEstimate))); // timeStop = System.nanoTime(); // execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // if (Main.VERBOSE) System.out.println(); // // // // // MAP INFERENCE, DETERMINISTIC // mapInference.setSampleSize(1); // timeStart = System.nanoTime(); // mapInference.runInference(-2); // // mapEstimate = mapInference.getMAPestimate(); // modelVariables = mapInference.getOriginalModel().getStaticVariables().getListOfVariables(); // if (Main.VERBOSE) System.out.println("MAP estimate (DETERM.): " + mapEstimate.outputString(modelVariables)); // if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getOriginalModel().getLogProbabiltyOf(mapEstimate))); // timeStop = System.nanoTime(); // execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // if (Main.VERBOSE) System.out.println(); // */ // // // // // /** // * // * // * MAP OVER SPECIFIC VARIABLES // * // * // */ // // // if (Main.VERBOSE) System.out.println(); // if (Main.VERBOSE) System.out.println(); // // Variable varInterest1 = mapInference.causalOrder.get(6); // causalOrder: A, S, L, T, E, X, B, D // Variable varInterest2 = mapInference.causalOrder.get(7); // // // Set<Variable> varsInterest = new HashSet<>(); // varsInterest.add(varInterest1); // varsInterest.add(varInterest2); // mapInference.setMAPVariables(varsInterest); // // if (Main.VERBOSE) System.out.println("MAP Variables of Interest: " + Arrays.toString(mapInference.MAPvariables.stream().map(Variable::getName).toArray())); // if (Main.VERBOSE) System.out.println(); // // // // // MAP INFERENCE // mapInference.setSampleSize(1); // timeStart = System.nanoTime(); // mapInference.runInference(1); // // mapEstimate = mapInference.getMAPestimate(); // modelVariables = mapInference.getOriginalModel().getVariables().getListOfVariables(); // if (Main.VERBOSE) System.out.println("MAP estimate: " + mapEstimate.outputString(new ArrayList(mapInference.MAPvariables))); // if (Main.VERBOSE) System.out.println("with probability: " + + mapInference.getMAPestimateProbability()); // timeStop = System.nanoTime(); // execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // if (Main.VERBOSE) System.out.println(); // // // // // // MAP INFERENCE // mapInference.setSampleSize(100); // timeStart = System.nanoTime(); // mapInference.runInference(-3); // // mapEstimate = mapInference.getMAPestimate(); // modelVariables = mapInference.getOriginalModel().getVariables().getListOfVariables(); // if (Main.VERBOSE) System.out.println("MAP estimate (-3): " + mapEstimate.outputString(new ArrayList(mapInference.MAPvariables))); // if (Main.VERBOSE) System.out.println("with probability: " + mapInference.getMAPestimateProbability()); // timeStop = System.nanoTime(); // execTime = (double) (timeStop - timeStart) / 1000000000.0; // if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds"); // if (Main.VERBOSE) System.out.println(); // // // // MAP Assignments // // // double s1 = mapInference.estimateProbabilityOfPartialAssignment(mapEstimate); // if (Main.VERBOSE) System.out.println(mapEstimate.outputString() + " with prob. " + s1); // // mapEstimate.setValue((Variable)mapEstimate.getVariables().toArray()[0],1); // double s2 = mapInference.estimateProbabilityOfPartialAssignment(mapEstimate); // if (Main.VERBOSE) System.out.println(mapEstimate.outputString() + " with prob. " + s2); // // mapEstimate.setValue((Variable)mapEstimate.getVariables().toArray()[1],1); // double s3 = mapInference.estimateProbabilityOfPartialAssignment(mapEstimate); // if (Main.VERBOSE) System.out.println(mapEstimate.outputString() + " with prob. " + s3); // // mapEstimate.setValue((Variable)mapEstimate.getVariables().toArray()[0],0); // double s4 = mapInference.estimateProbabilityOfPartialAssignment(mapEstimate); // if (Main.VERBOSE) System.out.println(mapEstimate.outputString() + " with prob. " + s4); // // double sumNonStateless = s1+s2+s3+s4; // // if (Main.VERBOSE) System.out.println("Probs: " + s1/sumNonStateless + ", " + s2/sumNonStateless + ", " + s3/sumNonStateless + ", " + s4/sumNonStateless + ", suma = " + sumNonStateless ); }
From source file:MainClass.EquationSolver.java
@Override public void actionPerformed(ActionEvent e) { this.setVisible(true); textArea.setText(null);//command to clear the textArea String decString = "0.";//block used to set the decimal point if (decTextField.getText().hashCode() != 0) { for (int i = 0; i < (Integer.parseInt(decTextField.getText())); i++) { decString += "0"; }/*from w w w . java2 s . c o m*/ decString += "1"; decpoint = Double.parseDouble(decString); } else { decTextField.setText("0"); } switch (methodComboBox.getSelectedItem().toString()) {//block used to show or hide the second textField coresponding the mothod selected case "Secant": sp2TextField.setVisible(true); this.setVisible(true); break; case "Bisection": sp2TextField.setVisible(true); this.setVisible(true); break; default: sp2TextField.setVisible(false); this.setVisible(true); break; } if (e.getSource() == calculateBtn) { try {//Try used to test if the inserted starting point is not a numerical value switch (methodComboBox.getSelectedItem().toString()) {//Switch used to implement the limits of the function ploted on the graph accordingly the method selected case "Secant": case "Bisection": if (sp1TextField.getText().hashCode() == 0 || sp2TextField.getText().hashCode() == 0) { JOptionPane.showMessageDialog(null, "Please insert two starting points"); } if (Double.parseDouble(sp2TextField.getText()) > Double.parseDouble(sp1TextField.getText())) { limitx = Math.abs(Double.parseDouble(sp2TextField.getText())); limity = limitx * (-1); } else { limitx = Math.abs(Double.parseDouble(sp1TextField.getText())); limity = limitx * (-1); } break; case "Newton-Raphson": limitx = Math.abs(Double.parseDouble(sp1TextField.getText())); limity = limitx * (-1); break; case "Select a method:": JOptionPane.showMessageDialog(null, "Please select a method!"); break; default: limitx = 50; limity = -50; break; } if (limitx == 0) { limitx = 50; limity = -50; } else if ("ln(x+1)+1".equals(equationComboBox.getSelectedItem().toString()) || "e^x-3x".equals(equationComboBox.getSelectedItem().toString()) || "x-x^2".equals(equationComboBox.getSelectedItem().toString())) { limitx *= 10; limity *= 10; } if (null != equationComboBox.getSelectedItem().toString()) {//Test if the comboBox was pressed switch (equationComboBox.getSelectedItem().toString()) {//Swith implementing in a global variable a dataset accordingly the function selected case "x-x^2": datasetFunction = DatasetUtilities.sampleFunction2D(v -> v - Math.pow(v, 2.0), limity, limitx, 100, "Function x-x^2"); break; case "ln(x+1)+1": datasetFunction = DatasetUtilities.sampleFunction2D(v -> Math.log(v + 1.0) + 1.0, limity, limitx, 100, "Function ln(x+1)+1"); break; default: datasetFunction = DatasetUtilities.sampleFunction2D(v -> (Math.exp(v)) - (3 * v), limity, limitx, 100, "Function e^x-3x"); break; } } switch (equationComboBox.getSelectedItem().toString()) {// Switch used to verify what function and method was selected case "x-x^2": if (null != methodComboBox.getSelectedItem().toString()) { switch (methodComboBox.getSelectedItem().toString()) { case "Newton-Raphson": CalculusNewtonRaphson.newtonRaphson1(Double.parseDouble(sp1TextField.getText()), decpoint); refreshTable(CalculusNewtonRaphson.createChartNewtonRapson(datasetFunction)); textArea.append(CalculusNewtonRaphson .textDataNewtonRapson(Integer.parseInt(decTextField.getText()))); table.setModel(CalculusNewtonRaphson.getTableData()); break; case "Secant": CalculusSecant.secant1(Double.parseDouble(sp1TextField.getText()), Double.parseDouble(sp2TextField.getText()), decpoint); refreshTable(CalculusSecant.createChartSecant(datasetFunction)); textArea.append( CalculusSecant.textDataSecant(Integer.parseInt(decTextField.getText()))); table.setModel(CalculusSecant.getTableData()); break; case "Bisection": CalculusBisection.bisection1(Double.parseDouble(sp1TextField.getText()), Double.parseDouble(sp2TextField.getText()), decpoint); refreshTable(CalculusBisection.createChartBisection(datasetFunction)); textArea.append( CalculusBisection.textDataBisection(Integer.parseInt(decTextField.getText()))); table.setModel(CalculusBisection.getTableData()); break; } } break; case "ln(x+1)+1": if (null != methodComboBox.getSelectedItem().toString()) { switch (methodComboBox.getSelectedItem().toString()) { case "Newton-Raphson": CalculusNewtonRaphson.newtonRaphson2(Double.parseDouble(sp1TextField.getText()), decpoint); refreshTable(CalculusNewtonRaphson.createChartNewtonRapson(datasetFunction)); textArea.append(CalculusNewtonRaphson .textDataNewtonRapson(Integer.parseInt(decTextField.getText()))); table.setModel(CalculusNewtonRaphson.getTableData()); break; case "Secant": CalculusSecant.secant2(Double.parseDouble(sp1TextField.getText()), Double.parseDouble(sp2TextField.getText()), decpoint); refreshTable(CalculusSecant.createChartSecant(datasetFunction)); textArea.append( CalculusSecant.textDataSecant(Integer.parseInt(decTextField.getText()))); table.setModel(CalculusSecant.getTableData()); break; case "Bisection": CalculusBisection.bisection2(Double.parseDouble(sp1TextField.getText()), Double.parseDouble(sp2TextField.getText()), decpoint); refreshTable(CalculusBisection.createChartBisection(datasetFunction)); textArea.append( CalculusBisection.textDataBisection(Integer.parseInt(decTextField.getText()))); table.setModel(CalculusBisection.getTableData()); break; } } break; case "e^x-3x": if (null != methodComboBox.getSelectedItem().toString()) { switch (methodComboBox.getSelectedItem().toString()) { case "Newton-Raphson": CalculusNewtonRaphson.newtonRaphson3(Double.parseDouble(sp1TextField.getText()), decpoint); refreshTable(CalculusNewtonRaphson.createChartNewtonRapson(datasetFunction)); textArea.append(CalculusNewtonRaphson .textDataNewtonRapson(Integer.parseInt(decTextField.getText()))); table.setModel(CalculusNewtonRaphson.getTableData()); break; case "Secant": CalculusSecant.secant3(Double.parseDouble(sp1TextField.getText()), Double.parseDouble(sp2TextField.getText()), decpoint); refreshTable(CalculusSecant.createChartSecant(datasetFunction)); textArea.append( CalculusSecant.textDataSecant(Integer.parseInt(decTextField.getText()))); table.setModel(CalculusSecant.getTableData()); break; case "Bisection": CalculusBisection.bisection3(Double.parseDouble(sp1TextField.getText()), Double.parseDouble(sp2TextField.getText()), decpoint); refreshTable(CalculusBisection.createChartBisection(datasetFunction)); textArea.append( CalculusBisection.textDataBisection(Integer.parseInt(decTextField.getText()))); table.setModel(CalculusBisection.getTableData()); break; } } break; } } catch (Exception x) { JOptionPane.showMessageDialog(null, "Please insert a numerical value!"); } } }
From source file:bb.mcmc.analysis.ConvergeStatUtils.java
private static double calSpectrum0(double[] newData) { final int N = newData.length; final int Nfreq = (int) Math.floor(N / 2); final double oneOverN = 1.0 / N; double[] freq = new double[Nfreq]; double[] f1 = new double[Nfreq]; for (int i = 0; i < Nfreq; i++) { freq[i] = oneOverN * (i + 1);/*from w ww. j a v a 2 s . c om*/ f1[i] = SQRT3 * (4 * freq[i] - 1); } double[] complexArray = ConvergeStatUtils.realToComplexArray(newData); double[] spec = new double[N]; DoubleFFT_1D fft = new DoubleFFT_1D(N); fft.complexForward(complexArray); for (int i = 0; i < N; i++) { Complex complexData = new Complex(complexArray[i * 2], complexArray[i * 2 + 1]); complexData = complexData.multiply(complexData.conjugate()); spec[i] = complexData.getReal() / N; } spec = Arrays.copyOfRange(spec, 1, f1.length + 1); double[] coefficients = gammaGLM.coefficients(spec, f1); double v = Math.exp(coefficients[0] + coefficients[1] * -SQRT3); return v; }
From source file:net.librec.recommender.content.EFMRecommender.java
@Override protected void setup() throws LibrecException { super.setup(); scoreScale = maxRate - minRate;//www. j a va 2 s . co m explicitFeatureNum = conf.getInt("rec.factor.explicit", 5); hiddenFeatureNum = numFactors - explicitFeatureNum; lambdaX = conf.getDouble("rec.regularization.lambdax", 0.001); lambdaY = conf.getDouble("rec.regularization.lambday", 0.001); lambdaU = conf.getDouble("rec.regularization.lambdau", 0.001); lambdaH = conf.getDouble("rec.regularization.lambdah", 0.001); lambdaV = conf.getDouble("rec.regularization.lambdav", 0.001); featureSentimemtPairsMappingData = allFeaturesMappingData.get(2).inverse(); trainMatrix = trainTensor.rateMatrix(); featureDict = HashBiMap.create(); Map<Integer, String> userFeatureDict = new HashMap<Integer, String>(); Map<Integer, String> itemFeatureDict = new HashMap<Integer, String>(); numberOfFeatures = 0; for (TensorEntry te : trainTensor) { int[] entryKeys = te.keys(); int userIndex = entryKeys[0]; int itemIndex = entryKeys[1]; int featureSentimentPairsIndex = entryKeys[2]; String featureSentimentPairsString = featureSentimemtPairsMappingData.get(featureSentimentPairsIndex); String[] fSPList = featureSentimentPairsString.split(" "); for (String p : fSPList) { String k = p.split(":")[0]; if (!featureDict.containsKey(k) && !StringUtils.isEmpty(k)) { featureDict.put(k, numberOfFeatures); numberOfFeatures++; } if (userFeatureDict.containsKey(userIndex)) { userFeatureDict.put(userIndex, userFeatureDict.get(userIndex) + " " + p); } else { userFeatureDict.put(userIndex, p); } if (itemFeatureDict.containsKey(itemIndex)) { itemFeatureDict.put(itemIndex, itemFeatureDict.get(itemIndex) + " " + p); } else { itemFeatureDict.put(itemIndex, p); } } } // Create V,U1,H1,U2,H2 featureMatrix = new DenseMatrix(numberOfFeatures, explicitFeatureNum); featureMatrix.init(0.01); userFeatureMatrix = new DenseMatrix(numUsers, explicitFeatureNum); //userFactors.getSubMatrix(0, userFactors.numRows() - 1, 0, explicitFeatureNum - 1); userFeatureMatrix.init(1); userHiddenMatrix = new DenseMatrix(numUsers, numFactors - explicitFeatureNum); // userFactors.getSubMatrix(0, userFactors.numRows() - 1, explicitFeatureNum, userFactors.numColumns() - 1); userHiddenMatrix.init(1); itemFeatureMatrix = new DenseMatrix(numItems, explicitFeatureNum);// itemFactors.getSubMatrix(0, itemFactors.numRows() - 1, 0, explicitFeatureNum - 1); itemFeatureMatrix.init(1); itemHiddenMatrix = new DenseMatrix(numItems, numFactors - explicitFeatureNum);// itemFactors.getSubMatrix(0, itemFactors.numRows() - 1, explicitFeatureNum, itemFactors.numColumns() - 1); itemHiddenMatrix.init(1); // compute UserFeatureAttention Table<Integer, Integer, Double> userFeatureAttentionTable = HashBasedTable.create(); for (int u : userFeatureDict.keySet()) { double[] featureValues = new double[numberOfFeatures]; String[] fList = userFeatureDict.get(u).split(" "); for (String a : fList) { if (!StringUtils.isEmpty(a)) { int fin = featureDict.get(a.split(":")[0]); featureValues[fin] += 1; } } for (int i = 0; i < numberOfFeatures; i++) { if (featureValues[i] != 0.0) { double v = 1 + (scoreScale - 1) * (2 / (1 + Math.exp(-featureValues[i])) - 1); userFeatureAttentionTable.put(u, i, v); } } } userFeatureAttention = new SparseMatrix(numUsers, numberOfFeatures, userFeatureAttentionTable); // Compute ItemFeatureQuality Table<Integer, Integer, Double> itemFeatureQualityTable = HashBasedTable.create(); for (int p : itemFeatureDict.keySet()) { double[] featureValues = new double[numberOfFeatures]; String[] fList = itemFeatureDict.get(p).split(" "); for (String a : fList) { if (!StringUtils.isEmpty(a)) { int fin = featureDict.get(a.split(":")[0]); featureValues[fin] += Double.parseDouble(a.split(":")[1]); } } for (int i = 0; i < numberOfFeatures; i++) { if (featureValues[i] != 0.0) { double v = 1 + (scoreScale - 1) / (1 + Math.exp(-featureValues[i])); itemFeatureQualityTable.put(p, i, v); } } } itemFeatureQuality = new SparseMatrix(numItems, numberOfFeatures, itemFeatureQualityTable); doExplain = conf.getBoolean("rec.explain.flag"); LOG.info("numUsers:" + numUsers); LOG.info("numItems:" + numItems); LOG.info("numFeatures:" + numberOfFeatures); }
From source file:com.datumbox.framework.statistics.distributions.ContinuousDistributions.java
/** * Internal function used by GammaCdf//from ww w. ja va 2 s . c o m * * @param x * @param A * @return */ protected static double Gcf(double x, double A) { // Good for X>A+1 double A0 = 0; double B0 = 1; double A1 = 1; double B1 = x; double AOLD = 0; double N = 0; while (Math.abs((A1 - AOLD) / A1) > .00001) { AOLD = A1; N = N + 1; A0 = A1 + (N - A) * A0; B0 = B1 + (N - A) * B0; A1 = x * A0 + N * A1; B1 = x * B0 + N * B1; A0 = A0 / B1; B0 = B0 / B1; A1 = A1 / B1; B1 = 1; } double Prob = Math.exp(A * Math.log(x) - x - LogGamma(A)) * A1; return 1.0 - Prob; }
From source file:crbm.CRBM.java
private float[] logistic(float[] data) { float[] result = new float[data.length]; for (int i = 0; i < data.length; i++) { result[i] = 1.f / (float) (1. + Math.exp(-data[i])); }// ww w . j a va 2 s . c o m return result; }
From source file:com.opengamma.analytics.financial.interestrate.swaption.method.SwaptionPhysicalFixedIborLMMDDMethod.java
/** * Computes the present value of the Physical delivery swaption. * @param swaption The swaption.//from w ww. jav a2s .co m * @param lmmBundle The LMM parameters and the curves. * @return The present value. */ public CurrencyAmount presentValue(final SwaptionPhysicalFixedIbor swaption, final LiborMarketModelDisplacedDiffusionDataBundle lmmBundle) { // 1. Swaption CFE preparation AnnuityPaymentFixed cfe = CFEC.visit(swaption.getUnderlyingSwap(), lmmBundle); YieldAndDiscountCurve dsc = lmmBundle.getCurve(cfe.getDiscountCurve()); int nbCFInit = cfe.getNumberOfPayments(); double multFact = Math.signum(cfe.getNthPayment(0).getAmount()); boolean isCall = (cfe.getNthPayment(0).getAmount() < 0); double[] cftInit = new double[nbCFInit]; double[] cfaInit = new double[nbCFInit]; for (int loopcf = 0; loopcf < nbCFInit; loopcf++) { cftInit[loopcf] = cfe.getNthPayment(loopcf).getPaymentTime(); cfaInit[loopcf] = cfe.getNthPayment(loopcf).getAmount() * -multFact; } double timeToExpiry = swaption.getTimeToExpiry(); // 2. Model data int nbFactor = lmmBundle.getLmmParameter().getNbFactor(); double[][] volLMM = lmmBundle.getLmmParameter().getVolatility(); double[] timeLMM = lmmBundle.getLmmParameter().getIborTime(); // 3. Link cfe dates to lmm int[] indCFDate = new int[nbCFInit]; int indStart = nbCFInit - 1; int indEnd = 0; for (int loopcf = 0; loopcf < nbCFInit; loopcf++) { indCFDate[loopcf] = Arrays.binarySearch(timeLMM, cftInit[loopcf]); if (indCFDate[loopcf] < 0) { if (timeLMM[-indCFDate[loopcf] - 1] - cftInit[loopcf] < TIME_TOLERANCE) { indCFDate[loopcf] = -indCFDate[loopcf] - 1; } else { if (cftInit[loopcf] - timeLMM[-indCFDate[loopcf] - 2] < TIME_TOLERANCE) { indCFDate[loopcf] = -indCFDate[loopcf] - 2; } else { Validate.isTrue(true, "Instrument time incompatible with LMM"); //TODO really? } } } if (indCFDate[loopcf] < indStart) { indStart = indCFDate[loopcf]; } if (indCFDate[loopcf] > indEnd) { indEnd = indCFDate[loopcf]; } } int nbCF = indEnd - indStart + 1; double[] cfa = new double[nbCF]; for (int loopcf = 0; loopcf < nbCFInit; loopcf++) { cfa[indCFDate[loopcf] - indStart] = cfaInit[loopcf]; } double[] cft = new double[nbCF]; System.arraycopy(timeLMM, indStart, cft, 0, nbCF); double[] dfLMM = new double[nbCF]; for (int loopcf = 0; loopcf < nbCF; loopcf++) { dfLMM[loopcf] = dsc.getDiscountFactor(cft[loopcf]); } double[][] gammaLMM = new double[nbCF - 1][nbFactor]; double[] deltaLMM = new double[nbCF - 1]; System.arraycopy(lmmBundle.getLmmParameter().getAccrualFactor(), indStart, deltaLMM, 0, nbCF - 1); double[] aLMM = new double[nbCF - 1]; System.arraycopy(lmmBundle.getLmmParameter().getDisplacement(), indStart, aLMM, 0, nbCF - 1); double[] liborLMM = new double[nbCF - 1]; double amr = lmmBundle.getLmmParameter().getMeanReversion(); for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) { gammaLMM[loopcf] = volLMM[indStart + loopcf]; liborLMM[loopcf] = (dfLMM[loopcf] / dfLMM[loopcf + 1] - 1.0d) / deltaLMM[loopcf]; } // TODO: 4. cfe modification (for roller coasters) double[] cfaMod = new double[nbCF + 1]; double cfaMod0 = cfa[0]; cfaMod[0] = cfaMod0; // modified strike cfaMod[1] = 0.0; System.arraycopy(cfa, 1, cfaMod, 2, nbCF - 1); // 5. Pricing algorithm double[] p0 = new double[nbCF]; double[] dP = new double[nbCF]; double b0 = 0; for (int loopcf = 0; loopcf < nbCF; loopcf++) { p0[loopcf] = dfLMM[loopcf] / dfLMM[0]; dP[loopcf] = cfaMod[loopcf + 1] * p0[loopcf]; b0 += dP[loopcf]; } double bK = -cfaMod0; double bM = (b0 + bK) / 2.0d; double meanReversionImpact = Math.abs(amr) < 1.0E-6 ? timeToExpiry : (Math.exp(2.0d * amr * timeToExpiry) - 1.0d) / (2.0d * amr); // To handle 0 mean reversion. double[] rate0Ratio = new double[nbCF - 1]; double[][] mu0 = new double[nbCF - 1][nbFactor]; for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) { rate0Ratio[loopcf] = (liborLMM[loopcf] + aLMM[loopcf]) / (liborLMM[loopcf] + 1 / deltaLMM[loopcf]); } for (int loopfact = 0; loopfact < nbFactor; loopfact++) { mu0[0][loopfact] = rate0Ratio[0] * gammaLMM[0][loopfact]; } for (int loopcf = 1; loopcf < nbCF - 1; loopcf++) { for (int loopfact = 0; loopfact < nbFactor; loopfact++) { mu0[loopcf][loopfact] = mu0[loopcf - 1][loopfact] + rate0Ratio[loopcf] * gammaLMM[loopcf][loopfact]; } } double[] tau = new double[nbCF]; double[] tau2 = new double[nbCF]; for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) { for (int loopfact = 0; loopfact < nbFactor; loopfact++) { tau2[loopcf + 1] += mu0[loopcf][loopfact] * mu0[loopcf][loopfact]; } tau2[loopcf + 1] = tau2[loopcf + 1] * meanReversionImpact; tau[loopcf + 1] = Math.sqrt(tau2[loopcf + 1]); } double sumNum = -bM; double sumDen = 0; for (int loopcf = 0; loopcf < nbCF; loopcf++) { sumNum += dP[loopcf] - dP[loopcf] * tau2[loopcf] / 2.0; sumDen += dP[loopcf] * tau[loopcf]; } double xBar = sumNum / sumDen; double[] pM = new double[nbCF]; for (int loopcf = 0; loopcf < nbCF; loopcf++) { pM[loopcf] = p0[loopcf] * (1 - xBar * tau[loopcf] - tau2[loopcf] / 2.0); } double[] liborM = new double[nbCF - 1]; double[] alphaM = new double[nbCF]; for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) { liborM[loopcf] = (pM[loopcf] / pM[loopcf + 1] - 1.0d) / deltaLMM[loopcf]; } for (int loopcf = 0; loopcf < nbCF; loopcf++) { alphaM[loopcf] = cfaMod[loopcf + 1] * pM[loopcf] / bM; } double[] rateMRatio = new double[nbCF - 1]; double[][] muM = new double[nbCF - 1][nbFactor]; for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) { rateMRatio[loopcf] = (liborM[loopcf] + aLMM[loopcf]) / (liborM[loopcf] + 1 / deltaLMM[loopcf]); } for (int loopfact = 0; loopfact < nbFactor; loopfact++) { muM[0][loopfact] = rateMRatio[0] * gammaLMM[0][loopfact]; } for (int loopcf = 1; loopcf < nbCF - 1; loopcf++) { for (int loopfact = 0; loopfact < nbFactor; loopfact++) { muM[loopcf][loopfact] = muM[loopcf - 1][loopfact] + rateMRatio[loopcf] * gammaLMM[loopcf][loopfact]; } } double normSigmaM = 0; double[] sigmaM = new double[nbFactor]; for (int loopfact = 0; loopfact < nbFactor; loopfact++) { for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) { sigmaM[loopfact] += alphaM[loopcf + 1] * muM[loopcf][loopfact]; } normSigmaM += sigmaM[loopfact] * sigmaM[loopfact]; } double impliedBlackVol = Math.sqrt(normSigmaM * meanReversionImpact); EuropeanVanillaOption option = new EuropeanVanillaOption(bK, 1, isCall); final BlackPriceFunction blackFunction = new BlackPriceFunction(); final BlackFunctionData dataBlack = new BlackFunctionData(b0, 1.0, impliedBlackVol); final Function1D<BlackFunctionData, Double> func = blackFunction.getPriceFunction(option); final double pv = dfLMM[0] * func.evaluate(dataBlack); return CurrencyAmount.of(swaption.getUnderlyingSwap().getFirstLeg().getCurrency(), pv * (swaption.isLong() ? 1.0 : -1.0)); }
From source file:com.itemanalysis.psychometrics.cmh.CochranMantelHaenszel.java
/** * Computes 95% confidence interval for the common odds ratio. * Used in computation of ETS DIF classification for binary items. * * @param commonOddsRatio/* ww w.ja v a 2 s . c o m*/ * @return */ public double[] commonOddsRatioConfidenceInterval(double commonOddsRatio) { if (ci != null) return ci; ci = new double[2]; double var = commonOddsRatioVariance(); double sigma = Math.sqrt(var); ci[0] = commonOddsRatio * Math.exp(-1.96 * sigma); ci[1] = commonOddsRatio * Math.exp(1.96 * sigma); return ci; }
From source file:com.genentech.application.property.SDFCalculate.java
private void calcProperties(OEGraphMol mol, Vector<String> propsList) { TPSA myTPSA = new TPSA(); int numHeavy = 0; int hPolar_neu = 0; double tpsa = 0.0; double mw = 0; int LipinskiHBA = 0, LipinskiHBD = 0; int aromaticRingCount = 0, carboAromaticRingCount = 0, aliphaticRingCount = 0, carboAliphaticRingCount = 0; final double R = 8.314510, J2kcal = 0.001 * (1. / 4.184), T = 300.0, RT = R * J2kcal * T; // assign OEChem default aromatic model and hybridazation oechem.OEAssignAromaticFlags(mol);/*from w ww . j a v a 2 s. c o m*/ oechem.OEAssignHybridization(mol); // transform molecule to protonateCNOS and deprotonateNP // explicit hydrogens are added to neutralMol OEGraphMol neutralMol = neutralizeMol(mol); // convert neutralMol to smiles, print smiles //String cansmi = oechem.OECreateSmiString(neutralMol); //System.err.println("SMILES: " + cansmi); //TPSA RotBonds H_polar N O NH OH Heavy_Atoms Rings MW RO5 cLogP_read Charge if (propsList.contains("TPSA") || propsList.contains("CNS_MPO") || propsList.contains("all")) { tpsa = myTPSA.calculateTPSA(neutralMol, countP, countS); if (tpsa <= 0.0) tpsa = 0.0; oechem.OESetSDData(mol, "TPSA", Integer.toString((int) tpsa)); } if (propsList.contains("Charge") || propsList.contains("all")) { int netCharge = oechem.OENetCharge(mol); oechem.OESetSDData(mol, "Charge", Integer.toString(netCharge)); } if (propsList.contains("RotBonds") || propsList.contains("all")) { /* use SMARTS to calculate the following properties */ int singleBonds = SmartsSearch.search(mol, smartsMap.get("SingleBond")); int amideCount = SmartsSearch.search(mol, smartsMap.get("Amide")); int tripleBondCount = SmartsSearch.search(mol, smartsMap.get("TripleBondAtom")); int rotBonds = singleBonds - amideCount - tripleBondCount; oechem.OESetSDData(mol, "RotBonds", Integer.toString(rotBonds)); } if (propsList.contains("Rings") || propsList.contains("all")) { //oechem.OEFindRingAtomsAndBonds(mol); // doesn't seem to be necessary int numRings = oechem.OEDetermineRingSystems(mol, new int[mol.GetMaxAtomIdx()]); oechem.OESetSDData(mol, "Rings", Integer.toString(numRings)); } if (propsList.contains("Heavy_Atoms") || propsList.contains("cIC50atLE0.3") || propsList.contains("all")) { numHeavy = SmartsSearch.search(mol, smartsMap.get("HeavyAtom")); oechem.OESetSDData(mol, "Heavy_Atoms", Integer.toString(numHeavy)); } if (propsList.contains("cIC50atLE0.3") || propsList.contains("all")) { double cIC50atLE0_3 = Math.exp((-1.0 * 0.3 * numHeavy) / RT) * 1000000; // multiply by 1000000 to convert to uM units oechem.OESetSDData(mol, "cIC50atLE0.3", String.format("%.5f", cIC50atLE0_3)); } if (propsList.contains("cIC50atLE0.35") || propsList.contains("all")) { double cIC50atLE0_3 = Math.exp((-1.0 * 0.35 * numHeavy) / RT) * 1000000; // multiply by 1000000 to convert to uM units oechem.OESetSDData(mol, "cIC50atLE0.35", String.format("%.5f", cIC50atLE0_3)); } if (propsList.contains("cIC50atLE0.4") || propsList.contains("all")) { double cIC50atLE0_3 = Math.exp((-1.0 * 0.4 * numHeavy) / RT) * 1000000; // multiply by 1000000 to convert to uM units oechem.OESetSDData(mol, "cIC50atLE0.4", String.format("%.5f", cIC50atLE0_3)); } if (propsList.contains("NH+OH") || propsList.contains("RO5") || propsList.contains("CNS_MPO") || propsList.contains("all")) { hPolar_neu = countHPolar(neutralMol); LipinskiHBD = hPolar_neu; oechem.OESetSDData(mol, "NH+OH", Integer.toString(hPolar_neu)); } if (propsList.contains("H_polar") || propsList.contains("all")) { int hPolar = countHPolar(mol); oechem.OESetSDData(mol, "H_polar", Integer.toString(hPolar)); } if (propsList.contains("N+O") || propsList.contains("RO5") || propsList.contains("all")) { int nCount = SmartsSearch.search(mol, smartsMap.get("NCount")); int oCount = SmartsSearch.search(mol, smartsMap.get("OCount")); LipinskiHBA = nCount + oCount; oechem.OESetSDData(mol, "N+O", String.format("%d", LipinskiHBA)); } if (propsList.contains("MW") || propsList.contains("CNS_MPO") || propsList.contains("RO5") || propsList.contains("all")) { mw = oechem.OECalculateMolecularWeight(neutralMol, true); oechem.OESetSDData(mol, "MW", String.format("%.2f ", mw)); } if (propsList.contains("AromaticRings") || propsList.contains("HeteroAromaticRings") || propsList.contains("Solubility_Index") || propsList.contains("all")) { int aCount = SmartsSearch.search(mol, smartsMap.get("Aromatic5Rings")); aCount += SmartsSearch.search(mol, smartsMap.get("Aromatic6Rings")); aCount += SmartsSearch.search(mol, smartsMap.get("Aromatic7Rings")); aromaticRingCount = aCount; oechem.OESetSDData(mol, "AromaticRings", String.format("%d", aCount)); } if (propsList.contains("CarboAromaticRings") || propsList.contains("HeteroAromaticRings") || propsList.contains("all")) { int caCount = SmartsSearch.search(mol, smartsMap.get("CarboAromatic5Rings")); caCount += SmartsSearch.search(mol, smartsMap.get("CarboAromatic6Rings")); caCount += SmartsSearch.search(mol, smartsMap.get("CarboAromatic7Rings")); carboAromaticRingCount = caCount; oechem.OESetSDData(mol, "CarboAromaticRings", String.format("%d", caCount)); } if (propsList.contains("HeteroAromaticRings") || propsList.contains("all")) { int haCount = aromaticRingCount - carboAromaticRingCount; oechem.OESetSDData(mol, "HeteroAromaticRings", String.format("%d", haCount)); } if (propsList.contains("AliphaticRings") || propsList.contains("HeteroAliphaticRings") || propsList.contains("all")) { int aCount = SmartsSearch.searchAliphaticRings(mol, smartsMap.get("Aliphatic3Rings")); aCount += SmartsSearch.searchAliphaticRings(mol, smartsMap.get("Aliphatic4Rings")); aCount += SmartsSearch.searchAliphaticRings(mol, smartsMap.get("Aliphatic5Rings")); aCount += SmartsSearch.searchAliphaticRings(mol, smartsMap.get("Aliphatic6Rings")); aCount += SmartsSearch.searchAliphaticRings(mol, smartsMap.get("Aliphatic7Rings")); aCount += SmartsSearch.searchAliphaticRings(mol, smartsMap.get("Aliphatic8Rings")); aliphaticRingCount = aCount; oechem.OESetSDData(mol, "AliphaticRings", String.format("%d", aCount)); } if (propsList.contains("CarboAliphaticRings") || propsList.contains("HeteroAliphaticRings") || propsList.contains("all")) { int aCount = SmartsSearch.searchAliphaticRings(mol, smartsMap.get("CarboAliphatic3Rings")); aCount += SmartsSearch.searchAliphaticRings(mol, smartsMap.get("CarboAliphatic4Rings")); aCount += SmartsSearch.searchAliphaticRings(mol, smartsMap.get("CarboAliphatic5Rings")); aCount += SmartsSearch.searchAliphaticRings(mol, smartsMap.get("CarboAliphatic6Rings")); aCount += SmartsSearch.searchAliphaticRings(mol, smartsMap.get("CarboAliphatic7Rings")); aCount += SmartsSearch.searchAliphaticRings(mol, smartsMap.get("CarboAliphatic8Rings")); carboAliphaticRingCount = aCount; oechem.OESetSDData(mol, "CarboAliphaticRings", String.format("%d", aCount)); } if (propsList.contains("HeteroAliphaticRings") || propsList.contains("all")) { int count = aliphaticRingCount - carboAliphaticRingCount; oechem.OESetSDData(mol, "HeteroAliphaticRings", String.format("%d", count)); } if (propsList.contains("AromaticFraction") || propsList.contains("all")) { int aCount = SmartsSearch.search(mol, smartsMap.get("AromaticAtom")); int heavyCount = SmartsSearch.search(mol, smartsMap.get("HeavyAtom")); double aromaticFraction = aCount / (heavyCount + 0.001); // so you don't divide by zero oechem.OESetSDData(mol, "AromaticFraction", String.format("%.2f", aromaticFraction)); } if (propsList.contains("CarboAromaticFraction") || propsList.contains("all")) { int cCount = SmartsSearch.search(mol, smartsMap.get("AromaticCarbonAtom")); int heavyCount = SmartsSearch.search(mol, smartsMap.get("HeavyAtom")); double carboAromaticFraction = cCount / (heavyCount + 0.001); // so you don't divide by zero oechem.OESetSDData(mol, "CarboAromaticFraction", String.format("%.2f", carboAromaticFraction)); } if (propsList.contains("NonSp3Fraction") || propsList.contains("all")) { int nonSp3Count = SmartsSearch.search(mol, smartsMap.get("sp3")); int heavyCount = SmartsSearch.search(mol, smartsMap.get("HeavyAtom")); double nonSp3Fraction = (heavyCount - nonSp3Count) / (heavyCount + 0.001); // so you don't divide by zero oechem.OESetSDData(mol, "NonSp3Fraction", String.format("%.2f", nonSp3Fraction)); } if (propsList.contains("CarboAromaticRings") || propsList.contains("HetereoAromaticRings") || propsList.contains("all")) { int caCount = SmartsSearch.search(mol, smartsMap.get("CarboAromatic5Rings")); caCount += SmartsSearch.search(mol, smartsMap.get("CarboAromatic6Rings")); caCount += SmartsSearch.search(mol, smartsMap.get("CarboAromatic7Rings")); carboAromaticRingCount = caCount; oechem.OESetSDData(mol, "CarboAromaticRings", String.format("%d", caCount)); } if (propsList.contains("Csp3") || propsList.contains("all")) { int count = SmartsSearch.search(mol, smartsMap.get("Csp3")); oechem.OESetSDData(mol, "Csp3", String.format("%d", count)); count = SmartsSearch.search(mol, smartsMap.get("CSsp3")); oechem.OESetSDData(mol, "CSsp3", String.format("%d", count)); count = SmartsSearch.search(mol, smartsMap.get("CS2sp3")); oechem.OESetSDData(mol, "CS2sp3", String.format("%d", count)); } if (propsList.contains("Csp3Fraction") || propsList.contains("all")) { int heavyCount = SmartsSearch.search(mol, smartsMap.get("HeavyAtom")); int count = SmartsSearch.search(mol, smartsMap.get("Csp3")); double Csp3Fraction = (count / (heavyCount + 0.001)); // so you don't divide by zero oechem.OESetSDData(mol, "Csp3Fraction", String.format("%.2f", Csp3Fraction)); } // get cLogP for RO5 and CNS_MPO calculation double cLogP = Double.NaN; if (propsList.contains("RO5") || propsList.contains("CNS_MPO") || propsList.contains("all")) { if (cLogPTag != null) { if (oechem.OEHasSDData(mol, cLogPTag)) { try { cLogP = Double.valueOf(oechem.OEGetSDData(mol, cLogPTag)); } catch (Exception e) { System.err.println(mol.GetTitle() + " " + oechem.OEGetSDData(mol, cLogPTag)); } } } } //get cLogD74 for CNS_MPO and Solubility_index calculation double cLogD74 = Double.NaN; if (propsList.contains("CNS_MPO") || propsList.contains("Solubility_Index") || propsList.contains("all")) { if (oechem.OEHasSDData(mol, CLOGD74_Tag)) { try { cLogD74 = Double.valueOf(oechem.OEGetSDData(mol, CLOGD74_Tag)); } catch (Exception e) { System.err.println("mol: " + mol.GetTitle() + " " + CLOGD74_Tag + ": " + oechem.OEGetSDData(mol, CLOGD74_Tag)); cLogD74 = Double.NaN; } } } if (propsList.contains("Solubility_Index") || propsList.contains("all")) { if (Double.isNaN(cLogD74)) { // do Solubility_Index if cLogD74 is not found System.err.println("mol: " + mol.GetTitle() + " Solubility_Index error, cLogD74 is not defined"); } else { double solIdx = cLogD74 + aromaticRingCount; oechem.OESetSDData(mol, "Solubility_Index", String.format("%.1f", solIdx)); } } if (propsList.contains("RO5") || propsList.contains("all")) { /*rule of Five violations, include cLogP if it is provided */ int ruleOf5Violation = 0; if (mw > 500.0) ruleOf5Violation++; if (LipinskiHBA > 10) ruleOf5Violation++; if (LipinskiHBD > 5) ruleOf5Violation++; if (cLogP > 5.0) ruleOf5Violation++; if (Double.isNaN(cLogP)) { // do not calculate RO5 violation if cLogP is not found System.err.println("mol: " + mol.GetTitle() + " RO5 error: cLogP is not defined"); } else { oechem.OESetSDData(mol, "RO5", Integer.toString(ruleOf5Violation)); } } if (propsList.contains("CNS_MPO") || propsList.contains("all")) { double c_pKa_MB = Double.NaN; String c_pKa_MB_Tag = "c_pKa_MB"; // if c_pKa_MB does not exist, add one to CNS_MPO score if (oechem.OEHasSDData(mol, c_pKa_MB_Tag)) { try { c_pKa_MB = Double.valueOf(oechem.OEGetSDData(mol, c_pKa_MB_Tag)); } catch (Exception e) { System.err.println( "mol: " + mol.GetTitle() + " c_pKa_MB: " + oechem.OEGetSDData(mol, c_pKa_MB_Tag)); c_pKa_MB = Double.NaN; } } else { c_pKa_MB = 0.0; // the step function will assign a CNS_MPO_pKa score of 1 for this pka_MB value } if (Double.isNaN(cLogP) || Double.isNaN(cLogD74) || Double.isNaN(c_pKa_MB)) { //oechem.OESetSDData(mol, "CNS_MPO_score", "error"); System.err.println("mol: " + mol.GetTitle() + " CNS_MPO_score error"); } else { double CNS_MPO_cLogP = StepFunction.linearScore(5, 3, cLogP); double CNS_MPO_cLogD = StepFunction.linearScore(4, 2, cLogD74); double CNS_MPO_MW = StepFunction.linearScore(500, 360, mw); double CNS_MPO_TPSA = StepFunction.humpScore(20, 40, 90, 120, tpsa); double CNS_MPO_HBD = StepFunction.linearScore(3.5, 0.5, hPolar_neu); double CNS_MPO_pKa = StepFunction.linearScore(10, 8, c_pKa_MB); double CNS_MPO = CNS_MPO_cLogP + CNS_MPO_cLogD + CNS_MPO_MW + CNS_MPO_TPSA + CNS_MPO_HBD + CNS_MPO_pKa; oechem.OESetSDData(mol, "CNS_MPO_score", String.format("%.2f", CNS_MPO)); // store MPO scores for the individual parts oechem.OESetSDData(mol, "CNS_MPO_cLogP", String.format("%.2f", CNS_MPO_cLogP)); oechem.OESetSDData(mol, "CNS_MPO_cLogD", String.format("%.2f", CNS_MPO_cLogD)); oechem.OESetSDData(mol, "CNS_MPO_MW", String.format("%.2f", CNS_MPO_MW)); oechem.OESetSDData(mol, "CNS_MPO_TPSA", String.format("%.2f", CNS_MPO_TPSA)); oechem.OESetSDData(mol, "CNS_MPO_HBD", String.format("%.2f", CNS_MPO_HBD)); oechem.OESetSDData(mol, "CNS_MPO_pKa", String.format("%.2f", CNS_MPO_pKa)); } } }