Search in sources :

Example 11 with IniParser

use of loci.common.IniParser in project bioformats by openmicroscopy.

the class MetaSupportAutogen method main.

// -- Main method --
public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        System.out.println("Usage: java MetaSupportAutogen ome-xml-version");
        System.out.println("    E.g.: java MetaSupportAutogen 2012-06");
        System.exit(1);
    }
    String version = args[0];
    // create needed directories
    File doc = new File("doc");
    if (!doc.exists()) {
        boolean success = doc.mkdir();
        if (!success) {
            throw new IOException("Could not create " + doc.getAbsolutePath());
        }
    }
    File docMeta = new File(doc, "meta");
    if (!docMeta.exists()) {
        boolean success = docMeta.mkdir();
        if (!success) {
            throw new IOException("Could not create " + docMeta.getAbsolutePath());
        }
    }
    // initialize Velocity
    VelocityEngine ve = VelocityTools.createEngine();
    VelocityContext context = VelocityTools.createContext();
    // parse supported properties list
    MetaSupportList supportList = new MetaSupportList(version);
    context.put("q", supportList);
    // retrieve the table of format page names
    IniParser parser = new IniParser();
    parser.setCommentDelimiter(null);
    IniList data = parser.parseINI(FORMAT_PAGES, MetaSupportAutogen.class);
    for (String handler : supportList.handlers()) {
        supportList.setHandler(handler);
        supportList.setPageName("metadata/" + handler);
    }
    // generate master table of metadata properties
    VelocityTools.processTemplate(ve, context, "doc/meta-summary.vm", "../../docs/sphinx/metadata-summary.rst");
    // generate metadata property support documentation for each handler
    for (String handler : supportList.handlers()) {
        supportList.setHandler(handler);
        String pagename = supportList.getPageName();
        if (pagename != null) {
            VelocityTools.processTemplate(ve, context, "doc/MetadataSupport.vm", "../../docs/sphinx/" + pagename + ".rst");
        }
    }
}
Also used : IniParser(loci.common.IniParser) VelocityEngine(org.apache.velocity.app.VelocityEngine) IniList(loci.common.IniList) VelocityContext(org.apache.velocity.VelocityContext) IOException(java.io.IOException) File(java.io.File)

Example 12 with IniParser

use of loci.common.IniParser in project bioformats by openmicroscopy.

the class FakeReader method initFile.

@Override
protected void initFile(String id) throws FormatException, IOException {
    if (!checkSuffix(id, "fake")) {
        if (checkSuffix(id, "fake.ini")) {
            id = id.substring(0, id.lastIndexOf("."));
        }
        Location file = new Location(id).getAbsoluteFile();
        if (!file.exists()) {
            Location dir = file.getParentFile();
            String[] list = dir.list(true);
            String name = file.getName();
            name = name.substring(0, name.lastIndexOf("."));
            for (String f : list) {
                if (checkSuffix(f, "fake") && f.startsWith(name)) {
                    id = new Location(dir, f).getAbsolutePath();
                    break;
                }
            }
        }
    }
    // Logic copied from deltavision. This should probably be refactored into
    // a helper method "replaceBySuffix" or something.
    super.initFile(id);
    findLogFiles();
    String path = id;
    Location location = new Location(id);
    String[] tokens = null;
    if (location.exists()) {
        path = location.getAbsoluteFile().getName();
        if (path.startsWith("Field")) {
            Location root = location.getAbsoluteFile().getParentFile();
            if (root != null) {
                root = root.getParentFile();
                if (root != null) {
                    root = root.getParentFile();
                    if (root != null) {
                        root = root.getParentFile();
                        if (isSPWStructure(root.getAbsolutePath())) {
                            tokens = extractTokensFromFakeSeries(root.getAbsolutePath());
                            // makes sure that getSeriesUsedFiles returns correctly
                            currentId = root.getAbsolutePath();
                        }
                    }
                }
            }
        }
    }
    if (location.isDirectory() && isSPWStructure(location.getAbsolutePath())) {
        tokens = extractTokensFromFakeSeries(location.getAbsolutePath());
    } else if (tokens == null) {
        String noExt = path.substring(0, path.lastIndexOf("."));
        tokens = noExt.split(TOKEN_SEPARATOR);
    }
    String name = null;
    // default
    int thumbSizeX = 0;
    // default
    int thumbSizeY = 0;
    int pixelType = DEFAULT_PIXEL_TYPE;
    // default
    int bitsPerPixel = 0;
    int rgb = DEFAULT_RGB_CHANNEL_COUNT;
    String dimOrder = DEFAULT_DIMENSION_ORDER;
    boolean orderCertain = true;
    boolean little = true;
    boolean interleaved = false;
    boolean indexed = false;
    boolean falseColor = false;
    boolean metadataComplete = true;
    boolean thumbnail = false;
    boolean withMicrobeam = false;
    int seriesCount = 1;
    int lutLength = 3;
    String acquisitionDate = null;
    int screens = 0;
    int plates = 0;
    int plateRows = 0;
    int plateCols = 0;
    int fields = 0;
    int plateAcqs = 0;
    Integer defaultColor = null;
    ArrayList<Integer> color = new ArrayList<Integer>();
    ArrayList<IniTable> seriesTables = new ArrayList<IniTable>();
    // add properties file values to list of tokens.
    if (iniFile != null) {
        IniParser parser = new IniParser();
        IniList list = parser.parseINI(new File(iniFile));
        List<String> newTokens = new ArrayList<String>();
        // Unclear what to do with other headers...
        IniTable table = list.getTable(IniTable.DEFAULT_HEADER);
        if (table != null) {
            for (Map.Entry<String, String> entry : table.entrySet()) {
                newTokens.add(entry.getKey() + "=" + entry.getValue());
            }
        }
        table = list.getTable("GlobalMetadata");
        if (table != null) {
            for (Map.Entry<String, String> entry : table.entrySet()) {
                addGlobalMeta(entry.getKey(), entry.getValue());
            }
        }
        String[] newTokArr = newTokens.toArray(new String[0]);
        String[] oldTokArr = tokens;
        tokens = new String[newTokArr.length + oldTokArr.length];
        System.arraycopy(oldTokArr, 0, tokens, 0, oldTokArr.length);
        System.arraycopy(newTokArr, 0, tokens, oldTokArr.length, newTokArr.length);
        // Properties overrides file name values
        int seriesIndex = 0;
        while (list.getTable("series_" + seriesIndex) != null) {
            seriesTables.add(list.getTable("series_" + seriesIndex));
            seriesIndex++;
        }
    }
    // parse tokens from filename
    for (String token : tokens) {
        if (name == null) {
            // first token is the image name
            name = token;
            continue;
        }
        int equals = token.indexOf('=');
        if (equals < 0) {
            LOGGER.warn("ignoring token: {}", token);
            continue;
        }
        String key = token.substring(0, equals);
        String value = token.substring(equals + 1);
        boolean boolValue = value.equals("true");
        double doubleValue;
        try {
            doubleValue = Double.parseDouble(value);
        } catch (NumberFormatException exc) {
            doubleValue = Double.NaN;
        }
        int intValue = Double.isNaN(doubleValue) ? -1 : (int) doubleValue;
        if (key.equals("sizeX"))
            sizeX = intValue;
        else if (key.equals("sizeY"))
            sizeY = intValue;
        else if (key.equals("sizeZ"))
            sizeZ = intValue;
        else if (key.equals("sizeC"))
            sizeC = intValue;
        else if (key.equals("sizeT"))
            sizeT = intValue;
        else if (key.equals("thumbSizeX"))
            thumbSizeX = intValue;
        else if (key.equals("thumbSizeY"))
            thumbSizeY = intValue;
        else if (key.equals("pixelType")) {
            pixelType = FormatTools.pixelTypeFromString(value);
        } else if (key.equals("bitsPerPixel"))
            bitsPerPixel = intValue;
        else if (key.equals("rgb"))
            rgb = intValue;
        else if (key.equals("dimOrder"))
            dimOrder = value.toUpperCase();
        else if (key.equals("orderCertain"))
            orderCertain = boolValue;
        else if (key.equals("little"))
            little = boolValue;
        else if (key.equals("interleaved"))
            interleaved = boolValue;
        else if (key.equals("indexed"))
            indexed = boolValue;
        else if (key.equals("falseColor"))
            falseColor = boolValue;
        else if (key.equals("metadataComplete"))
            metadataComplete = boolValue;
        else if (key.equals("thumbnail"))
            thumbnail = boolValue;
        else if (key.equals("series"))
            seriesCount = intValue;
        else if (key.equals("lutLength"))
            lutLength = intValue;
        else if (key.equals("scaleFactor"))
            scaleFactor = doubleValue;
        else if (key.equals("exposureTime"))
            exposureTime = new Time((float) doubleValue, UNITS.SECOND);
        else if (key.equals("acquisitionDate"))
            acquisitionDate = value;
        else if (key.equals("screens"))
            screens = intValue;
        else if (key.equals("plates"))
            plates = intValue;
        else if (key.equals("plateRows"))
            plateRows = intValue;
        else if (key.equals("plateCols"))
            plateCols = intValue;
        else if (key.equals("fields"))
            fields = intValue;
        else if (key.equals("plateAcqs"))
            plateAcqs = intValue;
        else if (key.equals("withMicrobeam"))
            withMicrobeam = boolValue;
        else if (key.equals("annLong"))
            annLong = intValue;
        else if (key.equals("annDouble"))
            annDouble = intValue;
        else if (key.equals("annMap"))
            annMap = intValue;
        else if (key.equals("annComment"))
            annComment = intValue;
        else if (key.equals("annBool"))
            annBool = intValue;
        else if (key.equals("annTime"))
            annTime = intValue;
        else if (key.equals("annTag"))
            annTag = intValue;
        else if (key.equals("annTerm"))
            annTerm = intValue;
        else if (key.equals("annXml"))
            annXml = intValue;
        else if (key.equals("ellipses"))
            ellipses = intValue;
        else if (key.equals("labels"))
            labels = intValue;
        else if (key.equals("lines"))
            lines = intValue;
        else if (key.equals("masks"))
            masks = intValue;
        else if (key.equals("points"))
            points = intValue;
        else if (key.equals("polygons"))
            polygons = intValue;
        else if (key.equals("polylines"))
            polylines = intValue;
        else if (key.equals("rectangles"))
            rectangles = intValue;
        else if (key.equals("physicalSizeX"))
            physicalSizeX = parseLength(value, getPhysicalSizeXUnitXsdDefault());
        else if (key.equals("physicalSizeY"))
            physicalSizeY = parseLength(value, getPhysicalSizeYUnitXsdDefault());
        else if (key.equals("physicalSizeZ"))
            physicalSizeZ = parseLength(value, getPhysicalSizeZUnitXsdDefault());
        else if (key.equals("color")) {
            defaultColor = parseColor(value);
        } else if (key.startsWith("color_")) {
            // 'color' and 'color_x' can be used together, but 'color_x' takes
            // precedence.  'color' will in that case be used for any missing
            // or invalid 'color_x' values.
            int index = Integer.parseInt(key.substring(key.indexOf('_') + 1));
            while (index >= color.size()) {
                color.add(null);
            }
            color.set(index, parseColor(value));
        }
    }
    // do some sanity checks
    if (sizeX < 1)
        throw new FormatException("Invalid sizeX: " + sizeX);
    if (sizeY < 1)
        throw new FormatException("Invalid sizeY: " + sizeY);
    if (sizeZ < 1)
        throw new FormatException("Invalid sizeZ: " + sizeZ);
    if (sizeC < 1)
        throw new FormatException("Invalid sizeC: " + sizeC);
    if (sizeT < 1)
        throw new FormatException("Invalid sizeT: " + sizeT);
    if (thumbSizeX < 0) {
        throw new FormatException("Invalid thumbSizeX: " + thumbSizeX);
    }
    if (thumbSizeY < 0) {
        throw new FormatException("Invalid thumbSizeY: " + thumbSizeY);
    }
    if (rgb < 1 || rgb > sizeC || sizeC % rgb != 0) {
        throw new FormatException("Invalid sizeC/rgb combination: " + sizeC + "/" + rgb);
    }
    getDimensionOrder(dimOrder);
    if (falseColor && !indexed) {
        throw new FormatException("False color images must be indexed");
    }
    if (seriesCount < 1) {
        throw new FormatException("Invalid seriesCount: " + seriesCount);
    }
    if (lutLength < 1) {
        throw new FormatException("Invalid lutLength: " + lutLength);
    }
    // populate SPW metadata
    MetadataStore store = makeFilterMetadata();
    boolean hasSPW = screens > 0 || plates > 0 || plateRows > 0 || plateCols > 0 || fields > 0 || plateAcqs > 0;
    if (hasSPW) {
        if (screens < 0)
            screens = 0;
        if (plates <= 0)
            plates = 1;
        if (plateRows <= 0)
            plateRows = 1;
        if (plateCols <= 0)
            plateCols = 1;
        if (fields <= 0)
            fields = 1;
        if (plateAcqs <= 0)
            plateAcqs = 1;
        // generate SPW metadata and override series count to match
        int imageCount = populateSPW(store, screens, plates, plateRows, plateCols, fields, plateAcqs, withMicrobeam);
        if (imageCount > 0)
            seriesCount = imageCount;
        else
            // failed to generate SPW metadata
            hasSPW = false;
    }
    // populate core metadata
    int effSizeC = sizeC / rgb;
    core.clear();
    for (int s = 0; s < seriesCount; s++) {
        CoreMetadata ms = new CoreMetadata();
        core.add(ms);
        ms.sizeX = sizeX;
        ms.sizeY = sizeY;
        ms.sizeZ = sizeZ;
        ms.sizeC = sizeC;
        ms.sizeT = sizeT;
        ms.thumbSizeX = thumbSizeX;
        ms.thumbSizeY = thumbSizeY;
        ms.pixelType = pixelType;
        ms.bitsPerPixel = bitsPerPixel;
        ms.imageCount = sizeZ * effSizeC * sizeT;
        ms.rgb = rgb > 1;
        ms.dimensionOrder = dimOrder;
        ms.orderCertain = orderCertain;
        ms.littleEndian = little;
        ms.interleaved = interleaved;
        ms.indexed = indexed;
        ms.falseColor = falseColor;
        ms.metadataComplete = metadataComplete;
        ms.thumbnail = thumbnail;
    }
    // populate OME metadata
    boolean planeInfo = (exposureTime != null) || seriesTables.size() > 0;
    MetadataTools.populatePixels(store, this, planeInfo);
    fillExposureTime(store);
    fillPhysicalSizes(store);
    for (int currentImageIndex = 0; currentImageIndex < seriesCount; currentImageIndex++) {
        if (currentImageIndex < seriesTables.size()) {
            parseSeriesTable(seriesTables.get(currentImageIndex), store, currentImageIndex);
        }
        String imageName = currentImageIndex > 0 ? name + " " + (currentImageIndex + 1) : name;
        store.setImageName(imageName, currentImageIndex);
        fillAcquisitionDate(store, acquisitionDate, currentImageIndex);
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            Color channel = defaultColor == null ? null : new Color(defaultColor);
            if (c < color.size() && color.get(c) != null) {
                channel = new Color(color.get(c));
            }
            if (channel != null) {
                store.setChannelColor(channel, currentImageIndex, c);
            }
        }
        fillAnnotations(store, currentImageIndex);
        fillRegions(store, currentImageIndex);
    }
    // for indexed color images, create lookup tables
    if (indexed) {
        if (pixelType == FormatTools.UINT8) {
            // create 8-bit LUTs
            final int num = 256;
            createIndexMap(num);
            lut8 = new byte[sizeC][lutLength][num];
            // linear ramp
            for (int c = 0; c < sizeC; c++) {
                for (int i = 0; i < lutLength; i++) {
                    for (int index = 0; index < num; index++) {
                        lut8[c][i][index] = (byte) indexToValue[c][index];
                    }
                }
            }
        } else if (pixelType == FormatTools.UINT16) {
            // create 16-bit LUTs
            final int num = 65536;
            createIndexMap(num);
            lut16 = new short[sizeC][lutLength][num];
            // linear ramp
            for (int c = 0; c < sizeC; c++) {
                for (int i = 0; i < lutLength; i++) {
                    for (int index = 0; index < num; index++) {
                        lut16[c][i][index] = (short) indexToValue[c][index];
                    }
                }
            }
        }
    // NB: Other pixel types will have null LUTs.
    }
}
Also used : IniParser(loci.common.IniParser) IniList(loci.common.IniList) Color(ome.xml.model.primitives.Color) ArrayList(java.util.ArrayList) Time(ome.units.quantity.Time) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) IniTable(loci.common.IniTable) File(java.io.File) Map(java.util.Map) Location(loci.common.Location)

Example 13 with IniParser

use of loci.common.IniParser in project bioformats by openmicroscopy.

the class SISReader method initStandardMetadata.

// -- Internal BaseTiffReader API methods --
/* @see BaseTiffReader#initStandardMetadata() */
@Override
protected void initStandardMetadata() throws FormatException, IOException {
    super.initStandardMetadata();
    IFD ifd = ifds.get(0);
    CoreMetadata m = core.get(0);
    String iniMetadata = ifd.getIFDTextValue(SIS_INI_TAG);
    if (iniMetadata != null) {
        IniParser parser = new IniParser();
        IniList ini = parser.parseINI(new BufferedReader(new StringReader(iniMetadata)));
        IniTable dimensions = ini.getTable("Dimension");
        int z = Integer.parseInt(dimensions.get("Z"));
        int c = Integer.parseInt(dimensions.get("Band"));
        int t = Integer.parseInt(dimensions.get("Time"));
        if (z * c * t == ifds.size()) {
            m.sizeZ = z;
            m.sizeT = t;
            m.sizeC *= c;
        }
    // TODO : parse more metadata from the INI tables
    }
    if (!ifd.containsKey(SIS_TAG)) {
        // TODO: parse this metadata more thoroughly
        in.seek(ifd.getIFDLongValue(SIS_TAG_2, 0));
        while (!in.readString(2).equals("IS")) {
            in.seek(in.getFilePointer() - 1);
        }
        in.skipBytes(28);
        in.seek(in.readLong() - 84);
        physicalSizeX = in.readDouble() * 1000;
        physicalSizeY = in.readDouble() * 1000;
        return;
    }
    long metadataPointer = ifd.getIFDLongValue(SIS_TAG, 0);
    in.seek(metadataPointer);
    in.skipBytes(4);
    in.skipBytes(6);
    int minute = in.readShort();
    int hour = in.readShort();
    int day = in.readShort();
    int month = in.readShort() + 1;
    int year = 1900 + in.readShort();
    acquisitionDate = year + "-" + month + "-" + day + " " + hour + ":" + minute;
    acquisitionDate = DateTools.formatDate(acquisitionDate, "yyyy-M-d H:m");
    in.skipBytes(6);
    imageName = in.readCString();
    if ((in.getFilePointer() % 2) == 1) {
        in.skipBytes(1);
    }
    short check = in.readShort();
    while (check != 7 && check != 8) {
        check = in.readShort();
        if (check == 0x700 || check == 0x800 || check == 0xa00) {
            in.skipBytes(1);
            break;
        }
    }
    in.skipBytes(4);
    long pos = in.readInt() & 0xffffffffL;
    if (pos >= in.length()) {
        return;
    }
    in.seek(pos);
    in.skipBytes(12);
    physicalSizeX = in.readDouble();
    physicalSizeY = in.readDouble();
    if (Math.abs(physicalSizeX - physicalSizeY) > Constants.EPSILON) {
        // ??
        physicalSizeX = physicalSizeY;
        physicalSizeY = in.readDouble();
    }
    in.skipBytes(8);
    magnification = in.readDouble();
    int cameraNameLength = in.readShort();
    channelName = in.readCString();
    if (channelName.length() > 128) {
        channelName = "";
    }
    int length = (int) Math.min(cameraNameLength, channelName.length());
    if (length > 0) {
        cameraName = channelName.substring(0, length);
    }
    // these are no longer valid
    getGlobalMetadata().remove("XResolution");
    getGlobalMetadata().remove("YResolution");
    addGlobalMeta("Nanometers per pixel (X)", physicalSizeX);
    addGlobalMeta("Nanometers per pixel (Y)", physicalSizeY);
    addGlobalMeta("Magnification", magnification);
    addGlobalMeta("Channel name", channelName);
    addGlobalMeta("Camera name", cameraName);
    addGlobalMeta("Image name", imageName);
    addGlobalMeta("Acquisition date", acquisitionDate);
}
Also used : IniParser(loci.common.IniParser) IniList(loci.common.IniList) IFD(loci.formats.tiff.IFD) IniTable(loci.common.IniTable) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) CoreMetadata(loci.formats.CoreMetadata)

Aggregations

IniParser (loci.common.IniParser)13 IniList (loci.common.IniList)12 BufferedReader (java.io.BufferedReader)11 IniTable (loci.common.IniTable)11 CoreMetadata (loci.formats.CoreMetadata)8 Location (loci.common.Location)7 StringReader (java.io.StringReader)6 InputStreamReader (java.io.InputStreamReader)5 RandomAccessInputStream (loci.common.RandomAccessInputStream)4 FormatException (loci.formats.FormatException)4 MetadataStore (loci.formats.meta.MetadataStore)4 File (java.io.File)3 Length (ome.units.quantity.Length)3 FileInputStream (java.io.FileInputStream)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 Time (ome.units.quantity.Time)2 Hashtable (java.util.Hashtable)1 Map (java.util.Map)1 DefaultMutableTreeNode (javax.swing.tree.DefaultMutableTreeNode)1