Example usage for java.lang Math random

List of usage examples for java.lang Math random

Introduction

In this page you can find the example usage for java.lang Math random.

Prototype

public static double random() 

Source Link

Document

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0 .

Usage

From source file:com.hurence.tmp.FFT.java

/**
 * *******************************************************************
 * Test client and sample execution// w  ww .ja v a  2  s.c o m
 *
 * % java FFT 4 x ------------------- -0.03480425839330703
 * 0.07910192950176387 0.7233322451735928 0.1659819820667019
 *
 * y = fft(x) ------------------- 0.9336118983487516 -0.7581365035668999 +
 * 0.08688005256493803i 0.44344407521182005 -0.7581365035668999 -
 * 0.08688005256493803i
 *
 * z = ifft(y) ------------------- -0.03480425839330703 0.07910192950176387
 * + 2.6599344570851287E-18i 0.7233322451735928 0.1659819820667019 -
 * 2.6599344570851287E-18i
 *
 * c = cconvolve(x, x) ------------------- 0.5506798633981853
 * 0.23461407150576394 - 4.033186818023279E-18i -0.016542951108772352
 * 0.10288019294318276 + 4.033186818023279E-18i
 *
 * d = convolve(x, x) ------------------- 0.001211336402308083 -
 * 3.122502256758253E-17i -0.005506167987577068 - 5.058885073636224E-17i
 * -0.044092969479563274 + 2.1934338938072244E-18i 0.10288019294318276 -
 * 3.6147323062478115E-17i 0.5494685269958772 + 3.122502256758253E-17i
 * 0.240120239493341 + 4.655566391833896E-17i 0.02755001837079092 -
 * 2.1934338938072244E-18i 4.01805098805014E-17i
 *
 ********************************************************************
 */
public static void main(String[] args) {
    int N = 4; //Integer.parseInt(args[0]);
    Complex[] x = new Complex[N];

    // original data
    for (int i = 0; i < N; i++) {
        x[i] = new Complex(i, 0);
        x[i] = new Complex(-2 * Math.random() + 1, 0);
    }
    show(x, "x");

    // FFT of original data
    Complex[] y = fft(x);
    show(y, "y = fft(x)");

    // take inverse FFT
    Complex[] z = ifft(y);
    show(z, "z = ifft(y)");

    // circular convolution of x with itself
    Complex[] c = cconvolve(x, x);
    show(c, "c = cconvolve(x, x)");

    // linear convolution of x with itself
    Complex[] d = convolve(x, x);
    show(d, "d = convolve(x, x)");
}

From source file:com.era7.bioinfo.annotation.AutomaticQualityControl.java

public static void main(String[] args) {

    if (args.length != 4) {
        System.out.println("This program expects four parameters: \n" + "1. Gene annotation XML filename \n"
                + "2. Reference protein set (.fasta)\n" + "3. Output TXT filename\n"
                + "4. Initial Blast XML results filename (the one used at the very beginning of the semiautomatic annotation process)\n");
    } else {//from  ww w .  j a  v a 2s  . c  o m

        BufferedWriter outBuff = null;

        try {

            File inFile = new File(args[0]);
            File fastaFile = new File(args[1]);
            File outFile = new File(args[2]);
            File blastFile = new File(args[3]);

            //Primero cargo todos los datos del archivo xml del blast
            BufferedReader buffReader = new BufferedReader(new FileReader(blastFile));
            StringBuilder stBuilder = new StringBuilder();
            String line = null;

            while ((line = buffReader.readLine()) != null) {
                stBuilder.append(line);
            }

            buffReader.close();
            System.out.println("Creating blastoutput...");
            BlastOutput blastOutput = new BlastOutput(stBuilder.toString());
            System.out.println("BlastOutput created! :)");
            stBuilder.delete(0, stBuilder.length());

            HashMap<String, String> blastProteinsMap = new HashMap<String, String>();
            ArrayList<Iteration> iterations = blastOutput.getBlastOutputIterations();
            for (Iteration iteration : iterations) {
                blastProteinsMap.put(iteration.getQueryDef().split("\\|")[1].trim(), iteration.toString());
            }
            //freeing some memory
            blastOutput = null;
            //------------------------------------------------------------------------

            //Initializing writer for output file
            outBuff = new BufferedWriter(new FileWriter(outFile));

            //reading gene annotation xml file.....
            buffReader = new BufferedReader(new FileReader(inFile));
            stBuilder = new StringBuilder();
            line = null;
            while ((line = buffReader.readLine()) != null) {
                stBuilder.append(line);
            }
            buffReader.close();

            XMLElement genesXML = new XMLElement(stBuilder.toString());
            //freeing some memory I don't need anymore
            stBuilder.delete(0, stBuilder.length());

            //reading file with the reference proteins set
            ArrayList<String> proteinsReferenceSet = new ArrayList<String>();
            buffReader = new BufferedReader(new FileReader(fastaFile));
            while ((line = buffReader.readLine()) != null) {
                if (line.charAt(0) == '>') {
                    proteinsReferenceSet.add(line.split("\\|")[1]);
                }
            }
            buffReader.close();

            Element pGenes = genesXML.asJDomElement().getChild(PredictedGenes.TAG_NAME);

            List<Element> contigs = pGenes.getChildren(ContigXML.TAG_NAME);

            System.out.println("There are " + contigs.size() + " contigs to be checked... ");

            outBuff.write("There are " + contigs.size() + " contigs to be checked... \n");
            outBuff.write("Proteins reference set: \n");
            for (String st : proteinsReferenceSet) {
                outBuff.write(st + ",");
            }
            outBuff.write("\n");

            for (Element elem : contigs) {
                ContigXML contig = new ContigXML(elem);

                //escribo el id del contig en el que estoy
                outBuff.write("Checking contig: " + contig.getId() + "\n");
                outBuff.flush();

                List<XMLElement> geneList = contig.getChildrenWith(PredictedGene.TAG_NAME);
                System.out.println("geneList.size() = " + geneList.size());

                int numeroDeGenesParaAnalizar = geneList.size() / FACTOR;
                if (numeroDeGenesParaAnalizar == 0) {
                    numeroDeGenesParaAnalizar++;
                }

                ArrayList<Integer> indicesUtilizados = new ArrayList<Integer>();

                outBuff.write("\nThe contig has " + geneList.size() + " predicted genes, let's analyze: "
                        + numeroDeGenesParaAnalizar + "\n");

                for (int j = 0; j < numeroDeGenesParaAnalizar; j++) {
                    int geneIndex;

                    boolean geneIsDismissed = false;
                    do {
                        geneIsDismissed = false;
                        geneIndex = (int) Math.round(Math.floor(Math.random() * geneList.size()));
                        PredictedGene tempGene = new PredictedGene(geneList.get(geneIndex).asJDomElement());
                        if (tempGene.getStatus().equals(PredictedGene.STATUS_DISMISSED)) {
                            geneIsDismissed = true;
                        }
                    } while (indicesUtilizados.contains(new Integer(geneIndex)) && geneIsDismissed);

                    indicesUtilizados.add(geneIndex);
                    System.out.println("geneIndex = " + geneIndex);

                    //Ahora hay que sacar el gen correspondiente al indice y hacer el control de calidad
                    PredictedGene gene = new PredictedGene(geneList.get(geneIndex).asJDomElement());

                    outBuff.write("\nAnalyzing gene with id: " + gene.getId() + " , annotation uniprot id: "
                            + gene.getAnnotationUniprotId() + "\n");
                    outBuff.write("eValue: " + gene.getEvalue() + "\n");

                    //--------------PETICION POST HTTP BLAST----------------------
                    PostMethod post = new PostMethod(BLAST_URL);
                    post.addParameter("program", "blastx");
                    post.addParameter("sequence", gene.getSequence());
                    post.addParameter("database", "uniprotkb");
                    post.addParameter("email", "ppareja@era7.com");
                    post.addParameter("exp", "1e-10");
                    post.addParameter("stype", "dna");

                    // execute the POST
                    HttpClient client = new HttpClient();
                    int status = client.executeMethod(post);
                    System.out.println("status post = " + status);
                    InputStream inStream = post.getResponseBodyAsStream();

                    String fileName = "jobid.txt";
                    FileOutputStream outStream = new FileOutputStream(new File(fileName));
                    byte[] buffer = new byte[1024];
                    int len;

                    while ((len = inStream.read(buffer)) != -1) {
                        outStream.write(buffer, 0, len);
                    }
                    outStream.close();

                    //Once the file is created I just have to read one line in order to extract the job id
                    buffReader = new BufferedReader(new FileReader(new File(fileName)));
                    String jobId = buffReader.readLine();
                    buffReader.close();

                    System.out.println("jobId = " + jobId);

                    //--------------HTTP CHECK JOB STATUS REQUEST----------------------
                    GetMethod get = new GetMethod(CHECK_JOB_STATUS_URL + jobId);
                    String jobStatus = "";
                    do {

                        try {
                            Thread.sleep(1000);//sleep for 1000 ms                                
                        } catch (InterruptedException ie) {
                            //If this thread was intrrupted by nother thread
                        }

                        status = client.executeMethod(get);
                        //System.out.println("status get = " + status);

                        inStream = get.getResponseBodyAsStream();

                        fileName = "jobStatus.txt";
                        outStream = new FileOutputStream(new File(fileName));

                        while ((len = inStream.read(buffer)) != -1) {
                            outStream.write(buffer, 0, len);
                        }
                        outStream.close();

                        //Once the file is created I just have to read one line in order to extract the job id
                        buffReader = new BufferedReader(new FileReader(new File(fileName)));
                        jobStatus = buffReader.readLine();
                        //System.out.println("jobStatus = " + jobStatus);
                        buffReader.close();

                    } while (!jobStatus.equals(FINISHED_JOB_STATUS));

                    //Once I'm here the blast should've already finished

                    //--------------JOB RESULTS HTTP REQUEST----------------------
                    get = new GetMethod(JOB_RESULT_URL + jobId + "/out");

                    status = client.executeMethod(get);
                    System.out.println("status get = " + status);

                    inStream = get.getResponseBodyAsStream();

                    fileName = "jobResults.txt";
                    outStream = new FileOutputStream(new File(fileName));

                    while ((len = inStream.read(buffer)) != -1) {
                        outStream.write(buffer, 0, len);
                    }
                    outStream.close();

                    //--------parsing the blast results file-----

                    TreeSet<GeneEValuePair> featuresBlast = new TreeSet<GeneEValuePair>();

                    buffReader = new BufferedReader(new FileReader(new File(fileName)));
                    while ((line = buffReader.readLine()) != null) {
                        if (line.length() > 3) {
                            String prefix = line.substring(0, 3);
                            if (prefix.equals("TR:") || prefix.equals("SP:")) {
                                String[] columns = line.split(" ");
                                String id = columns[1];
                                //System.out.println("id = " + id);

                                String e = "";

                                String[] arraySt = line.split("\\.\\.\\.");
                                if (arraySt.length > 1) {
                                    arraySt = arraySt[1].trim().split(" ");
                                    int contador = 0;
                                    for (int k = 0; k < arraySt.length && contador <= 2; k++) {
                                        String string = arraySt[k];
                                        if (!string.equals("")) {
                                            contador++;
                                            if (contador == 2) {
                                                e = string;
                                            }
                                        }

                                    }
                                } else {
                                    //Number before e-
                                    String[] arr = arraySt[0].split("e-")[0].split(" ");
                                    String numeroAntesE = arr[arr.length - 1];
                                    String numeroDespuesE = arraySt[0].split("e-")[1].split(" ")[0];
                                    e = numeroAntesE + "e-" + numeroDespuesE;
                                }

                                double eValue = Double.parseDouble(e);
                                //System.out.println("eValue = " + eValue);
                                GeneEValuePair g = new GeneEValuePair(id, eValue);
                                featuresBlast.add(g);
                            }
                        }
                    }

                    GeneEValuePair currentGeneEValuePair = new GeneEValuePair(gene.getAnnotationUniprotId(),
                            gene.getEvalue());

                    System.out.println("currentGeneEValuePair.id = " + currentGeneEValuePair.id);
                    System.out.println("currentGeneEValuePair.eValue = " + currentGeneEValuePair.eValue);
                    boolean blastContainsGene = false;
                    for (GeneEValuePair geneEValuePair : featuresBlast) {
                        if (geneEValuePair.id.equals(currentGeneEValuePair.id)) {
                            blastContainsGene = true;
                            //le pongo la e que tiene en el wu-blast para poder comparar
                            currentGeneEValuePair.eValue = geneEValuePair.eValue;
                            break;
                        }
                    }

                    if (blastContainsGene) {
                        outBuff.write("The protein was found in the WU-BLAST result.. \n");
                        //Una vez que se que esta en el blast tengo que ver que sea la mejor
                        GeneEValuePair first = featuresBlast.first();
                        outBuff.write("Protein with best eValue according to the WU-BLAST result: " + first.id
                                + " , " + first.eValue + "\n");
                        if (first.id.equals(currentGeneEValuePair.id)) {
                            outBuff.write("Proteins with best eValue match up \n");
                        } else {
                            if (first.eValue == currentGeneEValuePair.eValue) {
                                outBuff.write(
                                        "The one with best eValue is not the same protein but has the same eValue \n");
                            } else if (first.eValue > currentGeneEValuePair.eValue) {
                                outBuff.write(
                                        "The one with best eValue is not the same protein but has a worse eValue :) \n");
                            } else {
                                outBuff.write(
                                        "The best protein from BLAST has an eValue smaller than ours, checking if it's part of the reference set...\n");
                                //System.exit(-1);
                                if (proteinsReferenceSet.contains(first.id)) {
                                    //The protein is in the reference set and that shouldn't happen
                                    outBuff.write(
                                            "The protein was found on the reference set, checking if it belongs to the same contig...\n");
                                    String iterationSt = blastProteinsMap.get(gene.getAnnotationUniprotId());
                                    if (iterationSt != null) {
                                        outBuff.write(
                                                "The protein was found in the BLAST used at the beginning of the annotation process.\n");
                                        Iteration iteration = new Iteration(iterationSt);
                                        ArrayList<Hit> hits = iteration.getIterationHits();
                                        boolean contigFound = false;
                                        Hit errorHit = null;
                                        for (Hit hit : hits) {
                                            if (hit.getHitDef().indexOf(contig.getId()) >= 0) {
                                                contigFound = true;
                                                errorHit = hit;
                                                break;
                                            }
                                        }
                                        if (contigFound) {
                                            outBuff.write(
                                                    "ERROR: A hit from the same contig was find in the Blast file: \n"
                                                            + errorHit.toString() + "\n");
                                        } else {
                                            outBuff.write("There is no hit with the same contig! :)\n");
                                        }
                                    } else {
                                        outBuff.write(
                                                "The protein is NOT in the BLAST used at the beginning of the annotation process.\n");
                                    }

                                } else {
                                    //The protein was not found on the reference set so everything's ok
                                    outBuff.write(
                                            "The protein was not found on the reference, everything's ok :)\n");
                                }
                            }
                        }

                    } else {
                        outBuff.write("The protein was NOT found on the WU-BLAST !! :( \n");

                        //System.exit(-1);
                    }

                }

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                //closing outputfile
                outBuff.close();
            } catch (IOException ex) {
                Logger.getLogger(AutomaticQualityControl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
}

From source file:com.actelion.research.spiritcore.util.StatUtils.java

public static void main(String[] args) {
    //      List<Double> list = new ArrayList<Double>();
    ////      list.add(30d); list.add(171d); list.add(184d); list.add(201d); list.add(212d); list.add(250d); list.add(265d); list.add(270d); list.add(272d); list.add(289d); list.add(305d); list.add(306d); list.add(322d); list.add(322d); list.add(336d); list.add(346d); list.add(351d); list.add(370d); list.add(390d); list.add(404d); list.add(409d); list.add(411d); list.add(436d); list.add(437d); list.add(439d); list.add(441d); list.add(444d); list.add(448d); list.add(451d); list.add(453d); list.add(470d); list.add(480d); list.add(482d); list.add(487d); list.add(494d); list.add(495d); list.add(499d); list.add(503d); list.add(514d); list.add(521d); list.add(522d); list.add(527d); list.add(548d); list.add(550d); list.add(559d); list.add(560d); list.add(570d); list.add(572d); list.add(574d); list.add(578d); list.add(585d); list.add(592d); list.add(592d); list.add(607d); list.add(616d); list.add(618d); list.add(621d); list.add(629d); list.add(637d); list.add(638d); list.add(640d); list.add(656d); list.add(668d); list.add(707d); list.add(709d); list.add(719d); list.add(737d); list.add(739d); list.add(752d); list.add(758d); list.add(766d); list.add(792d); list.add(792d); list.add(794d); list.add(802d); list.add(818d); list.add(830d); list.add(832d); list.add(843d); list.add(858d); list.add(860d); list.add(869d); list.add(918d); list.add(925d); list.add(953d); list.add(991d); list.add(1000d); list.add(1005d); list.add(1068d); list.add(1441d); 
    //      list.add(0.0); list.add(156.0); list.add(156.0); list.add(161.0); list.add(176.0); 
    //      //from  ww w  . j av  a  2 s . co m
    //      double[] fences = getFences(list);
    //      System.out.println("median="+getMedian(list));
    //      System.out.println("std="+getStandardDeviationOfMean(list));
    //      System.out.println("fences="+Arrays.toString(fences));

    int count = 0;
    int N = 1000;
    for (int t = 0; t < N; t++) {
        List<double[]> doubles = new ArrayList<double[]>();
        for (int i = 0; i < 3; i++) {
            double[] array = new double[10];
            doubles.add(array);
            for (int j = 0; j < array.length; j++) {
                array[j] = Math.random() * 10;// i<2 || j<10? j: j+100; 
            }
        }
        double r = getKruskalWallis(doubles);
        if (r < 0.05)
            count++;
        System.out.println("[" + t + "] KW=" + r);
    }
    System.out.println("==> percentage of false positive " + (1.0 * count / N) + " ~ 0.05");

}

From source file:netplot.DialPlotPanel.java

/**
 * Starting point for the demo application.
 * /* w ww .j a v  a  2s .com*/
 * @param args  ignored.
 */
public static void main(String[] args) {
    JFrame jf = new JFrame();
    DialPlotPanel dialPlotPanel = new DialPlotPanel();
    try {
        dialPlotPanel.setAttribute(KeyWords.PLOT_TITLE, "Number And MAX");
        dialPlotPanel.setAttribute(KeyWords.PLOT_NAME, "Number");
        dialPlotPanel.setAttribute(KeyWords.TICK_COUNT, "10");
        dialPlotPanel.setAttribute(KeyWords.MIN_SCALE_VALUE, "0");
        dialPlotPanel.setAttribute(KeyWords.MAX_SCALE_VALUE, "150");
        dialPlotPanel.setAttribute(KeyWords.PLOT_NAME, "Number");
        dialPlotPanel.addPlot();
        dialPlotPanel.setAttribute(KeyWords.PLOT_NAME, "MAX");
        dialPlotPanel.setAttribute(KeyWords.MIN_SCALE_VALUE, "-20");
        dialPlotPanel.addPlot();

        jf.getContentPane().add(dialPlotPanel);
        jf.pack();
        jf.setVisible(true);
        double max = -1;
        while (true) {
            double v0 = Math.random() * 50;
            if (max == -1) {
                max = v0;
            }
            if (max < v0) {
                max = v0;
            }
            dialPlotPanel.addPlotValue(0, v0);
            dialPlotPanel.addPlotValue(1, max);
            Thread.sleep(2000);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:no.uio.medicine.virsurveillance.charts.BoxAndWhiskerChart_AWT.java

public static void main(final String[] args) {

    //Log.getInstance().addTarget(new PrintStreamLogTarget(System.out));
    ArrayList<ArrayList<ArrayList<Float>>> dataPoints = new ArrayList<>();
    ArrayList<String> titles = new ArrayList<>();
    ArrayList<ArrayList<String>> categories = new ArrayList<>();

    for (int i = 0; i < 2; i++) {
        ArrayList<ArrayList<Float>> serie = new ArrayList<>();
        titles.add("Serie " + i);

        ArrayList<String> categoriesPerSerie = new ArrayList<>();
        int max = i + 2;
        for (int j = 0; j < max; j++) {
            ArrayList<Float> points = new ArrayList<>();
            for (int k = 0; k < 50; k++) {
                points.add((float) (i * 10 + Math.random() * 50));
            }//w ww . j  a  va2 s  .  c  om
            serie.add(points);
            categoriesPerSerie.add("Categorie" + j);
        }
        dataPoints.add(serie);
        categories.add(categoriesPerSerie);

    }

    final BoxAndWhiskerChart_AWT demo = new BoxAndWhiskerChart_AWT("A", "B", "C", "D", dataPoints, categories,
            titles);

    final BoxAndWhiskerChart_AWT demo2 = new BoxAndWhiskerChart_AWT("A2", "B2", "C2", "D2", dataPoints.get(0),
            categories.get(0), titles.get(0));

    demo.updateChartData();
    demo2.updateChartData();

}

From source file:Main.java

public static int getMyId() {
    int id = (int) (Math.random() * 1000000);
    return id;
}

From source file:Main.java

public static int getRandom(int max) {
    return (int) (Math.random() * max);
}

From source file:Main.java

public static int generaRandom(int size) {
    return (int) (Math.random() * size);
}

From source file:Main.java

public static int randomOrient() {
    return (int) Math.ceil(Math.random() * 360);
}

From source file:Main.java

public static int getRandom(int min, int max) {
    return (int) ((Math.random() * 1000) % max + min);
}