Example usage for java.io DataInputStream readDouble

List of usage examples for java.io DataInputStream readDouble

Introduction

In this page you can find the example usage for java.io DataInputStream readDouble.

Prototype

public final double readDouble() throws IOException 

Source Link

Document

See the general contract of the readDouble method of DataInput.

Usage

From source file:ch.unil.genescore.vegas.Snp.java

/** 
 * Read this snp from the binary file. Format is:
 * 1. genotypes_.length/*from  www  .j a va  2 s. c  om*/
 * 2. genotypes_
 * 3. maf_
 * 4. alleleSd_
 * 5. alleleMean_
 * @throws IOException 
 */
public void readGenotype(DataInputStream is) throws IOException {

    // id_ is already read 
    genotypes_ = new byte[genotypeLength_];
    for (int i = 0; i < genotypeLength_; i++)
        genotypes_[i] = is.readByte();

    maf_ = is.readDouble();
    alleleMean_ = is.readDouble();
    alleleSd_ = is.readDouble();
}

From source file:darks.learning.word2vec.Word2Vec.java

/**
 * Load model file/*from www  .  j a  v a2s .  c  om*/
 * 
 * @param file Model file
 */
public void loadModel(File file) {
    DataInputStream dis = null;
    try {
        log.info("Reading word2vec model from " + file);
        dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
        int wordSize = dis.readInt();
        int featureSize = dis.readInt();
        wordNodes.clear();
        for (int i = 0; i < wordSize; i++) {
            DoubleMatrix feature = new DoubleMatrix(featureSize);
            int nameLen = dis.readInt();
            byte[] bits = new byte[nameLen];
            dis.read(bits, 0, nameLen);
            String name = new String(bits);
            double len = 0;
            for (int f = 0; f < featureSize; f++) {
                double w = dis.readDouble();
                feature.put(f, w);
                len += w * w;
            }
            len = FastMath.sqrt(len);
            //            feature.divi(len);
            wordNodes.put(name, new WordNode(name, feature));
        }
        log.info("Succeed to read word2vec model. Word dictionary size " + wordNodes.size());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    } finally {
        IOUtils.closeStream(dis);
    }
}

From source file:MersenneTwisterFast.java

/** Reads the entire state of the MersenneTwister RNG from the stream
 *  @param stream input stream//from  w  w  w. java 2 s  .com
 *  @throws IOException exception from stream reading
 */
public void readState(DataInputStream stream) throws IOException {
    int len = mt.length;
    for (int x = 0; x < len; x++)
        mt[x] = stream.readInt();

    len = mag01.length;
    for (int x = 0; x < len; x++)
        mag01[x] = stream.readInt();

    mti = stream.readInt();
    __nextNextGaussian = stream.readDouble();
    __haveNextNextGaussian = stream.readBoolean();
}

From source file:org.nd4j.linalg.util.ArrayUtil.java

public static double[] read(int length, DataInputStream dis) throws IOException {
    double[] ret = new double[length];
    for (int i = 0; i < length; i++)
        ret[i] = dis.readDouble();
    return ret;//from w  w  w . j a va  2 s.c  om
}

From source file:org.nd4j.linalg.util.ArrayUtil.java

public static double[] readDouble(int length, DataInputStream dis) throws IOException {
    double[] ret = new double[length];
    for (int i = 0; i < length; i++)
        ret[i] = dis.readDouble();
    return ret;/*w ww  .java 2  s . c o m*/
}

From source file:org.openmrs.module.odkconnector.serialization.serializer.ListSerializerTest.java

@Test
public void serialize_shouldSerializePatientInformation() throws Exception {
    File file = File.createTempFile("PatientSerialization", "Example");
    GZIPOutputStream outputStream = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(file)));

    log.info("Writing to: " + file.getAbsolutePath());

    Cohort cohort = new Cohort();
    cohort.addMember(6);//from   w w  w . j a  v  a 2 s.c  o  m
    cohort.addMember(7);
    cohort.addMember(8);

    List<Patient> patients = new ArrayList<Patient>();
    List<Obs> observations = new ArrayList<Obs>();
    List<Form> forms = new ArrayList<Form>();

    for (Integer patientId : cohort.getMemberIds()) {
        Patient patient = Context.getPatientService().getPatient(patientId);
        observations.addAll(Context.getObsService().getObservationsByPerson(patient));
        patients.add(patient);
    }

    Serializer serializer = HandlerUtil.getPreferredHandler(Serializer.class, List.class);
    serializer.write(outputStream, patients);
    serializer.write(outputStream, observations);
    serializer.write(outputStream, forms);

    outputStream.close();

    GZIPInputStream inputStream = new GZIPInputStream(new BufferedInputStream(new FileInputStream(file)));
    DataInputStream dataInputStream = new DataInputStream(inputStream);

    // total number of patients
    Integer patientCounter = dataInputStream.readInt();
    System.out.println("Patient Counter: " + patientCounter);
    for (int i = 0; i < patientCounter; i++) {
        System.out.println("=================Patient=====================");
        System.out.println("Patient Id: " + dataInputStream.readInt());
        System.out.println("Family Name: " + dataInputStream.readUTF());
        System.out.println("Middle Name: " + dataInputStream.readUTF());
        System.out.println("Last Name: " + dataInputStream.readUTF());
        System.out.println("Gender: " + dataInputStream.readUTF());
        System.out.println("Birth Date: " + dataInputStream.readLong());
        System.out.println("Identifier" + dataInputStream.readUTF());
    }

    Integer obsCounter = dataInputStream.readInt();
    for (int j = 0; j < obsCounter; j++) {
        System.out.println("==================Observation=================");
        System.out.println("Patient Id: " + dataInputStream.readInt());
        System.out.println("Concept Name: " + dataInputStream.readUTF());

        byte type = dataInputStream.readByte();
        if (type == ObsSerializer.TYPE_STRING)
            System.out.println("Value: " + dataInputStream.readUTF());
        else if (type == ObsSerializer.TYPE_INT)
            System.out.println("Value: " + dataInputStream.readInt());
        else if (type == ObsSerializer.TYPE_DOUBLE)
            System.out.println("Value: " + dataInputStream.readDouble());
        else if (type == ObsSerializer.TYPE_DATE)
            System.out.println("Value: " + dataInputStream.readLong());
        System.out.println("Time: " + dataInputStream.readLong());
    }

    Integer formCounter = dataInputStream.readInt();
    for (int j = 0; j < formCounter; j++) {
        System.out.println("==================Form=================");
        System.out.println("Form Id: " + dataInputStream.readInt());
    }

    System.out.println();

    inputStream.close();
}

From source file:org.openmrs.module.odkconnector.serialization.serializer.openmrs.PatientSerializerTest.java

@Test
public void serialize_shouldSerializePatientInformation() throws Exception {
    File file = File.createTempFile("PatientSerialization", "Example");
    GZIPOutputStream outputStream = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(file)));

    log.info("Writing to: " + file.getAbsolutePath());

    Cohort cohort = new Cohort();
    cohort.addMember(6);/*  w w w. j  a v a2 s . co m*/
    cohort.addMember(7);
    cohort.addMember(8);

    List<Patient> patients = new ArrayList<Patient>();
    List<Obs> observations = new ArrayList<Obs>();
    List<Form> forms = new ArrayList<Form>();

    for (Integer patientId : cohort.getMemberIds()) {
        Patient patient = Context.getPatientService().getPatient(patientId);
        observations.addAll(Context.getObsService().getObservationsByPerson(patient));
        patients.add(patient);
    }

    Serializer serializer = HandlerUtil.getPreferredHandler(Serializer.class, List.class);
    serializer.write(outputStream, patients);
    serializer.write(outputStream, observations);
    serializer.write(outputStream, forms);

    outputStream.close();

    GZIPInputStream inputStream = new GZIPInputStream(new BufferedInputStream(new FileInputStream(file)));
    DataInputStream dataInputStream = new DataInputStream(inputStream);

    // total number of patients
    Integer patientCounter = dataInputStream.readInt();
    System.out.println("Patient Counter: " + patientCounter);
    for (int i = 0; i < patientCounter; i++) {
        System.out.println("=================Patient=====================");
        System.out.println("Patient Id: " + dataInputStream.readInt());
        System.out.println("Family Name: " + dataInputStream.readUTF());
        System.out.println("Middle Name: " + dataInputStream.readUTF());
        System.out.println("Last Name: " + dataInputStream.readUTF());
        System.out.println("Gender: " + dataInputStream.readUTF());
        System.out.println("Birth Date: " + dataInputStream.readUTF());
        System.out.println("Identifier" + dataInputStream.readUTF());
    }

    Integer obsCounter = dataInputStream.readInt();
    for (int j = 0; j < obsCounter; j++) {
        System.out.println("==================Observation=================");
        System.out.println("Patient Id: " + dataInputStream.readInt());
        System.out.println("Concept Name: " + dataInputStream.readUTF());

        byte type = dataInputStream.readByte();
        if (type == ObsSerializer.TYPE_STRING)
            System.out.println("Value: " + dataInputStream.readUTF());
        else if (type == ObsSerializer.TYPE_INT)
            System.out.println("Value: " + dataInputStream.readInt());
        else if (type == ObsSerializer.TYPE_DOUBLE)
            System.out.println("Value: " + dataInputStream.readDouble());
        else if (type == ObsSerializer.TYPE_DATE)
            System.out.println("Value: " + dataInputStream.readUTF());
        System.out.println("Time: " + dataInputStream.readUTF());
    }

    Integer formCounter = dataInputStream.readInt();
    for (int j = 0; j < formCounter; j++) {
        System.out.println("==================Form=================");
        System.out.println("Form Id: " + dataInputStream.readInt());
    }

    System.out.println();

    inputStream.close();
}

From source file:org.bdval.cache.TableCache.java

/**
 * Retrieve a cached table from the cache. isTableCached should be called
 * before calling this to verify that the table is cached. Null will
 * be returned if the table wasn't in the cache or there was a problem
 * reading the table./*from w w  w . ja  v a 2  s.c om*/
 *
 * @param splitId        The split id
 * @param splitType      The Split type
 * @param datasetName    The dataset name
 * @param geneListFilter A gene list. If not null, the gene list is queried with each double
 * column identifier to determine if the identifier is contained in the gene list. Columns
 * that do not match the gene list are not loaded.
 * @return the table read from the cache (or null if it could not be read)
 */
public Table getCachedTable(final int splitId, final String splitType, final String datasetName,
        final GeneList geneListFilter) {
    final File cachedTableFile = getCachedTableFile(splitId, splitType, datasetName);

    if (geneListFilter != null && !(geneListFilter instanceof FullGeneList)) {
        final ObjectSet<CharSequence> tableColumnIds = getTableColumnIds(splitId, splitType, datasetName);
        geneListFilter.calculateProbeSetSelection(tableColumnIds);
    }
    DataInputStream dataInput = null;
    try {
        dataInput = new DataInputStream(new FastBufferedInputStream(new FileInputStream(cachedTableFile)));
        final ArrayTable result = new ArrayTable();
        final int numberOfColumns = dataInput.readInt();
        LOG.info("Reading cached table with " + numberOfColumns + " columns");
        for (int i = 0; i < numberOfColumns; i++) {
            final String colType = dataInput.readUTF();
            final String colId = dataInput.readUTF();

            if ("s".equals(colType)) {
                final int numStrings = dataInput.readInt();
                resize(result, numStrings);
                final int columnIndex = result.addColumn(colId, String.class);
                for (int j = 0; j < numStrings; j++) {
                    result.appendObject(columnIndex, dataInput.readUTF());
                }
            } else if ("d".equals(colType)) {
                final int numDoubles = dataInput.readInt();
                resize(result, numDoubles);
                if (geneListFilter != null && !geneListFilter.isProbesetInList(colId)) {
                    // the column does not match the gene list. Skip this column
                    // we don't need to read these doubles, just skip them;
                    final int numBytes = Double.SIZE * numDoubles / 8;
                    final int actualBytes = dataInput.skipBytes(numBytes);
                    if (actualBytes != numBytes) {
                        LOG.warn("actual bytes skipped (" + actualBytes + ") does" + "not equal expected of "
                                + numBytes);
                    }
                    continue;
                }

                final int columnIndex = result.addColumn(colId, double.class);
                for (int j = 0; j < numDoubles; j++) {
                    result.appendDoubleValue(columnIndex, dataInput.readDouble());
                }

            } else {
                LOG.error("UNKNOWN COLUMN TYPE " + colType + " cannot read cached table from file "
                        + filenameOf(cachedTableFile));
                return null;
            }
        }
        return result;
    } catch (IOException e) {
        LOG.error(e);
        return null;
    } catch (TypeMismatchException e) {
        LOG.error("TypeMismatchException adding data to Table " + filenameOf(cachedTableFile), e);
        return null;
    } finally {
        IOUtils.closeQuietly(dataInput);
    }
}

From source file:com.alphabetbloc.accessmrs.services.SyncManager.java

private void insertPatientForms(final DataInputStream zdis) throws Exception {
    long start = System.currentTimeMillis();

    SimpleDateFormat output = new SimpleDateFormat("MMM dd, yyyy");
    SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd");

    SQLiteDatabase db = DbProvider.getDb();
    InsertHelper ih = new InsertHelper(db, DataModel.OBSERVATIONS_TABLE);

    int ptIdIndex = ih.getColumnIndex(DataModel.KEY_PATIENT_ID);
    int obsTextIndex = ih.getColumnIndex(DataModel.KEY_VALUE_TEXT);
    int obsNumIndex = ih.getColumnIndex(DataModel.KEY_VALUE_NUMERIC);
    int obsDateIndex = ih.getColumnIndex(DataModel.KEY_VALUE_DATE);
    int obsIntIndex = ih.getColumnIndex(DataModel.KEY_VALUE_INT);
    int obsFieldIndex = ih.getColumnIndex(DataModel.KEY_FIELD_NAME);
    int obsTypeIndex = ih.getColumnIndex(DataModel.KEY_DATA_TYPE);
    int obsEncDateIndex = ih.getColumnIndex(DataModel.KEY_ENCOUNTER_DATE);

    db.beginTransaction();/*from   ww w  . j  a  v  a  2s .  co m*/
    sLoopProgress.set(0);
    try {
        sLoopCount.set(zdis.readInt());
        if (App.DEBUG)
            Log.v(TAG, "insertPatientForms icount: " + sLoopCount);
        for (int i = 1; i < sLoopCount.get() + 1; i++) {

            ih.prepareForInsert();
            ih.bind(ptIdIndex, zdis.readInt());
            ih.bind(obsFieldIndex, zdis.readUTF());
            byte dataType = zdis.readByte();
            if (dataType == DataModel.TYPE_STRING) {
                ih.bind(obsTextIndex, zdis.readUTF());
            } else if (dataType == DataModel.TYPE_INT) {
                ih.bind(obsIntIndex, zdis.readInt());
            } else if (dataType == DataModel.TYPE_DOUBLE) {
                ih.bind(obsNumIndex, zdis.readDouble());
            } else if (dataType == DataModel.TYPE_DATE) {
                ih.bind(obsDateIndex, parseDate(input, output, zdis.readUTF()));
            }
            ih.bind(obsTypeIndex, dataType);
            ih.bind(obsEncDateIndex, parseDate(input, output, zdis.readUTF()));
            ih.execute();

            sLoopProgress.getAndIncrement();
        }
        db.setTransactionSuccessful();
    } finally {
        ih.close();
        db.endTransaction();
    }

    long end = System.currentTimeMillis();
    if (App.DEBUG)
        Log.v("SYNC BENCHMARK",
                String.format("Total Patient-Forms: \n%d\nTotal Time: \n%d\nRecords per second: \n%.2f",
                        sLoopCount.get(), (int) (end - start),
                        1000 * (double) sLoopCount.get() / (double) (end - start)));
}

From source file:org.apache.pulsar.testclient.LoadSimulationClient.java

private void handle(final byte command, final DataInputStream inputStream, final DataOutputStream outputStream)
        throws Exception {
    final TradeConfiguration tradeConf = new TradeConfiguration();
    tradeConf.command = command;//from  ww w  .  jav  a2s .c  o  m
    switch (command) {
    case CHANGE_COMMAND:
        // Change the topic's settings if it exists.
        decodeProducerOptions(tradeConf, inputStream);
        if (topicsToTradeUnits.containsKey(tradeConf.topic)) {
            topicsToTradeUnits.get(tradeConf.topic).change(tradeConf);
        }
        break;
    case STOP_COMMAND:
        // Stop the topic if it exists.
        tradeConf.topic = inputStream.readUTF();
        if (topicsToTradeUnits.containsKey(tradeConf.topic)) {
            topicsToTradeUnits.get(tradeConf.topic).stop.set(true);
        }
        break;
    case TRADE_COMMAND:
        // Create the topic. It is assumed that the topic does not already exist.
        decodeProducerOptions(tradeConf, inputStream);
        final TradeUnit tradeUnit = new TradeUnit(tradeConf, client, producerConf, consumerConf, payloadCache);
        topicsToTradeUnits.put(tradeConf.topic, tradeUnit);
        executor.submit(() -> {
            try {
                final String topic = tradeConf.topic;
                final String namespace = topic.substring("persistent://".length(), topic.lastIndexOf('/'));
                try {
                    admin.namespaces().createNamespace(namespace);
                } catch (PulsarAdminException.ConflictException e) {
                    // Ignore, already created namespace.
                }
                tradeUnit.start();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        });
        break;
    case CHANGE_GROUP_COMMAND:
        // Change the settings of all topics belonging to a group.
        decodeGroupOptions(tradeConf, inputStream);
        tradeConf.size = inputStream.readInt();
        tradeConf.rate = inputStream.readDouble();
        // See if a topic belongs to this tenant and group using this regex.
        final String groupRegex = ".*://" + tradeConf.tenant + "/.*/" + tradeConf.group + "-.*/.*";
        for (Map.Entry<String, TradeUnit> entry : topicsToTradeUnits.entrySet()) {
            final String destination = entry.getKey();
            final TradeUnit unit = entry.getValue();
            if (destination.matches(groupRegex)) {
                unit.change(tradeConf);
            }
        }
        break;
    case STOP_GROUP_COMMAND:
        // Stop all topics belonging to a group.
        decodeGroupOptions(tradeConf, inputStream);
        // See if a topic belongs to this tenant and group using this regex.
        final String regex = ".*://" + tradeConf.tenant + "/.*/" + tradeConf.group + "-.*/.*";
        for (Map.Entry<String, TradeUnit> entry : topicsToTradeUnits.entrySet()) {
            final String destination = entry.getKey();
            final TradeUnit unit = entry.getValue();
            if (destination.matches(regex)) {
                unit.stop.set(true);
            }
        }
        break;
    case FIND_COMMAND:
        // Write a single boolean indicating if the topic was found.
        outputStream.writeBoolean(topicsToTradeUnits.containsKey(inputStream.readUTF()));
        outputStream.flush();
        break;
    default:
        throw new IllegalArgumentException("Unrecognized command code received: " + command);
    }
}