Search in sources :

Example 26 with ByteOrder

use of java.nio.ByteOrder in project javacv by bytedeco.

the class DC1394FrameGrabber method grab.

public Frame grab() throws Exception {
    enqueue();
    if (linux) {
        fds.events(POLLIN);
        if (poll(fds, 1, timeout) == 0) {
            throw new Exception("poll() Error: Timeout occured. (Has start() been called?)");
        }
    }
    int i = 0;
    int err = dc1394_capture_dequeue(camera, DC1394_CAPTURE_POLICY_WAIT, raw_image[i]);
    if (err != DC1394_SUCCESS) {
        throw new Exception("dc1394_capture_dequeue(WAIT) Error " + err + ": Could not capture a frame. (Has start() been called?)");
    }
    // try to poll for more images, to get the most recent one...
    int numDequeued = 0;
    while (!raw_image[i].isNull()) {
        enqueue();
        enqueue_image = raw_image[i];
        i = (i + 1) % 2;
        numDequeued++;
        err = dc1394_capture_dequeue(camera, DC1394_CAPTURE_POLICY_POLL, raw_image[i]);
        if (err != DC1394_SUCCESS) {
            throw new Exception("dc1394_capture_dequeue(POLL) Error " + err + ": Could not capture a frame.");
        }
    }
    frame = raw_image[(i + 1) % 2];
    int w = frame.size(0);
    int h = frame.size(1);
    int depth = frame.data_depth();
    int iplDepth = 0;
    switch(depth) {
        case 8:
            iplDepth = IPL_DEPTH_8U;
            break;
        case 16:
            iplDepth = IPL_DEPTH_16U;
            break;
        default:
            assert false;
    }
    int stride = frame.stride();
    int size = frame.image_bytes();
    int numChannels = stride / w * 8 / depth;
    ByteOrder frameEndian = frame.little_endian() != 0 ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN;
    boolean alreadySwapped = false;
    int color_coding = frame.color_coding();
    boolean colorbayer = color_coding == DC1394_COLOR_CODING_RAW8 || color_coding == DC1394_COLOR_CODING_RAW16;
    boolean colorrgb = color_coding == DC1394_COLOR_CODING_RGB8 || color_coding == DC1394_COLOR_CODING_RGB16;
    boolean coloryuv = color_coding == DC1394_COLOR_CODING_YUV411 || color_coding == DC1394_COLOR_CODING_YUV422 || color_coding == DC1394_COLOR_CODING_YUV444;
    BytePointer imageData = frame.image();
    if ((depth <= 8 || frameEndian.equals(ByteOrder.nativeOrder())) && !coloryuv && (imageMode == ImageMode.RAW || (imageMode == ImageMode.COLOR && numChannels == 3) || (imageMode == ImageMode.GRAY && numChannels == 1 && !colorbayer))) {
        if (return_image == null) {
            return_image = IplImage.createHeader(w, h, iplDepth, numChannels);
        }
        return_image.widthStep(stride);
        return_image.imageSize(size);
        return_image.imageData(imageData);
    } else {
        // in the padding, there's sometimes timeframe information and stuff
        // that libdc1394 will copy for us, so we need to allocate it
        int padding_bytes = frame.padding_bytes();
        int padding1 = (int) Math.ceil((double) padding_bytes / (w * depth / 8));
        int padding3 = (int) Math.ceil((double) padding_bytes / (w * 3 * depth / 8));
        if (return_image == null) {
            int c = imageMode == ImageMode.COLOR ? 3 : 1;
            int padding = imageMode == ImageMode.COLOR ? padding3 : padding1;
            return_image = IplImage.create(w, h + padding, iplDepth, c);
            return_image.height(return_image.height() - padding);
        }
        if (temp_image == null) {
            if (imageMode == ImageMode.COLOR && (numChannels > 1 || depth > 8) && !coloryuv && !colorbayer) {
                temp_image = IplImage.create(w, h + padding1, iplDepth, numChannels);
                temp_image.height(temp_image.height() - padding1);
            } else if (imageMode == ImageMode.GRAY && (coloryuv || colorbayer || (colorrgb && depth > 8))) {
                temp_image = IplImage.create(w, h + padding3, iplDepth, 3);
                temp_image.height(temp_image.height() - padding3);
            } else if (imageMode == ImageMode.GRAY && colorrgb) {
                temp_image = IplImage.createHeader(w, h, iplDepth, 3);
            } else if (imageMode == ImageMode.COLOR && numChannels == 1 && !coloryuv && !colorbayer) {
                temp_image = IplImage.createHeader(w, h, iplDepth, 1);
            } else {
                temp_image = return_image;
            }
        }
        conv_image.size(0, temp_image.width());
        conv_image.size(1, temp_image.height());
        if (depth > 8) {
            conv_image.color_coding(imageMode == ImageMode.RAW ? DC1394_COLOR_CODING_RAW16 : temp_image.nChannels() == 1 ? DC1394_COLOR_CODING_MONO16 : DC1394_COLOR_CODING_RGB16);
            conv_image.data_depth(16);
        } else {
            conv_image.color_coding(imageMode == ImageMode.RAW ? DC1394_COLOR_CODING_RAW8 : temp_image.nChannels() == 1 ? DC1394_COLOR_CODING_MONO8 : DC1394_COLOR_CODING_RGB8);
            conv_image.data_depth(8);
        }
        conv_image.stride(temp_image.widthStep());
        int temp_size = temp_image.imageSize();
        conv_image.allocated_image_bytes(temp_size).total_bytes(temp_size).image_bytes(temp_size);
        conv_image.image(temp_image.imageData());
        if (colorbayer) {
            // from raw Bayer... invert R and B to get BGR images
            // (like OpenCV wants them) instead of RGB
            int c = frame.color_filter();
            if (c == DC1394_COLOR_FILTER_RGGB) {
                frame.color_filter(DC1394_COLOR_FILTER_BGGR);
            } else if (c == DC1394_COLOR_FILTER_GBRG) {
                frame.color_filter(DC1394_COLOR_FILTER_GRBG);
            } else if (c == DC1394_COLOR_FILTER_GRBG) {
                frame.color_filter(DC1394_COLOR_FILTER_GBRG);
            } else if (c == DC1394_COLOR_FILTER_BGGR) {
                frame.color_filter(DC1394_COLOR_FILTER_RGGB);
            } else {
                assert false;
            }
            // other better methods than "simple" give garbage at 16 bits..
            err = dc1394_debayer_frames(frame, conv_image, DC1394_BAYER_METHOD_SIMPLE);
            frame.color_filter(c);
            if (err != DC1394_SUCCESS) {
                throw new Exception("dc1394_debayer_frames() Error " + err + ": Could not debayer frame.");
            }
        } else if (depth > 8 && frame.data_depth() == conv_image.data_depth() && frame.color_coding() == conv_image.color_coding() && frame.stride() == conv_image.stride()) {
            // we just need a copy to swap bytes..
            ShortBuffer in = frame.getByteBuffer().order(frameEndian).asShortBuffer();
            ShortBuffer out = temp_image.getByteBuffer().order(ByteOrder.nativeOrder()).asShortBuffer();
            out.put(in);
            alreadySwapped = true;
        } else if ((imageMode == ImageMode.GRAY && colorrgb) || (imageMode == ImageMode.COLOR && numChannels == 1 && !coloryuv && !colorbayer)) {
            temp_image.widthStep(stride);
            temp_image.imageSize(size);
            temp_image.imageData(imageData);
        } else if (!colorrgb && (colorbayer || coloryuv || numChannels > 1)) {
            // from YUV, etc.
            err = dc1394_convert_frames(frame, conv_image);
            if (err != DC1394_SUCCESS) {
                throw new Exception("dc1394_convert_frames() Error " + err + ": Could not convert frame.");
            }
        }
        if (!alreadySwapped && depth > 8 && !frameEndian.equals(ByteOrder.nativeOrder())) {
            // ack, the camera's endianness doesn't correspond to our machine ...
            // swap bytes of 16-bit images
            ByteBuffer bb = temp_image.getByteBuffer();
            ShortBuffer in = bb.order(frameEndian).asShortBuffer();
            ShortBuffer out = bb.order(ByteOrder.nativeOrder()).asShortBuffer();
            out.put(in);
        }
        // should we copy the padding as well?
        if (imageMode == ImageMode.COLOR && numChannels == 1 && !coloryuv && !colorbayer) {
            cvCvtColor(temp_image, return_image, CV_GRAY2BGR);
        } else if (imageMode == ImageMode.GRAY && (colorbayer || colorrgb || coloryuv)) {
            cvCvtColor(temp_image, return_image, CV_BGR2GRAY);
        }
    }
    switch(frame.color_filter()) {
        case DC1394_COLOR_FILTER_RGGB:
            sensorPattern = SENSOR_PATTERN_RGGB;
            break;
        case DC1394_COLOR_FILTER_GBRG:
            sensorPattern = SENSOR_PATTERN_GBRG;
            break;
        case DC1394_COLOR_FILTER_GRBG:
            sensorPattern = SENSOR_PATTERN_GRBG;
            break;
        case DC1394_COLOR_FILTER_BGGR:
            sensorPattern = SENSOR_PATTERN_BGGR;
            break;
        default:
            sensorPattern = -1L;
    }
    enqueue_image = frame;
    timestamp = frame.timestamp();
    frameNumber += numDequeued;
    // System.out.println("frame age = " + (local_time[0] - timestamp));
    return converter.convert(return_image);
}
Also used : BytePointer(org.bytedeco.javacpp.BytePointer) ByteOrder(java.nio.ByteOrder) ShortBuffer(java.nio.ShortBuffer) ByteBuffer(java.nio.ByteBuffer)

Example 27 with ByteOrder

use of java.nio.ByteOrder in project javacv by bytedeco.

the class FlyCapture2FrameGrabber method grab.

public Frame grab() throws FrameGrabber.Exception {
    Error error = camera.RetrieveBuffer(raw_image);
    if (error.notEquals(PGRERROR_OK)) {
        throw new FrameGrabber.Exception("flycaptureGrabImage2() Error " + error + " (Has start() been called?)");
    }
    int w = raw_image.GetCols();
    int h = raw_image.GetRows();
    int format = raw_image.GetPixelFormat();
    int depth = getDepth(format);
    int stride = raw_image.GetStride();
    int size = h * stride;
    int numChannels = getNumChannels(format);
    error = camera.ReadRegister(IMAGE_DATA_FORMAT, regOut);
    if (error.notEquals(PGRERROR_OK)) {
        throw new FrameGrabber.Exception("flycaptureGetCameraRegister() Error " + error);
    }
    ByteOrder frameEndian = (regOut[0] & 0x1) != 0 ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN;
    boolean alreadySwapped = false;
    boolean colorbayer = raw_image.GetBayerTileFormat() != NONE;
    boolean colorrgb = format == PIXEL_FORMAT_RGB8 || format == PIXEL_FORMAT_RGB16 || format == PIXEL_FORMAT_BGR || format == PIXEL_FORMAT_BGRU;
    boolean coloryuv = format == PIXEL_FORMAT_411YUV8 || format == PIXEL_FORMAT_422YUV8 || format == PIXEL_FORMAT_444YUV8;
    BytePointer imageData = raw_image.GetData().capacity(raw_image.GetDataSize());
    if ((depth == IPL_DEPTH_8U || frameEndian.equals(ByteOrder.nativeOrder())) && (imageMode == FrameGrabber.ImageMode.RAW || (imageMode == FrameGrabber.ImageMode.COLOR && numChannels == 3) || (imageMode == FrameGrabber.ImageMode.GRAY && numChannels == 1 && !colorbayer))) {
        if (return_image == null) {
            return_image = IplImage.createHeader(w, h, depth, numChannels);
        }
        return_image.widthStep(stride);
        return_image.imageSize(size);
        return_image.imageData(imageData);
    } else {
        if (return_image == null) {
            return_image = IplImage.create(w, h, depth, imageMode == FrameGrabber.ImageMode.COLOR ? 3 : 1);
        }
        if (temp_image == null) {
            if (imageMode == FrameGrabber.ImageMode.COLOR && (numChannels > 1 || depth > 8) && !coloryuv && !colorbayer) {
                temp_image = IplImage.create(w, h, depth, numChannels);
            } else if (imageMode == FrameGrabber.ImageMode.GRAY && colorbayer) {
                temp_image = IplImage.create(w, h, depth, 3);
            } else if (imageMode == FrameGrabber.ImageMode.GRAY && colorrgb) {
                temp_image = IplImage.createHeader(w, h, depth, 3);
            } else if (imageMode == FrameGrabber.ImageMode.COLOR && numChannels == 1 && !coloryuv && !colorbayer) {
                temp_image = IplImage.createHeader(w, h, depth, 1);
            } else {
                temp_image = return_image;
            }
        }
        setStride(conv_image, temp_image.widthStep());
        conv_image.SetData(temp_image.imageData(), temp_image.width() * temp_image.height() * temp_image.depth());
        if (depth == IPL_DEPTH_8U) {
            setPixelFormat(conv_image, imageMode == FrameGrabber.ImageMode.RAW ? PIXEL_FORMAT_RAW8 : temp_image.nChannels() == 1 ? PIXEL_FORMAT_MONO8 : PIXEL_FORMAT_BGR);
        } else {
            setPixelFormat(conv_image, imageMode == FrameGrabber.ImageMode.RAW ? PIXEL_FORMAT_RAW16 : temp_image.nChannels() == 1 ? PIXEL_FORMAT_MONO16 : PIXEL_FORMAT_RGB16);
        }
        if (depth != IPL_DEPTH_8U && conv_image.GetPixelFormat() == format && conv_image.GetStride() == stride) {
            // we just need a copy to swap bytes..
            ShortBuffer in = imageData.asByteBuffer().order(frameEndian).asShortBuffer();
            ShortBuffer out = temp_image.getByteBuffer().order(ByteOrder.nativeOrder()).asShortBuffer();
            out.put(in);
            alreadySwapped = true;
        } else if ((imageMode == FrameGrabber.ImageMode.GRAY && colorrgb) || (imageMode == FrameGrabber.ImageMode.COLOR && numChannels == 1 && !coloryuv && !colorbayer)) {
            temp_image.widthStep(stride);
            temp_image.imageSize(size);
            temp_image.imageData(imageData);
        } else if (!colorrgb && (colorbayer || coloryuv || numChannels > 1)) {
            error = raw_image.Convert(conv_image);
            // error = flycaptureConvertImage(context, raw_image, conv_image);
            if (error.notEquals(PGRERROR_OK)) {
                PrintError(error);
                throw new FrameGrabber.Exception("raw_image.Convert Error " + error);
            }
        }
        if (!alreadySwapped && depth != IPL_DEPTH_8U && !frameEndian.equals(ByteOrder.nativeOrder())) {
            // ack, the camera's endianness doesn't correspond to our machine ...
            // swap bytes of 16-bit images
            ByteBuffer bb = temp_image.getByteBuffer();
            ShortBuffer in = bb.order(frameEndian).asShortBuffer();
            ShortBuffer out = bb.order(ByteOrder.nativeOrder()).asShortBuffer();
            out.put(in);
        }
        if (imageMode == FrameGrabber.ImageMode.COLOR && numChannels == 1 && !coloryuv && !colorbayer) {
            cvCvtColor(temp_image, return_image, CV_GRAY2BGR);
        } else if (imageMode == FrameGrabber.ImageMode.GRAY && (colorbayer || colorrgb)) {
            cvCvtColor(temp_image, return_image, CV_BGR2GRAY);
        }
    }
    int bayerFormat = cameraInfo.bayerTileFormat();
    switch(bayerFormat) {
        case BGGR:
            sensorPattern = SENSOR_PATTERN_BGGR;
            break;
        case GBRG:
            sensorPattern = SENSOR_PATTERN_GBRG;
            break;
        case GRBG:
            sensorPattern = SENSOR_PATTERN_GRBG;
            break;
        case RGGB:
            sensorPattern = SENSOR_PATTERN_RGGB;
            break;
        default:
            sensorPattern = -1L;
    }
    TimeStamp timeStamp = raw_image.GetTimeStamp();
    timestamp = timeStamp.seconds() * 1000000L + timeStamp.microSeconds();
    return converter.convert(return_image);
}
Also used : BytePointer(org.bytedeco.javacpp.BytePointer) Error(org.bytedeco.javacpp.FlyCapture2.Error) ByteOrder(java.nio.ByteOrder) ShortBuffer(java.nio.ShortBuffer) ByteBuffer(java.nio.ByteBuffer)

Example 28 with ByteOrder

use of java.nio.ByteOrder in project ffx by mjschnie.

the class CCP4MapFilter method getCrystal.

/**
 * {@inheritDoc}
 */
@Override
public Crystal getCrystal(String fileName, CompositeConfiguration properties) {
    int imapData;
    int spaceGroup = -1;
    double cellA = -1.0;
    double cellB = -1.0;
    double cellC = -1.0;
    double cellAlpha = -1.0;
    double cellBeta = -1.0;
    double cellGamma = -1.0;
    ByteOrder byteOrder = ByteOrder.nativeOrder();
    FileInputStream fileInputStream;
    DataInputStream dataInputStream;
    // first determine byte order of file versus system
    try {
        fileInputStream = new FileInputStream(fileName);
        dataInputStream = new DataInputStream(fileInputStream);
        dataInputStream.skipBytes(212);
        byte[] bytes = new byte[4];
        dataInputStream.read(bytes, 0, 4);
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        imapData = byteBuffer.order(ByteOrder.BIG_ENDIAN).getInt();
        String stampString = Integer.toHexString(imapData);
        switch(stampString.charAt(0)) {
            case '1':
            case '3':
                if (byteOrder.equals(ByteOrder.LITTLE_ENDIAN)) {
                    byteOrder = ByteOrder.BIG_ENDIAN;
                }
                break;
            case '4':
                if (byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
                    byteOrder = ByteOrder.LITTLE_ENDIAN;
                }
                break;
        }
        fileInputStream.close();
    } catch (Exception e) {
        String message = " Fatal exception reading CCP4 map.\n";
        logger.log(Level.SEVERE, message, e);
    }
    try {
        fileInputStream = new FileInputStream(fileName);
        dataInputStream = new DataInputStream(fileInputStream);
        dataInputStream.skipBytes(40);
        byte[] bytes = new byte[80];
        dataInputStream.read(bytes, 0, 80);
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        cellA = byteBuffer.order(byteOrder).getFloat();
        cellB = byteBuffer.order(byteOrder).getFloat();
        cellC = byteBuffer.order(byteOrder).getFloat();
        cellAlpha = byteBuffer.order(byteOrder).getFloat();
        cellBeta = byteBuffer.order(byteOrder).getFloat();
        cellGamma = byteBuffer.order(byteOrder).getFloat();
        for (int i = 0; i < 3; i++) {
            byteBuffer.order(byteOrder).getInt();
        }
        for (int i = 0; i < 3; i++) {
            byteBuffer.order(byteOrder).getFloat();
        }
        spaceGroup = byteBuffer.order(byteOrder).getInt();
        fileInputStream.close();
    } catch (Exception e) {
        String message = " Fatal exception reading CCP4 map.\n";
        logger.log(Level.SEVERE, message, e);
    }
    return new Crystal(cellA, cellB, cellC, cellAlpha, cellBeta, cellGamma, SpaceGroup.spaceGroupNames[spaceGroup - 1]);
}
Also used : ByteOrder(java.nio.ByteOrder) DataInputStream(java.io.DataInputStream) ByteBuffer(java.nio.ByteBuffer) FileInputStream(java.io.FileInputStream) Crystal(ffx.crystal.Crystal)

Example 29 with ByteOrder

use of java.nio.ByteOrder in project ffx by mjschnie.

the class MTZFilter method readFcs.

/**
 * Read the structure factors.
 *
 * @param mtzFile
 * @param reflectionList
 * @param fcData
 * @param properties
 * @return
 */
public boolean readFcs(File mtzFile, ReflectionList reflectionList, DiffractionRefinementData fcData, CompositeConfiguration properties) {
    int nRead, nIgnore, nRes, nFriedel, nCut;
    ByteOrder byteOrder = ByteOrder.nativeOrder();
    FileInputStream fileInputStream;
    DataInputStream dataInputStream;
    StringBuilder sb = new StringBuilder();
    try {
        fileInputStream = new FileInputStream(mtzFile);
        dataInputStream = new DataInputStream(fileInputStream);
        byte[] headerOffset = new byte[4];
        byte[] bytes = new byte[80];
        int offset = 0;
        // Eat "MTZ" title.
        dataInputStream.read(bytes, offset, 4);
        String mtzString = null;
        // Header offset.
        dataInputStream.read(headerOffset, offset, 4);
        // Machine stamp.
        dataInputStream.read(bytes, offset, 4);
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        int stamp = byteBuffer.order(ByteOrder.BIG_ENDIAN).getInt();
        String stampString = Integer.toHexString(stamp);
        switch(stampString.charAt(0)) {
            case '1':
            case '3':
                if (byteOrder.equals(ByteOrder.LITTLE_ENDIAN)) {
                    byteOrder = ByteOrder.BIG_ENDIAN;
                }
                break;
            case '4':
                if (byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
                    byteOrder = ByteOrder.LITTLE_ENDIAN;
                }
                break;
        }
        byteBuffer = ByteBuffer.wrap(headerOffset);
        int headerOffsetI = byteBuffer.order(byteOrder).getInt();
        // Skip to header and parse.
        dataInputStream.skipBytes((headerOffsetI - 4) * 4);
        for (Boolean parsing = true; parsing; dataInputStream.read(bytes, offset, 80)) {
            mtzString = new String(bytes);
            parsing = parseHeader(mtzString);
        }
        // Column identifiers.
        fc = phiC = fs = phiS = -1;
        boolean print = true;
        parseFcColumns(print);
        if (h < 0 || k < 0 || l < 0) {
            String message = " Fatal error in MTZ file - no H K L indexes?\n";
            logger.log(Level.SEVERE, message);
            return false;
        }
        // Reopen to start at beginning.
        fileInputStream = new FileInputStream(mtzFile);
        dataInputStream = new DataInputStream(fileInputStream);
        // Skip initial header.
        dataInputStream.skipBytes(80);
        float[] data = new float[nColumns];
        HKL mate = new HKL();
        // Read in data.
        ComplexNumber complexNumber = new ComplexNumber();
        nRead = nIgnore = nRes = nFriedel = nCut = 0;
        for (int i = 0; i < nReflections; i++) {
            for (int j = 0; j < nColumns; j++) {
                dataInputStream.read(bytes, offset, 4);
                byteBuffer = ByteBuffer.wrap(bytes);
                data[j] = byteBuffer.order(byteOrder).getFloat();
            }
            int ih = (int) data[h];
            int ik = (int) data[k];
            int il = (int) data[l];
            boolean friedel = reflectionList.findSymHKL(ih, ik, il, mate, false);
            HKL hkl = reflectionList.getHKL(mate);
            if (hkl != null) {
                if (fc > 0 && phiC > 0) {
                    complexNumber.re(data[fc] * cos(toRadians(data[phiC])));
                    complexNumber.im(data[fc] * sin(toRadians(data[phiC])));
                    fcData.setFc(hkl.index(), complexNumber);
                }
                if (fs > 0 && phiS > 0) {
                    complexNumber.re(data[fs] * cos(toRadians(data[phiS])));
                    complexNumber.im(data[fs] * sin(toRadians(data[phiS])));
                    fcData.setFs(hkl.index(), complexNumber);
                }
                nRead++;
            } else {
                HKL tmp = new HKL(ih, ik, il);
                if (!reflectionList.resolution.inInverseResSqRange(Crystal.invressq(reflectionList.crystal, tmp))) {
                    nRes++;
                } else {
                    nIgnore++;
                }
            }
        }
        if (logger.isLoggable(Level.INFO)) {
            sb.append(format(" MTZ file type (machine stamp): %s\n", stampString));
            sb.append(format(" Fc HKL read in:                             %d\n", nRead));
            sb.append(format(" Fc HKL read as friedel mates:               %d\n", nFriedel));
            sb.append(format(" Fc HKL NOT read in (too high resolution):   %d\n", nRes));
            sb.append(format(" Fc HKL NOT read in (not in internal list?): %d\n", nIgnore));
            sb.append(format(" Fc HKL NOT read in (F/sigF cutoff):         %d\n", nCut));
            sb.append(format(" HKL in internal list:                       %d\n", reflectionList.hkllist.size()));
            logger.info(sb.toString());
        }
    } catch (EOFException e) {
        String message = " MTZ end of file reached.";
        logger.log(Level.WARNING, message, e);
        return false;
    } catch (IOException e) {
        String message = " MTZ IO Exception.";
        logger.log(Level.WARNING, message, e);
        return false;
    }
    return true;
}
Also used : HKL(ffx.crystal.HKL) ByteOrder(java.nio.ByteOrder) ComplexNumber(ffx.numerics.ComplexNumber) IOException(java.io.IOException) DataInputStream(java.io.DataInputStream) ByteBuffer(java.nio.ByteBuffer) FileInputStream(java.io.FileInputStream) EOFException(java.io.EOFException)

Example 30 with ByteOrder

use of java.nio.ByteOrder in project ffx by mjschnie.

the class MTZFilter method getReflectionList.

/**
 * {@inheritDoc}
 */
@Override
public ReflectionList getReflectionList(File mtzFile, CompositeConfiguration properties) {
    ByteOrder byteOrder = ByteOrder.nativeOrder();
    FileInputStream fileInputStream;
    DataInputStream dataInputStream;
    try {
        fileInputStream = new FileInputStream(mtzFile);
        dataInputStream = new DataInputStream(fileInputStream);
        byte[] headerOffset = new byte[4];
        byte[] bytes = new byte[80];
        int offset = 0;
        // Eat "MTZ" title.
        dataInputStream.read(bytes, offset, 4);
        String mtzstr = new String(bytes);
        // Header offset.
        dataInputStream.read(headerOffset, offset, 4);
        // Machine stamp.
        dataInputStream.read(bytes, offset, 4);
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        int stamp = byteBuffer.order(ByteOrder.BIG_ENDIAN).getInt();
        String stampstr = Integer.toHexString(stamp);
        switch(stampstr.charAt(0)) {
            case '1':
            case '3':
                if (byteOrder.equals(ByteOrder.LITTLE_ENDIAN)) {
                    byteOrder = ByteOrder.BIG_ENDIAN;
                }
                break;
            case '4':
                if (byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
                    byteOrder = ByteOrder.LITTLE_ENDIAN;
                }
                break;
        }
        byteBuffer = ByteBuffer.wrap(headerOffset);
        int headerOffsetI = byteBuffer.order(byteOrder).getInt();
        // skip to header and parse
        dataInputStream.skipBytes((headerOffsetI - 4) * 4);
        for (Boolean parsing = true; parsing; dataInputStream.read(bytes, offset, 80)) {
            mtzstr = new String(bytes);
            parsing = parseHeader(mtzstr);
        }
    } catch (EOFException e) {
        String message = " MTZ end of file reached.";
        logger.log(Level.WARNING, message, e);
        return null;
    } catch (IOException e) {
        String message = " MTZ IO exception.";
        logger.log(Level.WARNING, message, e);
        return null;
    }
    // column identifiers
    foString = sigFoString = rFreeString = null;
    if (properties != null) {
        foString = properties.getString("fostring", null);
        sigFoString = properties.getString("sigfostring", null);
        rFreeString = properties.getString("rfreestring", null);
    }
    h = k = l = fo = sigFo = rFree = -1;
    fPlus = sigFPlus = fMinus = sigFMinus = rFreePlus = rFreeMinus = -1;
    fc = phiC = -1;
    boolean print = false;
    parseColumns(print);
    parseFcColumns(print);
    if (fo < 0 && fPlus < 0 && sigFo < 0 && sigFPlus < 0 && fc < 0 && phiC < 0) {
        logger.info(" The MTZ header contains insufficient information to generate the reflection list.");
        logger.info(" For non-default column labels set fostring/sigfostring in the properties file.");
        return null;
    }
    Column column;
    if (fo > 0) {
        column = (Column) columns.get(fo);
    } else if (fPlus > 0) {
        column = (Column) columns.get(fPlus);
    } else {
        column = (Column) columns.get(fc);
    }
    Dataset dataSet = (Dataset) dataSets.get(column.id - dsetOffset);
    if (logger.isLoggable(Level.INFO)) {
        StringBuilder sb = new StringBuilder();
        sb.append(format("\n Reading %s\n\n", mtzFile.getName()));
        sb.append(format(" Setting up reflection list based on MTZ file.\n"));
        sb.append(format("  Space group number: %d (name: %s)\n", spaceGroupNum, SpaceGroup.spaceGroupNames[spaceGroupNum - 1]));
        sb.append(format("  Resolution:         %8.3f\n", 0.999999 * resHigh));
        sb.append(format("  Cell:               %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n", dataSet.cell[0], dataSet.cell[1], dataSet.cell[2], dataSet.cell[3], dataSet.cell[4], dataSet.cell[5]));
        logger.info(sb.toString());
    }
    Crystal crystal = new Crystal(dataSet.cell[0], dataSet.cell[1], dataSet.cell[2], dataSet.cell[3], dataSet.cell[4], dataSet.cell[5], SpaceGroup.spaceGroupNames[spaceGroupNum - 1]);
    double sampling = 0.6;
    if (properties != null) {
        sampling = properties.getDouble("sampling", 0.6);
    }
    Resolution resolution = new Resolution(0.999999 * resHigh, sampling);
    return new ReflectionList(crystal, resolution, properties);
}
Also used : ByteOrder(java.nio.ByteOrder) IOException(java.io.IOException) ReflectionList(ffx.crystal.ReflectionList) DataInputStream(java.io.DataInputStream) ByteBuffer(java.nio.ByteBuffer) FileInputStream(java.io.FileInputStream) EOFException(java.io.EOFException) Crystal(ffx.crystal.Crystal) Resolution(ffx.crystal.Resolution)

Aggregations

ByteOrder (java.nio.ByteOrder)111 ByteBuffer (java.nio.ByteBuffer)39 IOException (java.io.IOException)8 Test (org.junit.Test)7 QuickTest (com.hazelcast.test.annotation.QuickTest)5 DataInputStream (java.io.DataInputStream)5 FileInputStream (java.io.FileInputStream)5 UUID (java.util.UUID)5 ParallelJVMTest (com.hazelcast.test.annotation.ParallelJVMTest)4 HKL (ffx.crystal.HKL)3 DataOutputStream (java.io.DataOutputStream)3 EOFException (java.io.EOFException)3 FileOutputStream (java.io.FileOutputStream)3 ShortBuffer (java.nio.ShortBuffer)3 ArrayList (java.util.ArrayList)3 Element (org.jdom.Element)3 InvalidDumpFormatException (com.ibm.j9ddr.corereaders.InvalidDumpFormatException)2 Point (com.revolsys.geometry.model.Point)2 Crystal (ffx.crystal.Crystal)2 BigInteger (java.math.BigInteger)2