Example usage for java.util Random nextDouble

List of usage examples for java.util Random nextDouble

Introduction

In this page you can find the example usage for java.util Random nextDouble.

Prototype

public double nextDouble() 

Source Link

Document

Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.

Usage

From source file:pt.lsts.neptus.util.tid.TidReader.java

public static void main(String[] args) throws Exception {
    String tmpFolder = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator", "/");
    File tidFx = new File(tmpFolder + "tmp.tid");
    tidFx.delete();//  w w w  .jav a2 s  .c  o  m

    BufferedWriter writer = new BufferedWriter(new FileWriter(tidFx));
    TidWriter tidWriter = new TidWriter(writer, 2);
    tidWriter.writeHeader("Title", "harbor");
    Random rand = new Random(28091893);
    Date date = new GregorianCalendar(1993, 9, 28).getTime();
    for (int i = 0; i < 10; i++) {
        tidWriter.writeData(new Double(date.getTime() + i * 6.45 * 1E3 * 60 * 60).longValue(),
                2.0 * rand.nextDouble());
    }
    tidFx.deleteOnExit();
    writer.close();

    System.out.println("TID Created");
    System.out.println("===========");
    System.out.println(FileUtil.getFileAsString(tidFx));
    System.out.println();
    System.out.println();

    System.out.println("TID Read");
    System.out.println("========");

    BufferedReader reader = new BufferedReader(new FileReader(tidFx));
    TidReader tidReader = new TidReader(reader);
    while (true) {
        Data data = tidReader.readData();
        if (data == null)
            break;
        System.out.println("Data: " + new Date(data.timeMillis) + " depth: " + data.height + " other: "
                + Arrays.toString(data.other));
    }
    System.out.println("Harbor read: " + tidReader.getHarbor());
}

From source file:imp.lstm.main.Driver.java

public static void main(String[] args)
        throws FileNotFoundException, IOException, ConfigurationException, InvalidParametersException {
    FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>(
            PropertiesConfiguration.class).configure(
                    new Parameters().properties().setFileName(args[0]).setThrowExceptionOnMissing(true)
                            .setListDelimiterHandler(new DefaultListDelimiterHandler(';'))
                            .setIncludesAllowed(false));
    Configuration config = builder.getConfiguration();

    String inputSongPath = config.getString("input_song");
    String outputFolderPath = config.getString("output_folder");
    String autoEncoderParamsPath = config.getString("auto_encoder_params");
    String nameGeneratorParamsPath = config.getString("name_generator_params");
    String queueFolderPath = config.getString("queue_folder");
    String referenceQueuePath = config.getString("reference_queue", "nil");
    String inputCorpusFolder = config.getString("input_corpus_folder");
    boolean shouldWriteQueue = config.getBoolean("should_write_generated_queue");
    boolean frankensteinTest = config.getBoolean("queue_tests_frankenstein");
    boolean interpolateTest = config.getBoolean("queue_tests_interpolation");
    boolean iterateOverCorpus = config.getBoolean("iterate_over_corpus", false);
    boolean shouldGenerateSongTitle = config.getBoolean("generate_song_title");
    boolean shouldGenerateSong = config.getBoolean("generate_leadsheet");

    LogTimer.initStartTime(); //start our logging timer to keep track of our execution time
    LogTimer.log("Creating name generator...");

    //here is just silly code for generating name based on an LSTM lol $wag
    LSTM lstm = new LSTM();
    FullyConnectedLayer fullLayer = new FullyConnectedLayer(Operations.None);
    Loadable titleNetLoader = new Loadable() {
        @Override/*w  w  w .jav  a 2  s.  c  om*/
        public boolean load(INDArray array, String path) {
            String car = pathCar(path);
            String cdr = pathCdr(path);
            switch (car) {
            case "full":
                return fullLayer.load(array, cdr);
            case "lstm":
                return lstm.load(array, cdr);
            default:
                return false;
            }
        }
    };

    LogTimer.log("Packing name generator from files...");
    (new NetworkConnectomeLoader()).load(nameGeneratorParamsPath, titleNetLoader);

    String characterString = " !\"'[],-.01245679:?ABCDEFGHIJKLMNOPQRSTUVWYZabcdefghijklmnopqrstuvwxyz";

    //Initialization
    LogTimer.log("Creating autoencoder...");
    int inputSize = 34;
    int outputSize = EncodingParameters.noteEncoder.getNoteLength();
    int featureVectorSize = 100;
    ProductCompressingAutoencoder autoencoder = new ProductCompressingAutoencoder(24, 48, 84 + 1, false); //create our network

    int numInterpolationDivisions = 5;

    //"pack" the network from weights and biases file directory
    LogTimer.log("Packing autoencoder from files");
    (new NetworkConnectomeLoader()).load(autoEncoderParamsPath, autoencoder);

    File[] songFiles;
    if (iterateOverCorpus) {
        songFiles = new File(inputCorpusFolder).listFiles();
    } else {
        songFiles = new File[] { new File(inputSongPath) };
    }
    for (File inputFile : songFiles) {
        (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder, "initialstate");
        String songTitle;
        if (shouldGenerateSong) {
            Random rand = new Random();
            AVector charOut = Vector.createLength(characterString.length());
            GroupedSoftMaxSampler sampler = new GroupedSoftMaxSampler(
                    new Group[] { new Group(0, characterString.length(), true) });
            songTitle = "";
            for (int i = 0; i < 50; i++) {
                charOut = fullLayer.forward(lstm.step(charOut));
                charOut = sampler.filter(charOut);
                int charIndex = 0;
                for (; charIndex < charOut.length(); charIndex++) {
                    if (charOut.get(charIndex) == 1.0) {
                        break;
                    }
                }
                songTitle += characterString.substring(charIndex, charIndex + 1);
            }
            songTitle = songTitle.trim();

            LogTimer.log("Generated song name: " + songTitle);
        } else {
            songTitle = "The Song We Never Name";
        }
        LogTimer.log("Reading file...");
        LeadSheetDataSequence inputSequence = LeadSheetIO.readLeadSheet(inputFile); //read our leadsheet to get a data vessel as retrieved in rbm-provisor
        LeadSheetDataSequence outputSequence = inputSequence.copy();

        outputSequence.clearMelody();
        if (interpolateTest) {
            LeadSheetDataSequence additionalOutput = outputSequence.copy();
            for (int i = 0; i < numInterpolationDivisions; i++) {
                outputSequence.concat(additionalOutput.copy());
            }
        }
        LeadSheetDataSequence decoderInputSequence = outputSequence.copy();

        LogTimer.startLog("Encoding data...");
        //TradingTimer.initStart(); //start our trading timer to keep track our our generation versus realtime play
        while (inputSequence.hasNext()) { //iterate through time steps in input data
            //TradingTimer.waitForNextTimedInput();
            autoencoder.encodeStep(inputSequence.retrieve()); //feed the resultant input vector into the network
            if (advanceDecoding) { //if we are using advance decoding (we start decoding as soon as we can)
                if (autoencoder.canDecode()) { //if queue has enough data to decode from
                    outputSequence.pushStep(null, null,
                            autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                    //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are
                }
            }
        }
        LogTimer.endLog();

        if (shouldWriteQueue) {
            String queueFilePath = queueFolderPath + java.io.File.separator
                    + inputFile.getName().replace(".ls", ".q");
            FragmentedNeuralQueue currQueue = autoencoder.getQueue();
            currQueue.writeToFile(queueFilePath);
            LogTimer.log("Wrote queue " + inputFile.getName().replace(".ls", ".q") + " to file...");
        }
        if (shouldGenerateSong) {
            if (interpolateTest) {

                FragmentedNeuralQueue refQueue = new FragmentedNeuralQueue();
                refQueue.initFromFile(referenceQueuePath);

                FragmentedNeuralQueue currQueue = autoencoder.getQueue();
                //currQueue.writeToFile(queueFilePath);

                autoencoder.setQueue(currQueue.copy());
                while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                    outputSequence.pushStep(null, null,
                            autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                    //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
                }

                for (int i = 1; i <= numInterpolationDivisions; i++) {
                    System.out.println("Starting interpolation " + ((1.0 / numInterpolationDivisions) * (i)));
                    (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder, "initialstate");
                    FragmentedNeuralQueue currCopy = currQueue.copy();
                    currCopy.basicInterpolate(refQueue, (1.0 / numInterpolationDivisions) * (i));
                    autoencoder.setQueue(currCopy);
                    int timeStep = 0;
                    while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                        System.out.println("interpolation " + i + " step " + ++timeStep);
                        outputSequence.pushStep(null, null,
                                autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                        //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
                    }
                }

            }
            if (frankensteinTest) {
                LogTimer.startLog("Loading queues");
                File queueFolder = new File(queueFolderPath);
                int numComponents = config.getInt("frankenstein_num_components", 5);
                int numCombinations = config.getInt("frankenstein_num_combinations", 6);
                double interpolationMagnitude = config.getDouble("frankenstein_magnitude", 2.0);
                if (queueFolder.isDirectory()) {
                    File[] queueFiles = queueFolder.listFiles(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String name) {
                            return name.contains(".q");
                        }
                    });

                    List<File> fileList = new ArrayList<>();
                    for (File file : queueFiles) {
                        fileList.add(file);
                    }
                    Collections.shuffle(fileList);
                    int numSelectedFiles = (numComponents > queueFiles.length) ? queueFiles.length
                            : numComponents;

                    for (int i = 0; i < queueFiles.length - numSelectedFiles; i++) {
                        fileList.remove(fileList.size() - 1);
                    }
                    List<FragmentedNeuralQueue> queuePopulation = new ArrayList<>(fileList.size());
                    songTitle += " - a mix of ";
                    for (File file : fileList) {
                        FragmentedNeuralQueue newQueue = new FragmentedNeuralQueue();
                        newQueue.initFromFile(file.getPath());
                        queuePopulation.add(newQueue);
                        songTitle += file.getName().replaceAll(".ls", "") + ", ";
                    }
                    LogTimer.endLog();

                    LeadSheetDataSequence additionalOutput = outputSequence.copy();
                    for (int i = 1; i < numCombinations; i++) {
                        outputSequence.concat(additionalOutput.copy());
                    }
                    decoderInputSequence = outputSequence.copy();

                    FragmentedNeuralQueue origQueue = autoencoder.getQueue();

                    for (int i = 0; i < numCombinations; i++) {

                        LogTimer.startLog("Performing queue interpolation...");
                        AVector combinationStrengths = Vector.createLength(queuePopulation.size());
                        Random vectorRand = new Random(i);
                        for (int j = 0; j < combinationStrengths.length(); j++) {
                            combinationStrengths.set(j, vectorRand.nextDouble());
                        }
                        combinationStrengths.divide(combinationStrengths.elementSum());
                        FragmentedNeuralQueue currQueue = origQueue.copy();
                        for (int k = 0; k < combinationStrengths.length(); k++) {
                            currQueue.basicInterpolate(queuePopulation.get(k),
                                    combinationStrengths.get(k) * interpolationMagnitude);
                        }
                        LogTimer.endLog();
                        autoencoder.setQueue(currQueue);
                        LogTimer.startLog("Refreshing autoencoder state...");
                        (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder,
                                "initialstate");
                        LogTimer.endLog();
                        LogTimer.startLog("Decoding segment...");
                        while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                            outputSequence.pushStep(null, null,
                                    autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                            //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
                        }
                        LogTimer.endLog();
                    }

                }
            }

            while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                outputSequence.pushStep(null, null, autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
            }
            LogTimer.log("Writing file...");

            String outputFilename = outputFolderPath + java.io.File.separator
                    + inputFile.getName().replace(".ls", "_Output"); //we'll write our generated file with the same name plus "_Output"
            LeadSheetIO.writeLeadSheet(outputSequence, outputFilename, songTitle);
            System.out.println(outputFilename);
        } else {
            autoencoder.setQueue(new FragmentedNeuralQueue());
        }
    }
    LogTimer.log("Process finished"); //Done!

}

From source file:org.apache.kylin.source.kafka.util.KafkaSampleProducer.java

public static void main(String[] args) throws Exception {
    logger.info("args: " + Arrays.toString(args));
    OptionsHelper optionsHelper = new OptionsHelper();
    Options options = new Options();
    String topic, broker;/*from   w  w  w  .  j a  va2  s .com*/
    options.addOption(OPTION_TOPIC);
    options.addOption(OPTION_BROKER);
    options.addOption(OPTION_INTERVAL);
    optionsHelper.parseOptions(options, args);

    logger.info("options: '" + optionsHelper.getOptionsAsString() + "'");

    topic = optionsHelper.getOptionValue(OPTION_TOPIC);
    broker = optionsHelper.getOptionValue(OPTION_BROKER);

    long interval = 10;
    String intervalString = optionsHelper.getOptionValue(OPTION_INTERVAL);
    if (intervalString != null) {
        interval = Long.parseLong(intervalString);
    }

    List<String> countries = new ArrayList();
    countries.add("AUSTRALIA");
    countries.add("CANADA");
    countries.add("CHINA");
    countries.add("INDIA");
    countries.add("JAPAN");
    countries.add("KOREA");
    countries.add("US");
    countries.add("Other");
    List<String> category = new ArrayList();
    category.add("BOOK");
    category.add("TOY");
    category.add("CLOTH");
    category.add("ELECTRONIC");
    category.add("Other");
    List<String> devices = new ArrayList();
    devices.add("iOS");
    devices.add("Windows");
    devices.add("Andriod");
    devices.add("Other");

    List<String> genders = new ArrayList();
    genders.add("Male");
    genders.add("Female");

    Properties props = new Properties();
    props.put("bootstrap.servers", broker);
    props.put("acks", "all");
    props.put("retries", 0);
    props.put("batch.size", 16384);
    props.put("linger.ms", 1);
    props.put("buffer.memory", 33554432);
    props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

    Producer<String, String> producer = new KafkaProducer<>(props);

    boolean alive = true;
    Random rnd = new Random();
    Map<String, Object> record = new HashMap();
    while (alive == true) {
        //add normal record
        record.put("order_time", (new Date().getTime()));
        record.put("country", countries.get(rnd.nextInt(countries.size())));
        record.put("category", category.get(rnd.nextInt(category.size())));
        record.put("device", devices.get(rnd.nextInt(devices.size())));
        record.put("qty", rnd.nextInt(10));
        record.put("currency", "USD");
        record.put("amount", rnd.nextDouble() * 100);
        //add embedded record
        Map<String, Object> user = new HashMap();
        user.put("id", UUID.randomUUID().toString());
        user.put("gender", genders.get(rnd.nextInt(2)));
        user.put("age", rnd.nextInt(20) + 10);
        record.put("user", user);
        //send message
        ProducerRecord<String, String> data = new ProducerRecord<>(topic, System.currentTimeMillis() + "",
                mapper.writeValueAsString(record));
        System.out.println("Sending 1 message: " + JsonUtil.writeValueAsString(record));
        producer.send(data);
        Thread.sleep(interval);
    }
    producer.close();
}

From source file:ffx.numerics.fft.RowMajorComplex3DCuda.java

/**
 * <p>/*from   w  w w .j a  va 2  s  .  c o  m*/
 * main</p>
 *
 * @param args an array of {@link java.lang.String} objects.
 * @throws java.lang.Exception if any.
 */
public static void main(String[] args) throws Exception {
    int dimNotFinal = 64;
    int reps = 10;
    if (args != null) {
        try {
            dimNotFinal = Integer.parseInt(args[0]);
            if (dimNotFinal < 1) {
                dimNotFinal = 64;
            }
            reps = Integer.parseInt(args[2]);
            if (reps < 1) {
                reps = 5;
            }
        } catch (Exception e) {
        }
    }
    final int dim = dimNotFinal;

    System.out.println(String.format(
            " Initializing a %d cubed grid.\n" + " The best timing out of %d repititions will be used.", dim,
            reps));

    final int dimCubed = dim * dim * dim;

    /**
     * Create an array to save the initial input and result.
     */
    double orig[] = new double[dimCubed];
    double answer[] = new double[dimCubed];

    double data[] = new double[dimCubed * 2];
    double recip[] = new double[dimCubed];

    Random random = new Random(1);
    for (int x = 0; x < dim; x++) {
        for (int y = 0; y < dim; y++) {
            for (int z = 0; z < dim; z++) {
                int index = RowMajorComplex3D.iComplex3D(x, y, z, dim, dim);
                orig[index / 2] = random.nextDouble();
                recip[index / 2] = orig[index / 2];
            }
        }
    }

    RowMajorComplex3D complex3D = new RowMajorComplex3D(dim, dim, dim);
    RowMajorComplex3DParallel complex3DParallel = new RowMajorComplex3DParallel(dim, dim, dim,
            new ParallelTeam(), IntegerSchedule.fixed());
    RowMajorComplex3DCuda complex3DCUDA = new RowMajorComplex3DCuda(dim, dim, dim, data, recip);
    Thread cudaThread = new Thread(complex3DCUDA);

    cudaThread.setPriority(Thread.MAX_PRIORITY);
    cudaThread.start();

    double toSeconds = 0.000000001;
    long parTime = Long.MAX_VALUE;
    long seqTime = Long.MAX_VALUE;
    long clTime = Long.MAX_VALUE;

    complex3D.setRecip(recip);
    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            data[j * 2] = orig[j];
            data[j * 2 + 1] = 0.0;
        }
        long time = System.nanoTime();
        complex3D.convolution(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d Sequential: %8.3f", i + 1, toSeconds * time));
        if (time < seqTime) {
            seqTime = time;
        }
    }

    for (int j = 0; j < dimCubed; j++) {
        answer[j] = data[j * 2];
    }

    complex3DParallel.setRecip(recip);
    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            data[j * 2] = orig[j];
            data[j * 2 + 1] = 0.0;
        }
        long time = System.nanoTime();
        complex3DParallel.convolution(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d Parallel:   %8.3f", i + 1, toSeconds * time));
        if (time < parTime) {
            parTime = time;
        }
    }

    double maxError = Double.MIN_VALUE;
    double rmse = 0.0;
    for (int i = 0; i < dimCubed; i++) {
        double error = Math.abs(answer[i] - data[2 * i]);
        if (error > maxError) {
            maxError = error;
        }
        rmse += error * error;
    }
    rmse /= dimCubed;
    rmse = Math.sqrt(rmse);
    logger.info(String.format(" Parallel RMSE:   %12.10f, Max: %12.10f", rmse, maxError));
    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            data[j * 2] = orig[j];
            data[j * 2 + 1] = 0.0;
        }
        long time = System.nanoTime();
        complex3DCUDA.convolution(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d CUDA:     %8.3f", i + 1, toSeconds * time));
        if (time < clTime) {
            clTime = time;
        }
    }

    maxError = Double.MIN_VALUE;
    double avg = 0.0;
    rmse = 0.0;
    for (int i = 0; i < dimCubed; i++) {
        double error = Math.abs((answer[i] - data[2 * i]) / dimCubed);
        avg += error;
        if (error > maxError) {
            maxError = error;
        }
        rmse += error * error;
    }
    rmse /= dimCubed;
    avg /= dimCubed;
    rmse = Math.sqrt(rmse);
    logger.info(String.format(" CUDA RMSE:   %12.10f, Max: %12.10f, Avg: %12.10f", rmse, maxError, avg));

    complex3DCUDA.free();
    complex3DCUDA = null;

    System.out.println(String.format(" Best Sequential Time:  %8.3f", toSeconds * seqTime));
    System.out.println(String.format(" Best Parallel Time:    %8.3f", toSeconds * parTime));
    System.out.println(String.format(" Best CUDA Time:        %8.3f", toSeconds * clTime));
    System.out.println(String.format(" Parallel Speedup: %15.5f", (double) seqTime / parTime));
    System.out.println(String.format(" CUDA Speedup:     %15.5f", (double) seqTime / clTime));
}

From source file:pt.lsts.neptus.mra.importers.deltat.DeltaTParser.java

public static void main(String[] args) {
    try {//ww w . j  a  v a2  s  .c  o  m
        LsfLogSource source = new LsfLogSource(new File(
                // "/home/lsts/Desktop/to_upload_20130715/lauv-noptilus-1/20130715/122455_out_survey/Data.lsf"
                "D:\\LSTS-Logs\\2014-11-09-Madeira\\2014-11-12-Madeira_115528_rows_maneuver_cais2_day3\\Data.lsf.gz"),
                null);
        File fxB = source.getFile("mra/bathy.info");
        if (fxB != null && fxB.exists())
            fxB.delete();
        fxB = source.getFile("mra/deltaT-process.txt");
        if (fxB != null && fxB.exists())
            fxB.delete();
        MRAProperties.generateDeltaTProcessReport = true;
        MRAProperties.soundSpeedCorrection = true;
        DeltaTParser p = new DeltaTParser(source);

        int c = 0;
        BathymetrySwath s;
        while ((s = p.nextSwath()) != null) {
            // // for(BathymetryPoint bp : bs.getData()) {
            // // double r[] = CoordinateUtil.latLonAddNE2(bp.lat, bp.lon, bp.north, bp.east);
            // // float f[] = new float[2];
            // //
            // // f[0] = (float) (r[0] * 1000000f);
            // // f[1] = new Double(r[1]).floatValue();
            // //
            // // NeptusLog.pub().info("<###> "+r[0]);
            // // NeptusLog.pub().info("<###> " + f[0]);
            // // }
            // c++;
            // // kryo.writeObject(output, bs);

            System.out.println(Math.toDegrees(s.getPose().getYaw()));
            c++;
        }
        System.out.println(c);

        long fTs = p.getFirstTimestamp();
        long lTs = p.getLastTimestamp();
        long sTs = lTs - fTs;
        Random rand = new Random();
        for (int i = 0; i < 4; i++) {
            double perc = rand.nextDouble();
            long searchTs = (long) (sTs * perc + fTs);
            long markStart = System.nanoTime();
            BathymetrySwath swath = p.getSwathAt(searchTs);
            long markEnd = System.nanoTime();
            System.out.printf("Search swath at '%s' and got one for time '%s' and took %.3fms\n",
                    DateTimeUtil.dateTimeFormatterUTC.format(new Date(searchTs)),
                    (swath != null ? DateTimeUtil.dateTimeFormatterUTC.format(new Date(swath.getTimestamp()))
                            : "NONE"),
                    (markEnd - markStart) / 1E6);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ffx.numerics.fft.Complex3DCuda.java

/**
 * <p>/*from   w  w w . ja va 2  s.com*/
 * main</p>
 *
 * @param args an array of {@link java.lang.String} objects.
 * @throws java.lang.Exception if any.
 */
public static void main(String[] args) throws Exception {
    int dimNotFinal = 64;
    int reps = 10;
    if (args != null) {
        try {
            dimNotFinal = Integer.parseInt(args[0]);
            if (dimNotFinal < 1) {
                dimNotFinal = 64;
            }
            reps = Integer.parseInt(args[1]);
            if (reps < 1) {
                reps = 10;
            }
        } catch (Exception e) {
        }
    }
    final int dim = dimNotFinal;

    System.out.println(String.format(
            " Initializing a %d cubed grid.\n" + " The best timing out of %d repititions will be used.", dim,
            reps));

    final int dimCubed = dim * dim * dim;

    /**
     * Create an array to save the initial input and result.
     */
    double orig[] = new double[dimCubed];
    double answer[] = new double[dimCubed];
    double data[] = new double[dimCubed * 2];
    double recip[] = new double[dimCubed];

    Random random = new Random(1);
    int index = 0;
    for (int k = 0; k < dim; k++) {
        for (int j = 0; j < dim; j++) {
            for (int i = 0; i < dim; i++) {
                orig[index] = random.nextDouble();
                //recip[index] = orig[index];
                recip[index] = 1.0;
                index++;
            }
        }
    }

    Complex3D complex3D = new Complex3D(dim, dim, dim);
    Complex3DParallel complex3DParallel = new Complex3DParallel(dim, dim, dim, new ParallelTeam(),
            IntegerSchedule.fixed());
    complex3DParallel.setRecip(recip);

    Complex3DCuda complex3DCUDA = new Complex3DCuda(dim, dim, dim);
    Thread cudaThread = new Thread(complex3DCUDA);
    cudaThread.setPriority(Thread.MAX_PRIORITY);
    cudaThread.start();
    complex3DCUDA.setRecip(recip);

    double toSeconds = 0.000000001;
    long parTime = Long.MAX_VALUE;
    long seqTime = Long.MAX_VALUE;
    long clTime = Long.MAX_VALUE;

    complex3D.setRecip(recip);
    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            data[j * 2] = orig[j];
            data[j * 2 + 1] = 0.0;
        }
        long time = System.nanoTime();
        //complex3D.convolution(data);
        complex3D.fft(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d Sequential: %8.3f", i + 1, toSeconds * time));
        if (time < seqTime) {
            seqTime = time;
        }
    }

    for (int j = 0; j < dimCubed; j++) {
        answer[j] = data[j * 2];
    }

    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            data[j * 2] = orig[j];
            data[j * 2 + 1] = 0.0;
        }
        long time = System.nanoTime();
        //complex3DParallel.convolution(data);
        complex3DParallel.fft(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d Parallel:   %8.3f", i + 1, toSeconds * time));
        if (time < parTime) {
            parTime = time;
        }
    }

    double maxError = Double.MIN_VALUE;
    double rmse = 0.0;
    for (int i = 0; i < dimCubed; i++) {
        double error = Math.abs(answer[i] - data[2 * i]);
        if (error > maxError) {
            maxError = error;
        }
        rmse += error * error;
    }
    rmse /= dimCubed;
    rmse = Math.sqrt(rmse);
    logger.info(String.format(" Parallel RMSE:   %12.10f, Max: %12.10f", rmse, maxError));

    DoubleBuffer cudaBuffer = complex3DCUDA.getDoubleBuffer();
    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            // data[j * 2] = orig[j];
            // data[j * 2 + 1] = 0.0;
            cudaBuffer.put(j * 2, orig[j]);
            cudaBuffer.put(j * 2 + 1, 0.0);
        }
        long time = System.nanoTime();
        //complex3DCUDA.convolution(data);
        complex3DCUDA.fft(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d CUDA:     %8.3f", i + 1, toSeconds * time));
        if (time < clTime) {
            clTime = time;
        }
    }

    maxError = Double.MIN_VALUE;
    double avg = 0.0;
    rmse = 0.0;
    for (int i = 0; i < dimCubed; i++) {
        double error = Math.abs(answer[i] - cudaBuffer.get(2 * i));
        // double error = Math.abs(answer[i] / dimCubed -  data[2 * i]);
        avg += error;
        if (error > maxError) {
            maxError = error;
        }
        rmse += error * error;
    }
    rmse /= dimCubed;
    avg /= dimCubed;
    rmse = Math.sqrt(rmse);
    logger.info(String.format(" CUDA RMSE:   %12.10f, Max: %12.10f, Avg: %12.10f", rmse, maxError, avg));

    complex3DCUDA.free();
    complex3DCUDA = null;

    System.out.println(String.format(" Best Sequential Time:  %8.3f", toSeconds * seqTime));
    System.out.println(String.format(" Best Parallel Time:    %8.3f", toSeconds * parTime));
    System.out.println(String.format(" Best CUDA Time:        %8.3f", toSeconds * clTime));
    System.out.println(String.format(" Parallel Speedup: %15.5f", (double) seqTime / parTime));
    System.out.println(String.format(" CUDA Speedup:     %15.5f", (double) seqTime / clTime));
}

From source file:de.codesourcery.flocking.KDTree.java

public static void main(String[] args) {
    final KDTree<Vec2d> tree = new KDTree<Vec2d>();

    Random rnd = new Random(System.currentTimeMillis());
    for (int i = 0; i < 100; i++) {
        final double x = rnd.nextDouble() * MODEL_WIDTH;
        final double y = rnd.nextDouble() * MODEL_HEIGHT;
        tree.add(x, y, new Vec2d(x, y));
    }/* w  ww .j av a 2  s.com*/

    final MyPanel panel = new MyPanel(tree);

    panel.setPreferredSize(new Dimension((int) MODEL_WIDTH * 2, (int) MODEL_HEIGHT * 2));

    panel.addMouseListener(new MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent e) {
            final Vec2d p = panel.viewToModel(e.getX(), e.getY());
            panel.mark(p.x, p.y, 55);
        };
    });

    final JFrame frame = new JFrame("KDTreeTest");

    frame.addKeyListener(new KeyAdapter() {

        public void keyTyped(java.awt.event.KeyEvent e) {
        };
    });
    frame.getContentPane().setLayout(new GridBagLayout());
    final GridBagConstraints cnstrs = new GridBagConstraints();
    cnstrs.fill = GridBagConstraints.BOTH;
    cnstrs.gridx = GridBagConstraints.REMAINDER;
    cnstrs.gridy = GridBagConstraints.REMAINDER;
    cnstrs.weightx = 1.0;
    cnstrs.weighty = 1.0;
    frame.getContentPane().add(panel, cnstrs);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

From source file:com.mapr.PurchaseLog.java

public static void main(String[] args) throws IOException {
    Options opts = new Options();
    CmdLineParser parser = new CmdLineParser(opts);
    try {/*from   w  w w .j  a v a  2s .co m*/
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("Usage: -count <number>G|M|K [ -users number ]  log-file user-profiles");
        return;
    }

    Joiner withTab = Joiner.on("\t");

    // first generate lots of user definitions
    SchemaSampler users = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("user-schema.txt"), Charsets.UTF_8).read());
    File userFile = File.createTempFile("user", "tsv");
    BufferedWriter out = Files.newBufferedWriter(userFile.toPath(), Charsets.UTF_8);
    for (int i = 0; i < opts.users; i++) {
        out.write(withTab.join(users.sample()));
        out.newLine();
    }
    out.close();

    // now generate a session for each user
    Splitter onTabs = Splitter.on("\t");
    Splitter onComma = Splitter.on(",");

    Random gen = new Random();
    SchemaSampler intermediate = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("hit_step.txt"), Charsets.UTF_8).read());

    final int COUNTRY = users.getFieldNames().indexOf("country");
    final int CAMPAIGN = intermediate.getFieldNames().indexOf("campaign_list");
    final int SEARCH_TERMS = intermediate.getFieldNames().indexOf("search_keywords");
    Preconditions.checkState(COUNTRY >= 0, "Need country field in user schema");
    Preconditions.checkState(CAMPAIGN >= 0, "Need campaign_list field in step schema");
    Preconditions.checkState(SEARCH_TERMS >= 0, "Need search_keywords field in step schema");

    out = Files.newBufferedWriter(new File(opts.out).toPath(), Charsets.UTF_8);

    for (String line : Files.readAllLines(userFile.toPath(), Charsets.UTF_8)) {
        long t = (long) (TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS) * gen.nextDouble());
        List<String> user = Lists.newArrayList(onTabs.split(line));

        // pick session length
        int n = (int) Math.floor(-30 * Math.log(gen.nextDouble()));

        for (int i = 0; i < n; i++) {
            // time on page
            int dt = (int) Math.floor(-20000 * Math.log(gen.nextDouble()));
            t += dt;

            // hit specific values
            JsonNode step = intermediate.sample();

            // check for purchase
            double p = 0.01;
            List<String> campaigns = Lists.newArrayList(onComma.split(step.get("campaign_list").asText()));
            List<String> keywords = Lists.newArrayList(onComma.split(step.get("search_keywords").asText()));
            if ((user.get(COUNTRY).equals("us") && campaigns.contains("5"))
                    || (user.get(COUNTRY).equals("jp") && campaigns.contains("7")) || keywords.contains("homer")
                    || keywords.contains("simpson")) {
                p = 0.5;
            }

            String events = gen.nextDouble() < p ? "1" : "-";

            out.write(Long.toString(t));
            out.write("\t");
            out.write(line);
            out.write("\t");
            out.write(withTab.join(step));
            out.write("\t");
            out.write(events);
            out.write("\n");
        }
    }
    out.close();
}

From source file:knop.psfj.heatmap.HeatMapGenerator.java

/**
 * The main method./*w  w  w  .j  av  a  2 s.  c o  m*/
 *
 * @param args the arguments
 */
public static void main(String[] args) {

    BeadImage i = new BeadImage();
    i.setFileAddress("/home/cyril/test_img/6_small.tif");
    i.workFromMemory();

    FovDataSet dataSet = new FovDataSet();

    Random random = new Random();

    for (int j = 0; j != 3000; j++) {
        dataSet.addValue("x", random.nextDouble() * 10);
        dataSet.addValue("y", random.nextDouble() * 10);
        dataSet.addValue("deltaX", random.nextDouble() * 1.5 / 2);
    }

    // dataSet.setTheoriticalValue("deltaX_norm", 1.0);
    dataSet.setColumnsUnits(MathUtils.MICROMETERS, "x", "y", "deltaX");
    HeatMapGenerator generator = new HeatMapGenerator(dataSet);
    generator.setMinAndMax(-1, 0, 1);
    // generator.setMinAndMaxLabels("", lineLabel, maxLabel)
    generator.setUnit("");
    generator.setBeadImage(i);
    // generator.setLutMode(NORMALIZED);
    generator.setCurrentColumn("deltaX");

    // generator.show(gene);

    // generator.injectDataSet(new FovDataSet("/home/cyril/data2.txt"),
    // "fwhmZ");
    generator.show(generator.getAnnotatedHeatMap());

    // System.out.println(dataSet.getTheoriticalValue("fwhmZ"));

}

From source file:msi.gaml.operators.Maths.java

public static void main(final String[] args) throws ParseException {
    java.lang.System.out.println("Various format tests");
    java.lang.System.out.println("NumberFormat.parse1e1 = " + NumberFormat.getInstance(Locale.US).parse("1e1"));
    java.lang.System.out.println("Double.parse 1e1 = " + Double.parseDouble("1e1"));
    java.lang.System.out//  www  .j a va 2  s .c  o  m
            .println("NumberFormat.parse 1E1 = " + NumberFormat.getInstance(Locale.US).parse("1E1"));
    java.lang.System.out.println("Double.parse 1E1 = " + Double.parseDouble("1E1"));
    java.lang.System.out
            .println("NumberFormat.parse 1.0e1 = " + NumberFormat.getInstance(Locale.US).parse("1.0e1"));
    java.lang.System.out.println("Double.parse 1.0e1 = " + Double.parseDouble("1.0e1"));
    java.lang.System.out.println(
            "NumberFormat.parse 0.001E+10 = " + NumberFormat.getInstance(Locale.US).parse("0.001E+10"));
    java.lang.System.out.println("Double.parse 0.001E+10 = " + Double.parseDouble("0.001E+10"));
    java.lang.System.out.println(
            "NumberFormat.parse 0.001E-10 = " + NumberFormat.getInstance(Locale.US).parse("0.001E-10"));
    java.lang.System.out.println("Double.parse 0.001E-10 = " + Double.parseDouble("0.001E-10"));
    java.lang.System.out
            .println("NumberFormat.parse 0.001e-10 =" + NumberFormat.getInstance(Locale.US).parse("0.001e-10"));
    java.lang.System.out.println("Double.parse 0.001e-10 = " + Double.parseDouble("0.001e-10"));
    java.lang.System.out.println("Various arithmetic tests");
    java.lang.System.out.println("cos(PI) = " + Maths.cos_rad(PI));
    java.lang.System.out.println("sin_rad(0.0) = " + sin_rad(0.0));
    java.lang.System.out.println("tan_rad(0.0) = " + tan_rad(0.0));
    java.lang.System.out.println("sin(360) = " + sin(360));
    java.lang.System.out.println("sin(-720) = " + sin(-720));
    java.lang.System.out.println("sin(360.0) = " + sin(360.0));
    java.lang.System.out.println("sin(-720.0) = " + sin(-720.0));
    java.lang.System.out.println("sin(90) = " + sin(90));
    java.lang.System.out.println("sin(45) = " + sin(45));
    java.lang.System.out.println("sin(0) = " + sin(0));
    java.lang.System.out.println("sin(135) = " + sin(135));

    java.lang.System.out.println("Math.sin(360.0) = " + Math.sin(2 * Math.PI));
    // java.lang.System.out.println("3.0 = 3" + (3d == 3));
    // java.lang.System.out.println("3.0 != 3" + (3d != 3));
    java.lang.System.out.println("floor and ceil 2.7 " + floor(2.7) + " and " + ceil(2.7));
    java.lang.System.out.println("floor and ceil -2.7 " + floor(-2.7) + " and " + ceil(-2.7));
    java.lang.System.out.println("floor and ceil -2 " + floor(-2) + " and " + ceil(-2));
    java.lang.System.out.println("floor and ceil 3 " + floor(3) + " and " + ceil(3));
    double atan2diff = 0;
    double atan2diff2 = 0;
    Random rand = new Random();
    long s1 = 0;
    long t1 = 0;
    long t2 = 0;
    long t3 = 0;
    // for ( int i = 0; i < 10000000; i++ ) {
    // double x = rand.nextDouble();
    // double y = rand.nextDouble();
    // s1 = java.lang.System.currentTimeMillis();
    // double a1 = Math.atan2(x, y);
    // t1 += java.lang.System.currentTimeMillis() - s1;
    // s1 = java.lang.System.currentTimeMillis();
    // double a2 = FastMath.atan2(x, y);
    // t2 += java.lang.System.currentTimeMillis() - s1;
    // s1 = java.lang.System.currentTimeMillis();
    // double a3 = Maths.atan2Opt2(x, y);
    // t3 += java.lang.System.currentTimeMillis() - s1;
    //
    // atan2diff += Math.abs(a1 - a2);
    // atan2diff2 += Math.abs(a1 - a3);
    // }
    // java.lang.System.out.println("atan2diff : " + atan2diff + "  atan2diff2 : " + atan2diff2 + " t1 : " + t1 +
    // " t2 : " + t2 + " t3 : " + t3);

    long t4 = 0;
    long t5 = 0;
    long t6 = 0;
    double distDiff1 = 0;
    double distDiff2 = 0;
    for (int i = 0; i < 1000000; i++) {
        double x1 = rand.nextDouble();
        double y1 = rand.nextDouble();
        double x2 = rand.nextDouble();
        double y2 = rand.nextDouble();
        Coordinate c1 = new Coordinate(x1, y1);
        Coordinate c2 = new Coordinate(x2, y2);

        s1 = java.lang.System.currentTimeMillis();
        double a1 = Math.hypot(x2 - x1, y2 - y1);
        t4 += java.lang.System.currentTimeMillis() - s1;
        s1 = java.lang.System.currentTimeMillis();
        double a2 = FastMath.hypot(x2 - x1, y2 - y1);
        t5 += java.lang.System.currentTimeMillis() - s1;
        s1 = java.lang.System.currentTimeMillis();
        double a3 = c1.distance(c2);
        t6 += java.lang.System.currentTimeMillis() - s1;
        distDiff1 += Math.abs(a1 - a2);
        distDiff2 += Math.abs(a1 - a3);
    }
    java.lang.System.out.println("distDiff1 : " + distDiff1 + "  distDiff2 : " + distDiff2 + " t4 : " + t4
            + " t5 : " + t5 + " t6 : " + t6);

    long t7 = 0;
    long t8 = 0;
    distDiff1 = 0;

    for (int i = 0; i < 1000000; i++) {
        double a1, a2;
        double x1 = rand.nextDouble();
        double x2 = rand.nextDouble();
        double y1 = rand.nextDouble();
        double y2 = rand.nextDouble();
        double z1 = 0.0;
        double z2 = 0.0;
        GamaPoint c2 = new GamaPoint(x2, y2, z2);

        s1 = java.lang.System.currentTimeMillis();
        if (z1 == 0d && c2.getZ() == 0d) {
            a1 = hypot(x1, x2, y1, y2);
        } else {
            a1 = hypot(x1, x2, y1, y2, z1, z2);
        }
        t7 += java.lang.System.currentTimeMillis() - s1;
        s1 = java.lang.System.currentTimeMillis();
        a2 = hypot(x1, x2, y1, y2, z1, c2.getZ());
        t8 += java.lang.System.currentTimeMillis() - s1;
        distDiff1 += Math.abs(a1 - a2);
    }
    java.lang.System.out.println(
            "with 0.0 check : " + t7 + "  with direct 3 parameters call : " + t8 + " distance : " + distDiff1);
    // java.lang.System.out.println("Infinity to int:" + (int) Double.POSITIVE_INFINITY);
    // java.lang.System.out.println("NaN to int:" + (int) Double.NaN);
    // GuiUtils.debug("(int) (1.0/0.0):" + (int) (1.0 / 0.0));
    // GuiUtils.debug("(int) (1.0/0):" + (int) (1.0 / 0));
    // GuiUtils.debug("(int) (1.0/0d):" + (int) (1 / 0d));
    // GuiUtils.debug("(int) (1/0):" + 1 / 0);
}