From 06e6e057acf80f7d1a2e1068adcc18e64650b4c4 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Mon, 26 Mar 2018 10:27:02 +0100 Subject: Added Documentation, and A LOT of stuff to build up the further tiers --- src/conversion/czi/czi.ts | 678 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 572 insertions(+), 106 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index addf43e..aa1cfcc 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -1,16 +1,19 @@ - +//imports required to make the conversion import * as fs from 'fs'; import { logger } from '../../logger'; import * as sharp from 'sharp'; -import * as parsexml from 'xml-parser'; import { SharpInstance } from 'sharp'; +import * as parsexml from 'xml-parser'; +//various constants for placing files and defining tiles const extractionDirectory: string = '/cs/scratch/cjd24/0701-extraction/'; -const outputImageDirectory: string = '/cs/scratch/cjd24/0701-extraction-processed2/' +const outputImageData: string = '/cs/scratch/cjd24/0701-extraction-processed/' +const outputImageDirectory: string = '/cs/scratch/cjd24/0701-extraction-processed/data/' const tileOverlap: number = 0; const tileSize: number = 1024; const maxZoom: number = 64; +//Interfaces used to define the tiles incoming from the CZI extraction interface Dimension { Dimension: string; Start: number; @@ -29,6 +32,8 @@ interface Segment { UsedSize: number; Data: SubBlock; } + +//Interface used to define the pixel-bounds of a 'section' within the image class TileBounds { public left!: number; public right!: number; @@ -41,6 +46,9 @@ class TileBounds { this.bottom = bottomBound; } } + +//Interface used to define the structure of the "supportedViews" section +//of the protocol specification for scalable images interface SupportedViews { scalable_image: { width: number; @@ -49,20 +57,23 @@ interface SupportedViews { { channel_id: string; channel_name: string; - metadata?: {}; + metadata?: parsexml.Node[]; } ]; real_width?: { - value: number; - units: string; + value?: number; + units?: string; }; real_height?: { - value: number; - units: string; + value?: number; + units?: string; }; metadata?: {}; } } + +//The following are interfaces for the Custom object storing Information +//about the CUSTOM pyramid being created for this image interface CZITile { x_offset: number; y_offset: number; @@ -72,24 +83,35 @@ interface CZITile { } interface CZIHeightMap { zoom_level: number, + tile_width_count?: number, + tile_height_count?: number, plane: CZITile[][]; } interface WholeCZIHierarchy { c_values: [{ channel_id: string, height_map: CZIHeightMap[]; - }]; + }], + c_value_count: number, + zoom_level_count: number; + total_files: number; } +/* + * Simple function to find the tile bounds version of an original tile in the base image + */ const getOriginalTileBounds: Function = function(originalTile: Segment): (TileBounds | null) { const bounds: TileBounds = new TileBounds(-1, -1, -1, -1); + //loop over all dimensions to get the x and y for (const dimension of originalTile.Data.DirectoryEntry.DimensionEntries) { switch (dimension.Dimension) { + //If we have found x, then match the start and width case 'X': bounds.left = dimension.Start; bounds.right = bounds.left + dimension.Size; continue; + //If we have found y, then match the top and bottom case 'Y': bounds.top = dimension.Start; bounds.bottom = bounds.top + dimension.Size; @@ -99,20 +121,26 @@ const getOriginalTileBounds: Function = function(originalTile: Segment): (TileBo } } + //If one of the bounds was not created, then there must have been an error if (bounds.left < 0 || bounds.right < 0 || bounds.top < 0 || bounds.bottom < 0) { return null; } - + //Successful return return bounds; }; +/* + * Function used to find which of the original base tiles are + * overlapping with the area of the to-be-created tile + */ const findRelatedTiles: Function = function(activeSegments: Segment[], desired: TileBounds): Segment[] { const relatedTiles: Segment[] = []; + //For all tiles within the region being checked for (const baseTile of activeSegments) { + //find out the coordinates of the current base tile being checked let origCoords: TileBounds | null; - if ((origCoords = getOriginalTileBounds(baseTile)) === null) { throw new Error('There was a Sad Boi error'); } @@ -141,6 +169,8 @@ const findRelatedTiles: Function = function(activeSegments: Segment[], desired: ((desired.top < origCoords.top) && (desired.bottom > origCoords.bottom))) { + //If all of the if statements have passed, then this tile + //is part of the overlap for the new tile to be created. relatedTiles.push(baseTile); } } @@ -149,24 +179,40 @@ const findRelatedTiles: Function = function(activeSegments: Segment[], desired: return relatedTiles; }; +/* + * This gets the particular dimension from a segment given a segment and dimesnion ID + */ const getDimension: Function = function(segment: Segment, name: string): Dimension { + + //loop over all dimensions within this segment for (const dimension of segment.Data.DirectoryEntry.DimensionEntries) { + //If the current dimension is the one we are looking for then return it. if (dimension.Dimension === name) { return dimension; } } + //If we have gotten to here, then the dimension doesnt exist, so throw error. throw new Error('Dimension: ' + name + " doesn't exist for segment: " + segment); }; +/* + * This takes a selection of segments and ensures that they are ordered + * left to right, and top to bottom like the words in a book, so that the + * stiching process will take the correct slice from them all. + * (this is based on the pixel x-y coords of the segment.) + */ const orderSegments: Function = function(segments: Segment[]): Segment[][] { const output: Segment[][] = []; + //So long as there is at least 2 segments to order if (segments.length > 1) { let xCoords: number[] = []; let yCoords: number[] = []; // Get all x/y's; + // However also ensure that all of the segments to be ordered, all come + // from the same value of 'C' dimension, otherwise there could be overlaps. const initC: number = getDimension(segments[0], 'C').Start; for (const seg of segments) { if (getDimension(seg, 'C').Start !== initC) { @@ -175,7 +221,7 @@ const orderSegments: Function = function(segments: Segment[]): Segment[][] { xCoords.push(getDimension(seg, 'X').Start); yCoords.push(getDimension(seg, 'Y').Start); } - // Filter to get Uniaue Values + // Filter to get Unique Values xCoords = xCoords.filter( (item: number, index: number, array: number[]) => array.indexOf(item) === index); yCoords = yCoords.filter( @@ -209,52 +255,75 @@ const orderSegments: Function = function(segments: Segment[]): Segment[][] { // Return the result return output; - } else { - output.push(segments); - return output; } + + //There is only one segment, so no need to re-order. + return [segments]; }; +/* + * Takes a base tile, and the whole bounds of a new tile, and uses this + * to calculate the region within the base tile that is overlapping the new tile + * to be extracted. + */ const findRegionToExtract: Function = function(segment: Segment, desired: TileBounds): TileBounds { + + //get the base tile area and create an object for the chunk to extract const baseBounds: TileBounds = getOriginalTileBounds(segment); let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); + // check if the new tile overlaps the leftmost boundary if (desired.left <= baseBounds.left) { chunkToExtract.left = 0; } else { chunkToExtract.left = desired.left - baseBounds.left; } + // check if the new tile overlaps the rightmost boundary if (desired.right >= baseBounds.right) { chunkToExtract.right = baseBounds.right - baseBounds.left; } else { chunkToExtract.right = desired.right - baseBounds.left; } + // check if the new tile overlaps the top boundary if (desired.top <= baseBounds.top) { chunkToExtract.top = 0; } else { chunkToExtract.top = desired.top - baseBounds.top; } + // check if the new tile overlaps the bottom boundary if (desired.bottom >= baseBounds.bottom) { chunkToExtract.bottom = baseBounds.bottom - baseBounds.top; } else { chunkToExtract.bottom = desired.bottom - baseBounds.top; } + //return the slice within the base tile for extraction return chunkToExtract; }; +/* + * Take an ordered selection of segments and cookie cutter out a tile from this + * into a new image + */ const extractAndStitchChunks: Function = async function(segments: Segment[][], desiredRegion: TileBounds): Promise { + //create a buffer for the rows part of raw image data let tileVerticalBuffer: Buffer[] = []; + //for all ros (y coords) in the image for (const segRow of segments) { + //create a buffer for this row let tileRow: Buffer[] = []; let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); + + //For all of the columns within this row for (const segCol of segRow) { + //find out the region of the base tile to be added to the new image chunkToExtract = findRegionToExtract(segCol, desiredRegion); + //extract this section of image data into a sharp buffer let data: Promise = sharp(`${extractionDirectory}${segCol.Data.Data}`) .extract({ @@ -265,134 +334,376 @@ const extractAndStitchChunks: Function = async function(segments: Segment[][], d }) .toBuffer(); + //push this data into the row buffer tileRow.push(await data); } + //prepare variables to squash all of the column data into one, for this row let imageVerticalSlice: SharpInstance = sharp(tileRow[0]); let bufferBound = findRegionToExtract(segRow[0], desiredRegion); + //check if the inital chunk needs to be extended to support the other columns if ((bufferBound.right - bufferBound.left) < (tileSize - tileOverlap)) { - imageVerticalSlice = await imageVerticalSlice.extend( + imageVerticalSlice = await imageVerticalSlice.background({r: 0, g: 0, b: 0, alpha: 0}).extend( {top:0, left:0, bottom:0, right: (tileSize - (bufferBound.right - bufferBound.left))}); } + //for every column along this row, join it to the previous column data for (let index = 1; index < segRow.length; index++) { imageVerticalSlice = await imageVerticalSlice .overlayWith(tileRow[index], {top: 0, left: (bufferBound.right - bufferBound.left) + ((index -1) * tileSize)}); } + //add this horizontal data buffer to the vertical buffer tileVerticalBuffer.push(await imageVerticalSlice.toBuffer()); } + //prepare variables used to combine all rows into one image let finalImage: SharpInstance = sharp(tileVerticalBuffer[0]); let bufferBound = findRegionToExtract(segments[0][0], desiredRegion); + //Check if the inital row needs to be extended to support further rows if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) { - finalImage = await finalImage.extend( + finalImage = await finalImage.background({r: 0, g: 0, b: 0, alpha: 0}).extend( {top:0, left:0, bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), right: 0}); } + //For all further rows in the image, combine it with the previous rows' data for (let index = 1; index < segments.length; index++) { finalImage = finalImage.overlayWith( tileVerticalBuffer[index], {top: getDimension(segments[index -1][0], 'Y').Size, left: 0}); } + //return the finalised image. return finalImage; }; +/* + * Used to remove obtuse JSON data, where it is not needed in the SupportedView object + */ +const cleanSupportedViewObject: Function = function(obj: parsexml.Node[]): Object { + let newChild: any = {}; + let hasAttr: boolean = false, hasChildren: boolean = false, hasContent: boolean = false; + + //for all nodes in the json object + for (const node of obj) { + + //Check if this node has attributes + if (node.attributes !== undefined && node.attributes !== null && Object.keys(node.attributes).length !== 0) + {hasAttr = true;} else {hasAttr = false;} + //Check for further children + if (node.children !== undefined && node.children.length > 0) + {hasChildren = true;} else {hasChildren = false;} + //Check for simple content object + if (node.content !== undefined && node.content !== null && node.content !== '') + {hasContent = true;} else {hasContent = false;} + + //If the Node has further children, then deal with this + if (hasChildren) { + let soloChildren: boolean = true; + + //Check if this node just contains children, or its own data too + newChild[node.name] = {} + if (hasAttr) { + //IF there are also attributes, then set this in the output + newChild[node.name].attributes = node.attributes; + soloChildren = false; + } + if (hasContent) { + //If there is also a 'content' then set this in the output + newChild[node.name].content = node.content; + soloChildren = false; + } + //If there are only chilren, then set this as this objects data + if (soloChildren) { + //recursively call this function to clean up sub-children too. + newChild[node.name] = cleanSupportedViewObject(node.children); + } else { + //Otherwise, if there is also data, then add a children object + newChild[node.name].children = cleanSupportedViewObject(node.children); + } + } + + //If this node only has attributes, then add this + else if (hasAttr) { + newChild[node.name] = {}; + + //Check for content too, if so, add a discrete child for this. + if (hasContent) { + newChild[node.name].content = node.content; + } + //add the attributes as a sub child regardless, + // since it exists on this key. + newChild[node.name].attributes = node.attributes; + } + + //If this node only has a content object then remove all other content + // and only attatch the content result as the value for this node key + else if (hasContent) { + newChild[node.name] = node.content; + } + } + return newChild; +}; +/* + * Clean up all vales of C within the JSON for supported views + */ +const cleanSupportedViews: Function = function(view: SupportedViews): void { + for (const channel of view.scalable_image.channels) { + channel.metadata = cleanSupportedViewObject(channel.metadata); + } +}; -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +//create the objects needed for parsing the XML object of the initial extraction. const dataBlocks: Segment[] = require(`${extractionDirectory}outputjson.json`).czi.filter( (s: Segment) => s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty'); -const inspect = require('util').inspect; -const metaXML: parsexml.Document = parsexml(fs.readFileSync(`${extractionDirectory}FILE-META-1.xml`, 'utf8')); - -let supportedViews: SupportedViews = {scalable_image: {width: -1, height: -1, channels: [{channel_id: '-1', channel_name: ''}], metadata: metaXML}}; -supportedViews.scalable_image.channels.pop(); let totalSizeX: number = -1; let totalSizeY: number = -1; +let supportedViews: SupportedViews = {scalable_image: {width: -1, height: -1, channels: [{channel_id: '-1', channel_name: ''}], metadata: {}}}; +supportedViews.scalable_image.channels.pop(); + +/* + * Function to parse the xml file from the original extraction from CZI, its nasty! + */ +const parseExtractedXML: Function = function(xmlFile: string): void { + // const inspect = require('util').inspect; // << Used when console logging stuff to prettify it + const metaXML: parsexml.Document = parsexml(fs.readFileSync(xmlFile, 'utf8')); + // parse the XML :( + // THE FOLLOWING 2 FOR LOOPS ARE DISGUSTING AND I HATE IT, AND I WISH I DIDNT WRITE IT BUT DON'T SEE ANY OTHER WAY TO DO IT LOL :'( + for (const child of metaXML.root.children) { + if (child.name === 'Metadata') { + for (const entry of child.children) { + if (entry.name === 'Information') { + for (const properties of entry.children) { + if (properties.name === 'Image') { + for (const property of properties.children) { + if (property.name === 'SizeX' && property.content) { + totalSizeX = Number.parseInt(property.content, 10); + supportedViews.scalable_image.width = totalSizeX; + continue; + } else if (property.name === 'SizeY' && property.content) { + totalSizeY = Number.parseInt(property.content, 10); + supportedViews.scalable_image.height = totalSizeY; + continue; + } else if(property.name === 'Dimensions') { + for (const chan of property.children) { + if (chan.name === 'Channels') { + for (const channel of chan.children) { + supportedViews.scalable_image.channels.push( + { + channel_id: channel.attributes.Id.split(":")[1], + channel_name: channel.attributes.Name, + metadata: channel.children + } + ); + } + } + } + } + } + } + } + } + } + } + } + for (const child of metaXML.root.children) { + if (child.name === 'Metadata') { + for (const entry of child.children) { + if (entry.name === 'Scaling') { + for (const properties of entry.children) { + if (properties.name === 'Items') { + for (const dist of properties.children) { + if (dist.name === 'Distance') { + if (dist.attributes.Id === 'X') { + supportedViews.scalable_image.real_width = {}; + for (const attr of dist.children) { + if (attr.name === 'Value' && attr.content !== undefined) + supportedViews.scalable_image.real_width.value = Number.parseFloat(attr.content) * 1000000 * totalSizeX; + if (attr.name === 'DefaultUnitFormat') + supportedViews.scalable_image.real_width.units = attr.content; + } + } + if (dist.attributes.Id === 'Y') { + supportedViews.scalable_image.real_height = {}; + for (const attr of dist.children) { + if (attr.name === 'Value' && attr.content !== undefined) + supportedViews.scalable_image.real_height.value = Number.parseFloat(attr.content) * 1000000 * totalSizeY; + if (attr.name === 'DefaultUnitFormat') + supportedViews.scalable_image.real_height.units = attr.content; + } + } + } + } + } + } + } + } + } + } + supportedViews.scalable_image.metadata = metaXML; +}; -// THE FOLLOWING FOR LOOP IS DISGUSTING AND I HATE IT, AND I WISH I DIDNT WRITE IT BUT DON'T SEE ANY OTHER WAY TO DO IT LOL :'( -for (const child of metaXML.root.children) { - if (child.name === 'Metadata') { - for (const entry of child.children) { - if (entry.name === 'Information') { - for (const properties of entry.children) { - if (properties.name === 'Image') { - for (const property of properties.children) { - if (property.name === 'SizeX' && property.content) { - totalSizeX = Number.parseInt(property.content, 10); - supportedViews.scalable_image.width = totalSizeX; - continue; - } else if (property.name === 'SizeY' && property.content) { - totalSizeY = Number.parseInt(property.content, 10); - supportedViews.scalable_image.height = totalSizeY; - continue; - } else if(property.name === 'Dimensions') { - for (const chan of property.children) { - if (chan.name === 'Channels') { - for (const channel of chan.children) { - supportedViews.scalable_image.channels.push( - { - channel_id: channel.attributes.Id.split(":")[1], - channel_name: channel.attributes.Name, - metadata: channel.children - } - ); - } - } - } - } - } - } - } - } - } - } -} -// Get all values of X and Y respectively. -const uniqueX: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'X').Start).filter( - (item: number, index: number, array: number[]) => array.indexOf(item) === index); -const uniqueY: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'Y').Start).filter( - (item: number, index: number, array: number[]) => array.indexOf(item) === index); - -const uniqueTileSizes: number[][] = []; -for (const seg of dataBlocks) { - - const x: number = getDimension(seg, 'X').Size; - const y: number = getDimension(seg, 'Y').Size; - let found: boolean = false; - for (const dimPair of uniqueTileSizes) { - if (x === dimPair[0] && y === dimPair[1]) { - found = true; - break; - } - } - if (!found) { - uniqueTileSizes.push([x, y]); - } -} +// // Get all values of X and Y respectively. +// const uniqueX: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'X').Start).filter( +// (item: number, index: number, array: number[]) => array.indexOf(item) === index); +// const uniqueY: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'Y').Start).filter( +// (item: number, index: number, array: number[]) => array.indexOf(item) === index); +// +// const uniqueTileSizes: number[][] = []; +// for (const seg of dataBlocks) { +// +// const x: number = getDimension(seg, 'X').Size; +// const y: number = getDimension(seg, 'Y').Size; +// let found: boolean = false; +// for (const dimPair of uniqueTileSizes) { +// if (x === dimPair[0] && y === dimPair[1]) { +// found = true; +// break; +// } +// } +// if (!found) { +// uniqueTileSizes.push([x, y]); +// } +// } + + + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Begin work on getting the new tiles all nice // +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +//used to filter all databocks to get certain values of 'C'. let filteredDataBlocks: Segment[] = []; -const filterC: Function = function(to: number): void { +const filterC: Function = function(c_value_filter: number): void +{ filteredDataBlocks = dataBlocks.filter( - (item: Segment, index: number, array: Segment[]) => getDimension(item, 'C').Start === to + (item: Segment, index: number, array: Segment[]) => getDimension(item, 'C').Start === c_value_filter ); }; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// Begin work on getting the new tiles all nice // Print out all of the related tiles to every new tile to be created. let filecoutner: number = 0; -async function extrapolateDimension(cVal: number, totalCs: number, maxZoomLevel: number): Promise { - console.log(`Stage (${cVal + 1}/${totalCs}): Task(0/${Math.ceil(totalSizeY/tileSize)}): 0% complete.`) - for (let ys: number = 0; ys < totalSizeY;) { - var timing = process.hrtime(); +/* + * This is used to create the next zoomed out tier of the given height map + */ +const zoomTier: Function = async function(previousHeightMap:CZIHeightMap): Promise { + + let ys:number = 0, timing = process.hrtime(), iterTimes: number[] = [50], avgItrTime: number;; + let newZoomTier: CZIHeightMap = {zoom_level: previousHeightMap.zoom_level * 2, plane: []}; + + //Check the condition where another zoom level does not make sense + if (previousHeightMap.plane.length === 1 && previousHeightMap.plane[0].length === 1) { + console.log( + ` Task(1/1): ` + + `Stage 100% complete. ` + + `(0 sec/iter) Stage was skipped as maximum sensible zoom level was reached. <<` + ); + return previousHeightMap; + } + + //For all rows within the previous plane + for (;ys < previousHeightMap.plane.length; ys += 2) { + timing = process.hrtime(); + let cziRow: CZITile[] = []; + //for all columns within the previous plane + for (let xs: number = 0; xs < previousHeightMap.plane[0].length; xs += 2) { + +// console.error(`ys: ${ys} ymax:${previousHeightMap.plane.length} xs: ${xs} xmax: ${previousHeightMap.plane[0].length}`) + + //combine 4 tiles into a new tile and scale down for this tier + + let combinedTile: SharpInstance; + //top left +// console.error(`SharpInitFile: ${previousHeightMap.plane[ys][xs].file}`) + combinedTile = await sharp(`${outputImageDirectory}${previousHeightMap.plane[ys][xs].file}`) + .background({r: 0, g: 0, b: 0, alpha: 0}).extend( + {top:0, left:0, bottom:tileSize, right: tileSize}); + + //combine top right + let moreToRight: boolean = (xs + 1) < previousHeightMap.plane[0].length; +// console.error(`More to right: ${moreToRight}`) + if (moreToRight) { +// console.error(`Top Right: ${previousHeightMap.plane[ys][xs + 1].file}`) + combinedTile = sharp(await combinedTile.overlayWith( + `${outputImageDirectory}${previousHeightMap.plane[ys][xs + 1].file}`, + {top: 0, left: tileSize}).toBuffer()); + } + + //combine bottom left + let moreToBottom: boolean = (ys + 1) < previousHeightMap.plane.length; +// console.error(`More to bottom: ${moreToBottom}`) + if (moreToBottom) { +// console.error(`Bottom Left: ${previousHeightMap.plane[ys + 1][xs].file}`) + combinedTile = sharp(await combinedTile.overlayWith( + `${outputImageDirectory}${previousHeightMap.plane[ys + 1][xs].file}`, + {top: tileSize, left: 0}).toBuffer()); + } + + //combine bottom right + if (moreToBottom && moreToRight) { +// console.error(`Bottom Right: ${previousHeightMap.plane[ys + 1][xs + 1].file}`) + combinedTile = sharp(await combinedTile.overlayWith( + `${outputImageDirectory}${previousHeightMap.plane[ys + 1][xs + 1].file}`, + {top: tileSize, left: tileSize}).toBuffer()); + } + +// console.error("\n\n"); + //rescale and push to file + await combinedTile.resize(tileSize, tileSize) + .toFile(`${outputImageDirectory}img-${filecoutner}`);/*.toFile(`${outputImageData}/thing/img-${filecoutner}`);*/ + + cziRow.push({ + x_offset: previousHeightMap.plane[ys][xs].x_offset, + y_offset: previousHeightMap.plane[ys][xs].y_offset, + width: previousHeightMap.plane[ys][xs].width * 2, + height: previousHeightMap.plane[ys][xs].height * 2, + file: `img-${filecoutner++}` + }); + finalCZIJson.total_files++; + } + + newZoomTier.plane.push(cziRow); + timing = process.hrtime(timing); + iterTimes.push(timing[0]); + avgItrTime = iterTimes.reduce((p, c, i) => {return p+(c-p)/(i+1)}, 0); + console.log( + ` Task(${ys/2}/${Math.floor(previousHeightMap.plane.length/2)}): ` + + `Stage ${Math.ceil(((ys/previousHeightMap.plane.length)*100) *100)/100}% complete. ` + + `(${timing[0]} sec/iter, est: ${((avgItrTime * (Math.floor(previousHeightMap.plane.length/2) - (ys/2 + 1)))/60).toFixed(2)} mins remain.)` + ); + } + newZoomTier.tile_height_count = newZoomTier.plane.length; + newZoomTier.tile_width_count = newZoomTier.plane[0].length; + + return newZoomTier; +} + +/* + * Big boi function to build up the base tier of each value of c, then builds + * Our pre-computed pyramid of the rest of the zoom levels. + */ +const extrapolateDimension:Function = async function(cVal: number, totalCs: number, maxZoom:number): Promise { + + let ys:number = 0, timing = process.hrtime(), iterTimes: number[] = [100], avgItrTime: number;; + //begin output for the base tier + console.log('========================================================='); + console.log(`>> Beginning Dimension Extrapolation for \'C\' : ${cVal}`); + console.log('========================================================='); + console.log(">> Computing base tier, this will take a while...\n") + let baseCZIHeightMap: CZIHeightMap = {zoom_level: 1, plane: []}, + width_in_tiles = 0, height_in_tiles = 0; + + console.log(`Stage (${cVal * Math.sqrt(maxZoom) + 1}/${totalCs}):`); + //For all rows within the total base pixel height + for (;ys < totalSizeY;) { + timing = process.hrtime(); + let cziRow: CZITile[] = []; for (let xs: number = 0; xs < totalSizeX; xs += tileSize) { const desired = new TileBounds ( xs - tileOverlap, @@ -402,30 +713,185 @@ async function extrapolateDimension(cVal: number, totalCs: number, maxZoomLevel: ); filterC(cVal); - // console.log(filteredDataBlocks.map((x: any) => x.Data.DirectoryEntry.DimensionEntries[2])); + cziRow.push({ + x_offset: xs, + y_offset: ys, + width: tileSize, + height: tileSize, + file: `img-${filecoutner}` + }); const sortedSegments: Segment[][] = orderSegments(findRelatedTiles(filteredDataBlocks, desired)); (await extractAndStitchChunks(sortedSegments, desired)).toFile(`${outputImageDirectory}img-${filecoutner++}`); + finalCZIJson.total_files++; + width_in_tiles = xs/tileSize; } + baseCZIHeightMap.plane.push(cziRow); ys += tileSize; timing = process.hrtime(timing); - console.log(`Stage (${cVal + 1}/${totalCs}): Task(${ys/tileSize}/${Math.ceil(totalSizeY/tileSize)}): ${Math.ceil(((ys/totalSizeY)*100) *100)/100}% complete. (${timing[0]} sec/iter)`); + iterTimes.push(timing[0]); + avgItrTime = iterTimes.reduce((p, c, i) => {return p+(c-p)/(i+1)}, 0); + console.log( + ` Task(${ys/tileSize}/${Math.ceil(totalSizeY/tileSize)}): ` + + `Stage ${Math.ceil(((ys/totalSizeY)*100) *100)/100}% complete. ` + + `(${timing[0]} sec/iter, est: ${((avgItrTime * (Math.ceil(totalSizeY/tileSize) - ys/tileSize))/60).toFixed(2)} mins remain.)` + ); + height_in_tiles = ys/tileSize; } - return []; -} + baseCZIHeightMap.tile_height_count = height_in_tiles; + baseCZIHeightMap.tile_width_count = width_in_tiles; -let finalCZIJson: WholeCZIHierarchy = {} as any; -async function main(): Promise { - for (const cval of supportedViews.scalable_image.channels) { - await extrapolateDimension(Number.parseInt(cval.channel_id, 10), supportedViews.scalable_image.channels.length, maxZoom).then(v => + //BUILD UP THE HIGHER ZOOM LAYERS. + console.log(">> Base tier complete for \'C\': " + cVal + "; Begin computing zoom tiers...\n") + + let retHeightMap: CZIHeightMap[] = [baseCZIHeightMap]; + for (let stage:number = 1; stage < Math.sqrt(maxZoom); stage++) { + console.log(`Stage (${cVal * Math.sqrt(maxZoom) + 1 + stage}/${totalCs}):`); + await zoomTier(retHeightMap[stage - 1]) + .then((v: CZIHeightMap) => { - finalCZIJson.c_values.push({channel_id: cval.channel_id, height_map: v}); - console.log(`Completed Tier: ${cval.channel_id}`); + retHeightMap.push(v); return; - }, err => { - console.error(err); } ); + writeJSONtoFile(`${outputImageData}stageMap-${stage}`, retHeightMap); + } + + console.log(`>> Completed Extrapolation for dimension, \'C\': ${cVal}\n\n`); + return retHeightMap; +} + +/* + * function used to ensure that the directories required have been created + */ +const checkForOutputDirectories: Function = function(directories: string[]): void +{ + for (const dir of directories) { + if (!fs.existsSync(`${dir}`)) { + fs.mkdirSync(`${dir}`); + } + } +}; + +/* + * Write given JSON object to given filepath + */ +const writeJSONtoFile: Function = function(filePath:string, object:Object): void +{ + fs.writeFile(filePath, + JSON.stringify(object, null, 2), + (err) => + { + if (err) { + console.error(err) + throw err; + } + } + ); +} + +/* + * used to write the supported views object to file both in total and "cleaned" + */ +const createSupportedViewsObject: Function = function(): void +{ + + //parse the xml + parseExtractedXML(`${extractionDirectory}FILE-META-1.xml`); + + //create the total supported Views object + writeJSONtoFile(`${outputImageData}supported_views.json`, supportedViews); + + //cleanup and create "smart" supported views object without whole metadata + cleanSupportedViews(supportedViews); + supportedViews.scalable_image.metadata = {}; + writeJSONtoFile(`${outputImageData}supported_views_minus_xml.json`, supportedViews); +} + +/* + * Used to build up a pyramid for each value of c from the base images + */ +const buildCustomPyramids:Function = async function buildCustomPyramids(): Promise +{ + //set some variables for errors and and percent counts + let errorOccurred: Boolean; + finalCZIJson.zoom_level_count = Math.sqrt(maxZoom); + finalCZIJson.c_values = [] as any; + finalCZIJson.c_value_count = 0; + + //for all channels in the base image + for (const cval of supportedViews.scalable_image.channels) { + errorOccurred = false; + if (!errorOccurred) { + //extract the base tiles and build up custom pyramid data + await extrapolateDimension(Number.parseInt(cval.channel_id, 10), supportedViews.scalable_image.channels.length * Math.sqrt(maxZoom), maxZoom) + .then((v: CZIHeightMap[]) => + { + // on success, add the new heightmap to the final json data block + finalCZIJson.c_values.push({channel_id: cval.channel_id, height_map: v}); + finalCZIJson.c_value_count++; + return; + } + ).catch((err: Error) => + { + // on error, write the error to console and set an error true. + if (err) { + console.error(err); + } + errorOccurred = true; + } + ); + } + else { + console.error("\nAn error occurred while extracting dimension: " + cval); + console.error("Skipping futher elements and moving to next dimension.\n\n"); + } + //write the final json data to file with most recent changes + writeJSONtoFile(`${outputImageData}layout.json`, finalCZIJson); } - fs.writeFile(`${outputImageDirectory}layout.json`, JSON.stringify(finalCZIJson), (err) => console.error(err)); +} + + + + + + + + + + +let finalCZIJson: WholeCZIHierarchy = {} as any; +/* + * Main function used to call the rest of the relevant code to crunch a CZI extraction. + */ +function main(){ + console.log("\n"); + + console.log(">> Checking/Creating output directories...") + checkForOutputDirectories([outputImageData, outputImageDirectory]); + + console.log(">> Creating Supported Views and writing files...") + createSupportedViewsObject(); + + console.log(""); + buildCustomPyramids(); } main(); +// async function main2() { +// +// let layout: WholeCZIHierarchy = require(`${outputImageData}layout.json`); +// let retHeightMap: CZIHeightMap = require(`${outputImageData}stageMap-1`); +// filecoutner = 5365; +// +// for (let stage:number = 2; stage < Math.sqrt(maxZoom); stage++) { +// console.log(`Stage (${0 * Math.sqrt(maxZoom) + 1 + stage}/${1}):`); +// await zoomTier(retHeightMap) +// .then((v: CZIHeightMap) => +// { +// writeJSONtoFile(`${outputImageData}stageMap-${stage}`, v); +// return; +// } +// ); +// } +// } +// +// main2().then(); -- cgit v1.2.1 From 54937bdf9c237caf8261a1312771874863eb931e Mon Sep 17 00:00:00 2001 From: cjd24 Date: Tue, 27 Mar 2018 22:12:58 +0100 Subject: Most up to Date version --This is the commit which produced working pyramid from 4.2Gb czi 0701 --- src/conversion/czi/czi.ts | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index aa1cfcc..9d955fa 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -602,7 +602,7 @@ const zoomTier: Function = async function(previousHeightMap:CZIHeightMap): Promi console.log( ` Task(1/1): ` + `Stage 100% complete. ` + - `(0 sec/iter) Stage was skipped as maximum sensible zoom level was reached. <<` + `(0 sec/iter) Stage was skipped as maximum sensible zoom level was reached.` ); return previousHeightMap; } @@ -671,11 +671,12 @@ const zoomTier: Function = async function(previousHeightMap:CZIHeightMap): Promi newZoomTier.plane.push(cziRow); timing = process.hrtime(timing); iterTimes.push(timing[0]); + if (iterTimes.length > 5) iterTimes.shift(); avgItrTime = iterTimes.reduce((p, c, i) => {return p+(c-p)/(i+1)}, 0); console.log( - ` Task(${ys/2}/${Math.floor(previousHeightMap.plane.length/2)}): ` + + ` Task(${ys/2 + 1}/${Math.floor(previousHeightMap.plane.length/2) + 1}): ` + `Stage ${Math.ceil(((ys/previousHeightMap.plane.length)*100) *100)/100}% complete. ` + - `(${timing[0]} sec/iter, est: ${((avgItrTime * (Math.floor(previousHeightMap.plane.length/2) - (ys/2 + 1)))/60).toFixed(2)} mins remain.)` + `(${timing[0]} sec/iter, est: ${((avgItrTime * ((Math.floor(previousHeightMap.plane.length/2) + 1) - (ys/2 + 1)))/60).toFixed(2)} mins remain.)` ); } newZoomTier.tile_height_count = newZoomTier.plane.length; @@ -690,7 +691,8 @@ const zoomTier: Function = async function(previousHeightMap:CZIHeightMap): Promi */ const extrapolateDimension:Function = async function(cVal: number, totalCs: number, maxZoom:number): Promise { - let ys:number = 0, timing = process.hrtime(), iterTimes: number[] = [100], avgItrTime: number;; + let ys:number = 0, timing = process.hrtime(), iterTimes: number[] = [100], avgItrTime: number; + filterC(cVal); //begin output for the base tier console.log('========================================================='); console.log(`>> Beginning Dimension Extrapolation for \'C\' : ${cVal}`); @@ -711,7 +713,6 @@ const extrapolateDimension:Function = async function(cVal: number, totalCs: numb ys - tileOverlap, ys + tileSize + tileOverlap ); - filterC(cVal); cziRow.push({ x_offset: xs, @@ -729,6 +730,7 @@ const extrapolateDimension:Function = async function(cVal: number, totalCs: numb ys += tileSize; timing = process.hrtime(timing); iterTimes.push(timing[0]); + if (iterTimes.length > 5) iterTimes.shift(); avgItrTime = iterTimes.reduce((p, c, i) => {return p+(c-p)/(i+1)}, 0); console.log( ` Task(${ys/tileSize}/${Math.ceil(totalSizeY/tileSize)}): ` + @@ -753,7 +755,7 @@ const extrapolateDimension:Function = async function(cVal: number, totalCs: numb return; } ); - writeJSONtoFile(`${outputImageData}stageMap-${stage}`, retHeightMap); + writeJSONtoFile(`${outputImageData}stageMap-${cVal}-${stage}`, retHeightMap); } console.log(`>> Completed Extrapolation for dimension, \'C\': ${cVal}\n\n`); @@ -817,6 +819,7 @@ const buildCustomPyramids:Function = async function buildCustomPyramids(): Promi finalCZIJson.zoom_level_count = Math.sqrt(maxZoom); finalCZIJson.c_values = [] as any; finalCZIJson.c_value_count = 0; + finalCZIJson.total_files = 0; //for all channels in the base image for (const cval of supportedViews.scalable_image.channels) { @@ -879,15 +882,16 @@ main(); // async function main2() { // // let layout: WholeCZIHierarchy = require(`${outputImageData}layout.json`); -// let retHeightMap: CZIHeightMap = require(`${outputImageData}stageMap-1`); -// filecoutner = 5365; +// let retHeightMap: any[] = [{}, {}, require(`${outputImageData}stageMap-2.json`)]; +// filecoutner = 5530; // -// for (let stage:number = 2; stage < Math.sqrt(maxZoom); stage++) { +// for (let stage:number = 3; stage < Math.sqrt(maxZoom); stage++) { // console.log(`Stage (${0 * Math.sqrt(maxZoom) + 1 + stage}/${1}):`); -// await zoomTier(retHeightMap) +// await zoomTier(retHeightMap[stage -1]) // .then((v: CZIHeightMap) => // { -// writeJSONtoFile(`${outputImageData}stageMap-${stage}`, v); +// retHeightMap.push(v); +// writeJSONtoFile(`${outputImageData}stageMap-${stage}.json`, v); // return; // } // ); -- cgit v1.2.1 From 4e63ccd63abe62230c254455b38e3f195b55d3b0 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Wed, 28 Mar 2018 02:34:45 +0100 Subject: V small commit to add some consolidation to filenames/paths --- src/conversion/czi/czi.ts | 7 ++++--- src/conversion/czi/cziConvert.sh | 5 +++-- 2 files changed, 7 insertions(+), 5 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index 9d955fa..d69d990 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -6,9 +6,10 @@ import { SharpInstance } from 'sharp'; import * as parsexml from 'xml-parser'; //various constants for placing files and defining tiles -const extractionDirectory: string = '/cs/scratch/cjd24/0701-extraction/'; -const outputImageData: string = '/cs/scratch/cjd24/0701-extraction-processed/' -const outputImageDirectory: string = '/cs/scratch/cjd24/0701-extraction-processed/data/' +const dirname: string = '/cs/scratch/cjd24/0701-extraction'; +const extractionDirectory: string = `${dirname}/`; +const outputImageData: string = `${dirname}-processed/`; +const outputImageDirectory: string = `${dirname}-processed/data/`; const tileOverlap: number = 0; const tileSize: number = 1024; const maxZoom: number = 64; diff --git a/src/conversion/czi/cziConvert.sh b/src/conversion/czi/cziConvert.sh index 639251c..2529d44 100755 --- a/src/conversion/czi/cziConvert.sh +++ b/src/conversion/czi/cziConvert.sh @@ -1,8 +1,9 @@ #!/bin/sh +FILENAME='2016_12_17__0701' CZI_WORKING_DIR=${1:-"/cs/scratch"} -CZI_EXTRACTION_DIR=${2:-"0701-extraction"} -CZI_FILE=${3:-"2016_12_17__0701.czi"} +CZI_EXTRACTION_DIR=${2:-${FILENAME}} +CZI_FILE=${3:-${FILENAME}".czi"} gcc -Wall -Wextra --pedantic -std=c99 cziconvert.c mkdir -p ${CZI_WORKING_DIR}/${USER}/${CZI_EXTRACTION_DIR} -- cgit v1.2.1 From 94acccd371a233cda1743d0d387247f0b9b55986 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Thu, 29 Mar 2018 03:50:47 +0100 Subject: Please dont use this commit lol --- src/conversion/czi/czi.ts | 177 +++-------------------------- src/conversion/czi/pyramidWorker.ts | 161 ++++++++++++++++++++++++++ src/conversion/czi/tileExtraction.ts | 124 ++++++++++++++++++++ src/conversion/types/customPyramidIndex.ts | 27 +++++ src/conversion/types/cziBinaryTypings.ts | 23 ++++ src/conversion/types/helperCZITypes.ts | 39 +++++++ 6 files changed, 390 insertions(+), 161 deletions(-) create mode 100644 src/conversion/czi/pyramidWorker.ts create mode 100644 src/conversion/czi/tileExtraction.ts create mode 100644 src/conversion/types/customPyramidIndex.ts create mode 100644 src/conversion/types/cziBinaryTypings.ts create mode 100644 src/conversion/types/helperCZITypes.ts (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index d69d990..b27cfec 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -1,103 +1,23 @@ //imports required to make the conversion import * as fs from 'fs'; +import * as parsexml from 'xml-parser'; import { logger } from '../../logger'; import * as sharp from 'sharp'; import { SharpInstance } from 'sharp'; -import * as parsexml from 'xml-parser'; +import { CZITile, CZIHeightMap, WholeCZIHierarchy } from '../types/customPyramidIndex'; +import { Dimension, DirectoryEntry, SubBlock, Segment } from '../types/cziBinaryTypings'; +import { SupportedViews, TileBounds } from '../types/helperCZITypes'; +import { isTileRelated, regionToExtract } from './tileExtraction'; //various constants for placing files and defining tiles -const dirname: string = '/cs/scratch/cjd24/0701-extraction'; -const extractionDirectory: string = `${dirname}/`; -const outputImageData: string = `${dirname}-processed/`; -const outputImageDirectory: string = `${dirname}-processed/data/`; -const tileOverlap: number = 0; +const baseDirname: string = '/cs/scratch/cjd24/0701-extraction'; +const extractionDirectory: string = `${baseDirname}/`; +const outputImageData: string = `${baseDirname}-processed/`; +const outputImageDirectory: string = `${baseDirname}-processed/data/`; +const tileOverlap: number = 0; // Overlap is only half implemented const tileSize: number = 1024; const maxZoom: number = 64; -//Interfaces used to define the tiles incoming from the CZI extraction -interface Dimension { - Dimension: string; - Start: number; - Size: number; -} -interface DirectoryEntry { - DimensionCount: number; - DimensionEntries: Dimension[]; -} -interface SubBlock { - DirectoryEntry: DirectoryEntry; - Data: string; -} -interface Segment { - Id: string; - UsedSize: number; - Data: SubBlock; -} - -//Interface used to define the pixel-bounds of a 'section' within the image -class TileBounds { - public left!: number; - public right!: number; - public top!: number; - public bottom!: number; - public constructor(leftBound: number, rightBound: number, topBound: number, bottomBound: number) { - this.left = leftBound; - this.right = rightBound; - this.top = topBound; - this.bottom = bottomBound; - } -} - -//Interface used to define the structure of the "supportedViews" section -//of the protocol specification for scalable images -interface SupportedViews { - scalable_image: { - width: number; - height: number; - channels: [ - { - channel_id: string; - channel_name: string; - metadata?: parsexml.Node[]; - } - ]; - real_width?: { - value?: number; - units?: string; - }; - real_height?: { - value?: number; - units?: string; - }; - metadata?: {}; - } -} - -//The following are interfaces for the Custom object storing Information -//about the CUSTOM pyramid being created for this image -interface CZITile { - x_offset: number; - y_offset: number; - width: number; - height: number; - file: string; -} -interface CZIHeightMap { - zoom_level: number, - tile_width_count?: number, - tile_height_count?: number, - plane: CZITile[][]; -} -interface WholeCZIHierarchy { - c_values: [{ - channel_id: string, - height_map: CZIHeightMap[]; - }], - c_value_count: number, - zoom_level_count: number; - total_files: number; -} - /* * Simple function to find the tile bounds version of an original tile in the base image */ @@ -146,34 +66,8 @@ const findRelatedTiles: Function = function(activeSegments: Segment[], desired: throw new Error('There was a Sad Boi error'); } - // Desired X on left is within current tile - if (((desired.left >= origCoords.left) && - (desired.left < origCoords.right)) || - - // Desired X on right is within the current tile - ((desired.right > origCoords.left) && - (desired.right <= origCoords.right)) || - - // Desired tile X overlaps base tile - ((desired.left < origCoords.left) && - (desired.right > origCoords.right))) { - - // Desired Y on top is within current tile - if (((desired.top >= origCoords.top) && - (desired.top < origCoords.bottom)) || - - // Desired Y on right is within the current tile - ((desired.bottom > origCoords.top) && - (desired.bottom <= origCoords.bottom)) || - - // Desired tile Y overlaps whole base tile - ((desired.top < origCoords.top) && - (desired.bottom > origCoords.bottom))) { - - //If all of the if statements have passed, then this tile - //is part of the overlap for the new tile to be created. - relatedTiles.push(baseTile); - } + if (isTileRelated(origCoords, desired)) { + relatedTiles.push(baseTile); } } @@ -269,40 +163,8 @@ const orderSegments: Function = function(segments: Segment[]): Segment[][] { */ const findRegionToExtract: Function = function(segment: Segment, desired: TileBounds): TileBounds { - //get the base tile area and create an object for the chunk to extract - const baseBounds: TileBounds = getOriginalTileBounds(segment); - let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); - - // check if the new tile overlaps the leftmost boundary - if (desired.left <= baseBounds.left) { - chunkToExtract.left = 0; - } else { - chunkToExtract.left = desired.left - baseBounds.left; - } - - // check if the new tile overlaps the rightmost boundary - if (desired.right >= baseBounds.right) { - chunkToExtract.right = baseBounds.right - baseBounds.left; - } else { - chunkToExtract.right = desired.right - baseBounds.left; - } - - // check if the new tile overlaps the top boundary - if (desired.top <= baseBounds.top) { - chunkToExtract.top = 0; - } else { - chunkToExtract.top = desired.top - baseBounds.top; - } - - // check if the new tile overlaps the bottom boundary - if (desired.bottom >= baseBounds.bottom) { - chunkToExtract.bottom = baseBounds.bottom - baseBounds.top; - } else { - chunkToExtract.bottom = desired.bottom - baseBounds.top; - } - //return the slice within the base tile for extraction - return chunkToExtract; + return regionToExtract(getOriginalTileBounds(segment) , desired); }; /* @@ -797,7 +659,6 @@ const writeJSONtoFile: Function = function(filePath:string, object:Object): void */ const createSupportedViewsObject: Function = function(): void { - //parse the xml parseExtractedXML(`${extractionDirectory}FILE-META-1.xml`); @@ -821,6 +682,7 @@ const buildCustomPyramids:Function = async function buildCustomPyramids(): Promi finalCZIJson.c_values = [] as any; finalCZIJson.c_value_count = 0; finalCZIJson.total_files = 0; + finalCZIJson.complete = false; //for all channels in the base image for (const cval of supportedViews.scalable_image.channels) { @@ -852,22 +714,15 @@ const buildCustomPyramids:Function = async function buildCustomPyramids(): Promi //write the final json data to file with most recent changes writeJSONtoFile(`${outputImageData}layout.json`, finalCZIJson); } + finalCZIJson.complete = true; } - - - - - - - - let finalCZIJson: WholeCZIHierarchy = {} as any; /* * Main function used to call the rest of the relevant code to crunch a CZI extraction. */ -function main(){ +const main: Function = function() { console.log("\n"); console.log(">> Checking/Creating output directories...") diff --git a/src/conversion/czi/pyramidWorker.ts b/src/conversion/czi/pyramidWorker.ts new file mode 100644 index 0000000..bdbcbfa --- /dev/null +++ b/src/conversion/czi/pyramidWorker.ts @@ -0,0 +1,161 @@ +import { CZITile, CZIHeightMap, WholeCZIHierarchy } from '../types/customPyramidIndex'; +import { TileBounds } from '../types/helperCZITypes'; +import * as sharp from 'sharp'; +import { SharpInstance } from 'sharp'; +import * as fs from 'fs'; +import { isTileRelated, regionToExtract } from './tileExtraction'; + +const processedDirname: string = '/cs/scratch/cjd24/0701-extraction-processed/'; +const processedImages: string = `${processedDirname}data/`; +const layout: WholeCZIHierarchy = require(`${processedDirname}layout.json`); +const TEMP_OUTPUT_THING: string = `${processedDirname}finalisedTiles/`; +const TEMP_REQUESTED_BOUNDS: TileBounds[] = +[ + new TileBounds(0, 5000, 2000, 7000), + new TileBounds(1000, 6000, 3000, 8000) +] +const TEMP_C_VALUE: number = 0, ZOOM_LEVEL: number = 2, TILE_SIZE: number = 1024, TILE_OVERLAP: number = 0; + + +const findRelatedTiles:Function = function(plane: CZIHeightMap, desired: TileBounds): CZITile[][] { + + let relatedTiles: CZITile[][] = []; + for (const planeTileRow of plane.plane) { + let tileRow: CZITile[] = [], foundTiles: boolean = false; + for (const tile of planeTileRow) { + + if (isTileRelated(new TileBounds(tile.x_offset, tile.x_offset + tile.width, tile.y_offset, tile.y_offset + tile.height), desired)) { + tileRow.push(tile); + foundTiles = true; + } + } + if (foundTiles) { + relatedTiles.push(tileRow); + } + } + return relatedTiles; +} + +const extractAndStitch: Function = async function(segments: CZITile[][], desiredRegion: TileBounds): Promise { + + // //create a buffer for the rows part of raw image data + // let tileVerticalBuffer: Buffer[] = []; + // + // //for all ros (y coords) in the image + // for (const segRow of segments) { + // //create a buffer for this row + // let tileRow: Buffer[] = []; + // let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); + // + // //For all of the columns within this row + // for (const segCol of segRow) { + // //find out the region of the base tile to be added to the new image + // chunkToExtract = findRegionToExtract(segCol, desiredRegion); + // //extract this section of image data into a sharp buffer + // let data: Promise = + // sharp(`${extractionDirectory}${segCol.Data.Data}`) + // .extract({ + // left: chunkToExtract.left, + // top: chunkToExtract.top, + // width: chunkToExtract.right - chunkToExtract.left, + // height: chunkToExtract.bottom - chunkToExtract.top + // }) + // .toBuffer(); + // + // //push this data into the row buffer + // tileRow.push(await data); + // } + // + // //prepare variables to squash all of the column data into one, for this row + // let imageVerticalSlice: SharpInstance = sharp(tileRow[0]); + // let bufferBound = findRegionToExtract(segRow[0], desiredRegion); + // //check if the inital chunk needs to be extended to support the other columns + // if ((bufferBound.right - bufferBound.left) < (tileSize - tileOverlap)) { + // imageVerticalSlice = await imageVerticalSlice.background({r: 0, g: 0, b: 0, alpha: 0}).extend( + // {top:0, left:0, bottom:0, right: (tileSize - (bufferBound.right - bufferBound.left))}); + // } + // //for every column along this row, join it to the previous column data + // for (let index = 1; index < segRow.length; index++) { + // imageVerticalSlice = await imageVerticalSlice + // .overlayWith(tileRow[index], + // {top: 0, left: (bufferBound.right - bufferBound.left) + ((index -1) * tileSize)}); + // } + // + // //add this horizontal data buffer to the vertical buffer + // tileVerticalBuffer.push(await imageVerticalSlice.toBuffer()); + // } + // + // //prepare variables used to combine all rows into one image + // let finalImage: SharpInstance = sharp(tileVerticalBuffer[0]); + // let bufferBound = findRegionToExtract(segments[0][0], desiredRegion); + // //Check if the inital row needs to be extended to support further rows + // if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) { + // finalImage = await finalImage.background({r: 0, g: 0, b: 0, alpha: 0}).extend( + // {top:0, left:0, bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), right: 0}); + // } + // //For all further rows in the image, combine it with the previous rows' data + // for (let index = 1; index < segments.length; index++) { + // finalImage = finalImage.overlayWith( + // tileVerticalBuffer[index], + // {top: getDimension(segments[index -1][0], 'Y').Size, left: 0}); + // } + // +// // return the finalised image. + // return finalImage; + return; +}; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +const main: Function = function() { + if (!layout.complete) { + console.error(`The files under: ${processedDirname} have not been finalised yet, please try again later`); + return; + } + + if (!fs.existsSync(`${TEMP_OUTPUT_THING}`)) { + fs.mkdirSync(`${TEMP_OUTPUT_THING}`); + } + + let requestCount: number = 0; + for (const bound of TEMP_REQUESTED_BOUNDS) { + extractAndStitch( + findRelatedTiles(layout.c_values[TEMP_C_VALUE].height_map[ZOOM_LEVEL], bound), bound + ).then((x: SharpInstance) => x.toFile(`${TEMP_OUTPUT_THING}request-${requestCount++}`)); + } +} +main(); diff --git a/src/conversion/czi/tileExtraction.ts b/src/conversion/czi/tileExtraction.ts new file mode 100644 index 0000000..9c87dd9 --- /dev/null +++ b/src/conversion/czi/tileExtraction.ts @@ -0,0 +1,124 @@ +import { CZITile } from '../types/customPyramidIndex'; +import { TileBounds } from '../types/helperCZITypes'; +import { SharpInstance } from 'sharp'; +import * as sharp from 'sharp'; + +export const isTileRelated:Function = function(origCoords: TileBounds, desired: TileBounds): boolean { + + if (((desired.left >= origCoords.left) && + (desired.left < origCoords.right)) || + + // Desired X on right is within the current tile + ((desired.right > origCoords.left) && + (desired.right <= origCoords.right)) || + + // Desired tile X overlaps base tile + ((desired.left < origCoords.left) && + (desired.right > origCoords.right))) + { + + // Desired Y on top is within current tile + if (((desired.top >= origCoords.top) && + (desired.top < origCoords.bottom)) || + + // Desired Y on right is within the current tile + ((desired.bottom > origCoords.top) && + (desired.bottom <= origCoords.bottom)) || + + // Desired tile Y overlaps whole base tile + ((desired.top < origCoords.top) && + (desired.bottom > origCoords.bottom))) + { + + //If all of the if statements have passed, then this tile + //is part of the overlap for the new tile to be created. + return true; + } + } + return false; +} + + +/* + * Takes a base tile, and the whole bounds of a new tile, and uses this + * to calculate the region within the base tile that is overlapping the new tile + * to be extracted. + */ +export const regionToExtract: Function = function(baseBounds: TileBounds, desired: TileBounds): TileBounds { + + //get the base tile area and create an object for the chunk to extract + let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); + + // check if the new tile overlaps the leftmost boundary + if (desired.left <= baseBounds.left) { + chunkToExtract.left = 0; + } else { + chunkToExtract.left = desired.left - baseBounds.left; + } + + // check if the new tile overlaps the rightmost boundary + if (desired.right >= baseBounds.right) { + chunkToExtract.right = baseBounds.right - baseBounds.left; + } else { + chunkToExtract.right = desired.right - baseBounds.left; + } + + // check if the new tile overlaps the top boundary + if (desired.top <= baseBounds.top) { + chunkToExtract.top = 0; + } else { + chunkToExtract.top = desired.top - baseBounds.top; + } + + // check if the new tile overlaps the bottom boundary + if (desired.bottom >= baseBounds.bottom) { + chunkToExtract.bottom = baseBounds.bottom - baseBounds.top; + } else { + chunkToExtract.bottom = desired.bottom - baseBounds.top; + } + + if (chunkToExtract.left < 0 || chunkToExtract.right < 0 || chunkToExtract.top < 0 || chunkToExtract.bottom < 0) { + throw new Error("Chunk to extract from base tile has invalid bound (< 0)."); + } + + //return the slice within the base tile for extraction + return chunkToExtract; +}; + + +// export const createHorizontalImageSlice: Function = async function (bufferBound: TileBounds, tileSize: number, tileOverlap: number, rowLength:number, row: Buffer[]): Promise { +// //prepare variables to squash all of the column data into one, for this row +// let imageVerticalSlice: SharpInstance = sharp(row[0]); +// //check if the inital chunk needs to be extended to support the other columns +// if ((bufferBound.right - bufferBound.left) < (tileSize - tileOverlap)) { +// imageVerticalSlice = await imageVerticalSlice.background({r: 0, g: 0, b: 0, alpha: 0}).extend( +// {top:0, left:0, bottom:0, right: (tileSize - (bufferBound.right - bufferBound.left))}); +// } +// //for every column along this row, join it to the previous column data +// for (let index = 1; index < rowLength; index++) { +// imageVerticalSlice = await imageVerticalSlice +// .overlayWith(row[index], +// {top: 0, left: (bufferBound.right - bufferBound.left) + ((index -1) * tileSize)}); +// } +// return imageVerticalSlice.toBuffer(); +// } +// +// +// export const createImageFromHorizontalSlices: Function = async function(bufferBound: TileBounds, horizontalSlices: Buffer[], tileSize: number, tileOverlap: number, rowCount: number, tiles: CZITile[][]): Promise { +// //prepare variables used to combine all rows into one image +// let finalImage: SharpInstance = sharp(horizontalSlices[0]); +// +// //Check if the inital row needs to be extended to support further rows +// if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) { +// finalImage = await finalImage.background({r: 0, g: 0, b: 0, alpha: 0}).extend( +// {top:0, left:0, bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), right: 0}); +// } +// //For all further rows in the image, combine it with the previous rows' data +// for (let index = 1; index < rowCount; index++) { +// finalImage = finalImage.overlayWith( +// horizontalSlices[index], +// {top: tiles[index - 1][0].height, left: 0}); +// } +// +// return finalImage; +// } diff --git a/src/conversion/types/customPyramidIndex.ts b/src/conversion/types/customPyramidIndex.ts new file mode 100644 index 0000000..f362372 --- /dev/null +++ b/src/conversion/types/customPyramidIndex.ts @@ -0,0 +1,27 @@ +//The following are interfaces for the Custom object storing Information +//about the CUSTOM pyramid being created for this image + export interface CZITile { + x_offset: number; + y_offset: number; + width: number; + height: number; + file: string; + } + + export interface CZIHeightMap { + zoom_level: number, + tile_width_count?: number, + tile_height_count?: number, + plane: CZITile[][]; + } + + export interface WholeCZIHierarchy { + c_values: [{ + channel_id: string, + height_map: CZIHeightMap[]; + }], + c_value_count: number, + zoom_level_count: number; + total_files: number; + complete: boolean; + } diff --git a/src/conversion/types/cziBinaryTypings.ts b/src/conversion/types/cziBinaryTypings.ts new file mode 100644 index 0000000..a78b4e9 --- /dev/null +++ b/src/conversion/types/cziBinaryTypings.ts @@ -0,0 +1,23 @@ +//Interfaces used to define the tiles incoming from the CZI extraction + +export interface Dimension { + Dimension: string; + Start: number; + Size: number; +} + +export interface DirectoryEntry { + DimensionCount: number; + DimensionEntries: Dimension[]; +} + +export interface SubBlock { + DirectoryEntry: DirectoryEntry; + Data: string; +} + +export interface Segment { + Id: string; + UsedSize: number; + Data: SubBlock; +} diff --git a/src/conversion/types/helperCZITypes.ts b/src/conversion/types/helperCZITypes.ts new file mode 100644 index 0000000..2d57b15 --- /dev/null +++ b/src/conversion/types/helperCZITypes.ts @@ -0,0 +1,39 @@ +//Interface used to define the structure of the "supportedViews" section +//of the protocol specification for scalable images +import { Node } from 'xml-parser'; +export interface SupportedViews { + scalable_image: { + width: number; + height: number; + channels: [ + { + channel_id: string; + channel_name: string; + metadata?: Node[]; + } + ]; + real_width?: { + value?: number; + units?: string; + }; + real_height?: { + value?: number; + units?: string; + }; + metadata?: {}; + } +} + +//Interface used to define the pixel-bounds of a 'section' within the image +export class TileBounds { + public left: number; + public right: number; + public top: number; + public bottom: number; + public constructor(leftBound: number, rightBound: number, topBound: number, bottomBound: number) { + this.left = leftBound; + this.right = rightBound; + this.top = topBound; + this.bottom = bottomBound; + } +} -- cgit v1.2.1 From feea9d9360409e6bd3cd0d874c7773523e47a7a4 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Thu, 29 Mar 2018 09:33:23 +0100 Subject: v basic and slow working version of final tile builder - Be Wary, this commit might break the old czi.ts builder --- src/conversion/czi/czi.ts | 12 +-- src/conversion/czi/pyramidWorker.ts | 160 +++++++++++++++++++---------------- src/conversion/czi/tileExtraction.ts | 7 +- 3 files changed, 101 insertions(+), 78 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index b27cfec..ea22c0a 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -164,7 +164,7 @@ const orderSegments: Function = function(segments: Segment[]): Segment[][] { const findRegionToExtract: Function = function(segment: Segment, desired: TileBounds): TileBounds { //return the slice within the base tile for extraction - return regionToExtract(getOriginalTileBounds(segment) , desired); + return regionToExtract(getOriginalTileBounds(segment), desired, 1); }; /* @@ -564,7 +564,7 @@ const extrapolateDimension:Function = async function(cVal: number, totalCs: numb let baseCZIHeightMap: CZIHeightMap = {zoom_level: 1, plane: []}, width_in_tiles = 0, height_in_tiles = 0; - console.log(`Stage (${cVal * Math.sqrt(maxZoom) + 1}/${totalCs}):`); + console.log(`Stage (${cVal * Math.log2(maxZoom) + 1}/${totalCs}):`); //For all rows within the total base pixel height for (;ys < totalSizeY;) { timing = process.hrtime(); @@ -609,8 +609,8 @@ const extrapolateDimension:Function = async function(cVal: number, totalCs: numb console.log(">> Base tier complete for \'C\': " + cVal + "; Begin computing zoom tiers...\n") let retHeightMap: CZIHeightMap[] = [baseCZIHeightMap]; - for (let stage:number = 1; stage < Math.sqrt(maxZoom); stage++) { - console.log(`Stage (${cVal * Math.sqrt(maxZoom) + 1 + stage}/${totalCs}):`); + for (let stage:number = 1; stage < Math.log2(maxZoom); stage++) { + console.log(`Stage (${cVal * Math.log2(maxZoom) + 1 + stage}/${totalCs}):`); await zoomTier(retHeightMap[stage - 1]) .then((v: CZIHeightMap) => { @@ -678,7 +678,7 @@ const buildCustomPyramids:Function = async function buildCustomPyramids(): Promi { //set some variables for errors and and percent counts let errorOccurred: Boolean; - finalCZIJson.zoom_level_count = Math.sqrt(maxZoom); + finalCZIJson.zoom_level_count = Math.log2(maxZoom); finalCZIJson.c_values = [] as any; finalCZIJson.c_value_count = 0; finalCZIJson.total_files = 0; @@ -689,7 +689,7 @@ const buildCustomPyramids:Function = async function buildCustomPyramids(): Promi errorOccurred = false; if (!errorOccurred) { //extract the base tiles and build up custom pyramid data - await extrapolateDimension(Number.parseInt(cval.channel_id, 10), supportedViews.scalable_image.channels.length * Math.sqrt(maxZoom), maxZoom) + await extrapolateDimension(Number.parseInt(cval.channel_id, 10), supportedViews.scalable_image.channels.length * Math.log2(maxZoom), maxZoom) .then((v: CZIHeightMap[]) => { // on success, add the new heightmap to the final json data block diff --git a/src/conversion/czi/pyramidWorker.ts b/src/conversion/czi/pyramidWorker.ts index bdbcbfa..286fd6b 100644 --- a/src/conversion/czi/pyramidWorker.ts +++ b/src/conversion/czi/pyramidWorker.ts @@ -11,10 +11,10 @@ const layout: WholeCZIHierarchy = require(`${processedDirname}layout.json`); const TEMP_OUTPUT_THING: string = `${processedDirname}finalisedTiles/`; const TEMP_REQUESTED_BOUNDS: TileBounds[] = [ - new TileBounds(0, 5000, 2000, 7000), - new TileBounds(1000, 6000, 3000, 8000) + new TileBounds(16386, 38000, 15000, 40000), + new TileBounds(6000, 15000, 9000, 18000) ] -const TEMP_C_VALUE: number = 0, ZOOM_LEVEL: number = 2, TILE_SIZE: number = 1024, TILE_OVERLAP: number = 0; +const TEMP_C_VALUE: number = 1, ZOOM_LEVEL: number = 8, TILE_SIZE: number = 1024, TILE_OVERLAP: number = 0; const findRelatedTiles:Function = function(plane: CZIHeightMap, desired: TileBounds): CZITile[][] { @@ -35,74 +35,92 @@ const findRelatedTiles:Function = function(plane: CZIHeightMap, desired: TileBou } return relatedTiles; } +let help: number = 0; +const extractAndStitch: Function = async function(tiles: CZITile[][], desiredRegion: TileBounds, zoom: number): Promise { + + //create a buffer for the rows part of raw image data + let tileHorizontalBuffer: Buffer[] = [], bufferBound: TileBounds, rowPixelWidth:number = 0, columnPixelHeight: number = 0; + + //for all rows (y coords) in the image + for (const row of tiles) { + //create a buffer for this row + let tileRow: Buffer[] = []; + let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); + rowPixelWidth = 0; + + //For all of the columns within this row + for (const tile of row) { + //find out the region of the base tile to be added to the new image + chunkToExtract = regionToExtract(new TileBounds(tile.x_offset, tile.x_offset + tile.width, tile.y_offset, tile.y_offset + tile.height), desiredRegion, zoom); + rowPixelWidth += (chunkToExtract.right - chunkToExtract.left); + + //extract this section of image data into a sharp buffer + let data: Promise = + sharp(`${processedImages}${tile.file}`) + .extract({ + left: chunkToExtract.left, + top: chunkToExtract.top, + width: chunkToExtract.right - chunkToExtract.left, + height: chunkToExtract.bottom - chunkToExtract.top + }) + .toBuffer(); + + //push this data into the row buffer + tileRow.push(await data); + } + + //prepare variables to squash all of the column data into one, for this row + let imageVerticalSlice: SharpInstance = sharp(tileRow[0]); + bufferBound = regionToExtract(new TileBounds( + row[0].x_offset, + row[0].x_offset + row[0].width, + row[0].y_offset, + row[0].y_offset + row[0].height, + ), desiredRegion, zoom); + //check if the inital chunk needs to be extended to support the other columns + if (row.length > 1) { + imageVerticalSlice = await imageVerticalSlice.background({r: 0, g: 0, b: 0, alpha: 0}).extend( + {top:0, left:0, bottom:0, right: rowPixelWidth - (bufferBound.right - bufferBound.left)}); + } + for (let index = 1; index < row.length; index++) { + imageVerticalSlice = sharp(await imageVerticalSlice + .overlayWith(tileRow[index], + {top: 0, left: ((bufferBound.right - bufferBound.left) + ((index -1) * TILE_SIZE))}).toBuffer()); + } + + //add this horizontal data buffer to the vertical buffer + tileHorizontalBuffer.push(await imageVerticalSlice.toBuffer()); + columnPixelHeight += bufferBound.bottom - bufferBound.top; + } + + // prepare variables used to combine all rows into one image + let finalImage: SharpInstance = sharp(tileHorizontalBuffer[0]); + bufferBound = regionToExtract(new TileBounds( + tiles[0][0].x_offset, + tiles[0][0].x_offset + tiles[0][0].width, + tiles[0][0].y_offset, + tiles[0][0].y_offset + tiles[0][0].height + ), desiredRegion, zoom); + //Check if the inital row needs to be extended to support further rows + if (tiles.length > 1) { + finalImage = await finalImage.background({r: 0, g: 0, b: 0, alpha: 0}).extend( + {top:0, left:0, bottom: (columnPixelHeight - (bufferBound.bottom - bufferBound.top)), right: 0}); + } + //For all further rows in the image, combine it with the previous rows' data + for (let index = 1; index < tiles.length; index++) { + finalImage = sharp(await finalImage.overlayWith( + tileHorizontalBuffer[index], + {top: ((bufferBound.bottom - bufferBound.top) + ((index -1) * TILE_SIZE)), left: 0}).toBuffer()); + } -const extractAndStitch: Function = async function(segments: CZITile[][], desiredRegion: TileBounds): Promise { - - // //create a buffer for the rows part of raw image data - // let tileVerticalBuffer: Buffer[] = []; - // - // //for all ros (y coords) in the image - // for (const segRow of segments) { - // //create a buffer for this row - // let tileRow: Buffer[] = []; - // let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); - // - // //For all of the columns within this row - // for (const segCol of segRow) { - // //find out the region of the base tile to be added to the new image - // chunkToExtract = findRegionToExtract(segCol, desiredRegion); - // //extract this section of image data into a sharp buffer - // let data: Promise = - // sharp(`${extractionDirectory}${segCol.Data.Data}`) - // .extract({ - // left: chunkToExtract.left, - // top: chunkToExtract.top, - // width: chunkToExtract.right - chunkToExtract.left, - // height: chunkToExtract.bottom - chunkToExtract.top - // }) - // .toBuffer(); - // - // //push this data into the row buffer - // tileRow.push(await data); - // } - // - // //prepare variables to squash all of the column data into one, for this row - // let imageVerticalSlice: SharpInstance = sharp(tileRow[0]); - // let bufferBound = findRegionToExtract(segRow[0], desiredRegion); - // //check if the inital chunk needs to be extended to support the other columns - // if ((bufferBound.right - bufferBound.left) < (tileSize - tileOverlap)) { - // imageVerticalSlice = await imageVerticalSlice.background({r: 0, g: 0, b: 0, alpha: 0}).extend( - // {top:0, left:0, bottom:0, right: (tileSize - (bufferBound.right - bufferBound.left))}); - // } - // //for every column along this row, join it to the previous column data - // for (let index = 1; index < segRow.length; index++) { - // imageVerticalSlice = await imageVerticalSlice - // .overlayWith(tileRow[index], - // {top: 0, left: (bufferBound.right - bufferBound.left) + ((index -1) * tileSize)}); - // } - // - // //add this horizontal data buffer to the vertical buffer - // tileVerticalBuffer.push(await imageVerticalSlice.toBuffer()); - // } - // - // //prepare variables used to combine all rows into one image - // let finalImage: SharpInstance = sharp(tileVerticalBuffer[0]); - // let bufferBound = findRegionToExtract(segments[0][0], desiredRegion); - // //Check if the inital row needs to be extended to support further rows - // if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) { - // finalImage = await finalImage.background({r: 0, g: 0, b: 0, alpha: 0}).extend( - // {top:0, left:0, bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), right: 0}); - // } - // //For all further rows in the image, combine it with the previous rows' data - // for (let index = 1; index < segments.length; index++) { - // finalImage = finalImage.overlayWith( - // tileVerticalBuffer[index], - // {top: getDimension(segments[index -1][0], 'Y').Size, left: 0}); - // } - // -// // return the finalised image. - // return finalImage; - return; + // return the finalised image. + console.log(`Width: ${rowPixelWidth} Height: ${columnPixelHeight}`) + return await finalImage + // .resize( + // rowPixelWidth, + // columnPixelHeight + // ) + // .crop(sharp.gravity.northwest); }; @@ -154,7 +172,7 @@ const main: Function = function() { let requestCount: number = 0; for (const bound of TEMP_REQUESTED_BOUNDS) { extractAndStitch( - findRelatedTiles(layout.c_values[TEMP_C_VALUE].height_map[ZOOM_LEVEL], bound), bound + findRelatedTiles(layout.c_values[TEMP_C_VALUE].height_map[Math.log2(ZOOM_LEVEL)], bound), bound, ZOOM_LEVEL ).then((x: SharpInstance) => x.toFile(`${TEMP_OUTPUT_THING}request-${requestCount++}`)); } } diff --git a/src/conversion/czi/tileExtraction.ts b/src/conversion/czi/tileExtraction.ts index 9c87dd9..be8bd3c 100644 --- a/src/conversion/czi/tileExtraction.ts +++ b/src/conversion/czi/tileExtraction.ts @@ -44,7 +44,7 @@ export const isTileRelated:Function = function(origCoords: TileBounds, desired: * to calculate the region within the base tile that is overlapping the new tile * to be extracted. */ -export const regionToExtract: Function = function(baseBounds: TileBounds, desired: TileBounds): TileBounds { +export const regionToExtract: Function = function(baseBounds: TileBounds, desired: TileBounds, zoomLevel: number): TileBounds { //get the base tile area and create an object for the chunk to extract let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); @@ -81,6 +81,11 @@ export const regionToExtract: Function = function(baseBounds: TileBounds, desire throw new Error("Chunk to extract from base tile has invalid bound (< 0)."); } + chunkToExtract.left = Math.ceil(chunkToExtract.left / zoomLevel); + chunkToExtract.right = Math.ceil(chunkToExtract.right / zoomLevel); + chunkToExtract.top = Math.ceil(chunkToExtract.top / zoomLevel); + chunkToExtract.bottom = Math.ceil(chunkToExtract.bottom / zoomLevel); + //return the slice within the base tile for extraction return chunkToExtract; }; -- cgit v1.2.1 From c7a81df7c15ef102a4d803dd45f02fc732051c5b Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 29 Mar 2018 10:00:04 +0100 Subject: Progress on tidying-up CZI converter --- src/conversion/czi/czi.ts | 230 ++++++++++++++++++++++++++++------------------ 1 file changed, 141 insertions(+), 89 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index addf43e..ae9a13d 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -1,12 +1,13 @@ - import * as fs from 'fs'; -import { logger } from '../../logger'; import * as sharp from 'sharp'; -import * as parsexml from 'xml-parser'; +// tslint:disable-next-line:no-duplicate-imports import { SharpInstance } from 'sharp'; +import * as parsexml from 'xml-parser'; -const extractionDirectory: string = '/cs/scratch/cjd24/0701-extraction/'; -const outputImageDirectory: string = '/cs/scratch/cjd24/0701-extraction-processed2/' +const extractionDirectory: string = + '/cs/scratch/cjd24/0701-extraction/'; +const outputImageDirectory: string = + '/cs/scratch/cjd24/0701-extraction-processed2/'; const tileOverlap: number = 0; const tileSize: number = 1024; const maxZoom: number = 64; @@ -16,31 +17,41 @@ interface Dimension { Start: number; Size: number; } + interface DirectoryEntry { DimensionCount: number; DimensionEntries: Dimension[]; } + interface SubBlock { DirectoryEntry: DirectoryEntry; Data: string; } + interface Segment { Id: string; UsedSize: number; Data: SubBlock; } + class TileBounds { public left!: number; public right!: number; public top!: number; public bottom!: number; - public constructor(leftBound: number, rightBound: number, topBound: number, bottomBound: number) { + public constructor( + leftBound: number, + rightBound: number, + topBound: number, + bottomBound: number + ) { this.left = leftBound; this.right = rightBound; this.top = topBound; this.bottom = bottomBound; } } + interface SupportedViews { scalable_image: { width: number; @@ -61,8 +72,9 @@ interface SupportedViews { units: string; }; metadata?: {}; - } + }; } + interface CZITile { x_offset: number; y_offset: number; @@ -70,18 +82,22 @@ interface CZITile { height: number; file: string; } + interface CZIHeightMap { - zoom_level: number, + zoom_level: number; plane: CZITile[][]; } + interface WholeCZIHierarchy { c_values: [{ - channel_id: string, + channel_id: string; height_map: CZIHeightMap[]; }]; } -const getOriginalTileBounds: Function = function(originalTile: Segment): (TileBounds | null) { +const getOriginalTileBounds: (originalTile: Segment) => TileBounds | null = ( + originalTile: Segment +): TileBounds | null => { const bounds: TileBounds = new TileBounds(-1, -1, -1, -1); for (const dimension of originalTile.Data.DirectoryEntry.DimensionEntries) { @@ -89,31 +105,36 @@ const getOriginalTileBounds: Function = function(originalTile: Segment): (TileBo case 'X': bounds.left = dimension.Start; bounds.right = bounds.left + dimension.Size; - continue; + break; case 'Y': bounds.top = dimension.Start; bounds.bottom = bounds.top + dimension.Size; - continue; - default: - continue; + break; } } - if (bounds.left < 0 || bounds.right < 0 || bounds.top < 0 || bounds.bottom < 0) { + if (bounds.left < 0 + || bounds.right < 0 + || bounds.top < 0 + || bounds.bottom < 0 + ) { return null; } return bounds; }; -const findRelatedTiles: Function = function(activeSegments: Segment[], desired: TileBounds): Segment[] { +const findRelatedTiles: (activeSegments: Segment[], desired: TileBounds) => + Segment[] = ( + activeSegments: Segment[], desired: TileBounds +): Segment[] => { const relatedTiles: Segment[] = []; for (const baseTile of activeSegments) { - let origCoords: TileBounds | null; - if ((origCoords = getOriginalTileBounds(baseTile)) === null) { + origCoords = getOriginalTileBounds(baseTile); + if (origCoords === null) { throw new Error('There was a Sad Boi error'); } @@ -149,17 +170,20 @@ const findRelatedTiles: Function = function(activeSegments: Segment[], desired: return relatedTiles; }; -const getDimension: Function = function(segment: Segment, name: string): Dimension { +const getDimension: (segment: Segment, name: string) => Dimension = ( + segment: Segment, name: string +): Dimension => { for (const dimension of segment.Data.DirectoryEntry.DimensionEntries) { if (dimension.Dimension === name) { return dimension; } } - throw new Error('Dimension: ' + name + " doesn't exist for segment: " + segment); + throw new Error(`Dimension: ${name} doesn't exist for segment: ${segment}`); }; -const orderSegments: Function = function(segments: Segment[]): Segment[][] { - +const orderSegments: (segments: Segment[]) => Segment[][] = ( + segments: Segment[] +): Segment[][] => { const output: Segment[][] = []; if (segments.length > 1) { @@ -170,16 +194,19 @@ const orderSegments: Function = function(segments: Segment[]): Segment[][] { const initC: number = getDimension(segments[0], 'C').Start; for (const seg of segments) { if (getDimension(seg, 'C').Start !== initC) { - throw new Error('Segment array contains multiple values of C - this overlay is currently unsupported within this method'); + throw new Error(`Segment array contains multiple values of C -\ + this overlay is currently unsupported within this method`); } xCoords.push(getDimension(seg, 'X').Start); yCoords.push(getDimension(seg, 'Y').Start); } - // Filter to get Uniaue Values - xCoords = xCoords.filter( - (item: number, index: number, array: number[]) => array.indexOf(item) === index); - yCoords = yCoords.filter( - (item: number, index: number, array: number[]) => array.indexOf(item) === index); + + // Filter to get Unique Values + const filter: (item: number, index: number, array: number[]) => boolean = ( + item: number, index: number, array: number[] + ): boolean => array.indexOf(item) === index; + xCoords = xCoords.filter(filter); + yCoords = yCoords.filter(filter); // Use the filtered list to order the segments into rows for (const yVal of yCoords) { @@ -215,100 +242,127 @@ const orderSegments: Function = function(segments: Segment[]): Segment[][] { } }; -const findRegionToExtract: Function = function(segment: Segment, desired: TileBounds): TileBounds { +const findRegionToExtract: (segment: Segment, desired: TileBounds) => + TileBounds = ( + segment: Segment, desired: TileBounds +): TileBounds => { const baseBounds: TileBounds = getOriginalTileBounds(segment); - let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); + const chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); - if (desired.left <= baseBounds.left) { - chunkToExtract.left = 0; - } else { - chunkToExtract.left = desired.left - baseBounds.left; - } + chunkToExtract.left = desired.left <= baseBounds.left + ? 0 + : desired.left - baseBounds.left; - if (desired.right >= baseBounds.right) { - chunkToExtract.right = baseBounds.right - baseBounds.left; - } else { - chunkToExtract.right = desired.right - baseBounds.left; - } + chunkToExtract.right = desired.right >= baseBounds.right + ? baseBounds.right - baseBounds.left + : desired.right - baseBounds.left; - if (desired.top <= baseBounds.top) { - chunkToExtract.top = 0; - } else { - chunkToExtract.top = desired.top - baseBounds.top; - } + chunkToExtract.top = desired.top <= baseBounds.top + ? 0 + : desired.top - baseBounds.top; - if (desired.bottom >= baseBounds.bottom) { - chunkToExtract.bottom = baseBounds.bottom - baseBounds.top; - } else { - chunkToExtract.bottom = desired.bottom - baseBounds.top; - } + chunkToExtract.bottom = desired.bottom >= baseBounds.bottom + ? baseBounds.bottom - baseBounds.top + : desired.bottom - baseBounds.top; return chunkToExtract; }; -const extractAndStitchChunks: Function = async function(segments: Segment[][], desiredRegion: TileBounds): Promise { +interface Offset { + top: number; + bottom: number; + right: number; + left: number; +} + +const stitchInALine: ( + buffers: Buffer[], + offset: (bufferBound: TileBounds, tileSize: number) => Offset +) => Promise = async( + buffers: Buffer[], + offset: (bufferBound: TileBounds, tileSize: number) => Offset +): Promise => { + let image: SharpInstance = sharp(null, { + create: { + } + }); +}; - let tileVerticalBuffer: Buffer[] = []; +const extractAndStitchChunks: ( + segments: Segment[][], desiredRegion: TileBounds +) => Promise = async( + segments: Segment[][], desiredRegion: TileBounds +): Promise => { + const tileVerticalBuffer: Buffer[] = []; for (const segRow of segments) { - let tileRow: Buffer[] = []; + const tileRowPromises: Promise[] = []; let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); for (const segCol of segRow) { chunkToExtract = findRegionToExtract(segCol, desiredRegion); - let data: Promise = + const data: Promise = sharp(`${extractionDirectory}${segCol.Data.Data}`) - .extract({ - left: chunkToExtract.left, - top: chunkToExtract.top, - width: chunkToExtract.right - chunkToExtract.left, - height: chunkToExtract.bottom - chunkToExtract.top - }) - .toBuffer(); - - tileRow.push(await data); + .extract({ + left: chunkToExtract.left, + top: chunkToExtract.top, + width: chunkToExtract.right - chunkToExtract.left, + height: chunkToExtract.bottom - chunkToExtract.top + }).toBuffer(); + + tileRowPromises.push(data); } + const tileRow: Buffer[] = await Promise.all(tileRowPromises); let imageVerticalSlice: SharpInstance = sharp(tileRow[0]); - let bufferBound = findRegionToExtract(segRow[0], desiredRegion); + const bufferBound: TileBounds = findRegionToExtract(segRow[0], desiredRegion); if ((bufferBound.right - bufferBound.left) < (tileSize - tileOverlap)) { - imageVerticalSlice = await imageVerticalSlice.extend( - {top:0, left:0, bottom:0, right: (tileSize - (bufferBound.right - bufferBound.left))}); + imageVerticalSlice = await imageVerticalSlice.extend({ + top: 0, + left: 0, + bottom: 0, + right: (tileSize - (bufferBound.right - bufferBound.left)) + }); } - for (let index = 1; index < segRow.length; index++) { + for (let index: number = 1; index < segRow.length; index++) { imageVerticalSlice = await imageVerticalSlice - .overlayWith(tileRow[index], - {top: 0, left: (bufferBound.right - bufferBound.left) + ((index -1) * tileSize)}); + .overlayWith(tileRow[index], { + top: 0, + left: (bufferBound.right - bufferBound.left) + + ((index - 1) * tileSize) + }); } tileVerticalBuffer.push(await imageVerticalSlice.toBuffer()); } let finalImage: SharpInstance = sharp(tileVerticalBuffer[0]); - let bufferBound = findRegionToExtract(segments[0][0], desiredRegion); + const bufferBound: TileBounds = + findRegionToExtract(segments[0][0], desiredRegion); if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) { - finalImage = await finalImage.extend( - {top:0, left:0, bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), right: 0}); + finalImage = await finalImage.extend({ + top: 0, + left: 0, + bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), + right: 0 + }); } - for (let index = 1; index < segments.length; index++) { + for (let index: number = 1; index < segments.length; index++) { finalImage = finalImage.overlayWith( tileVerticalBuffer[index], - {top: getDimension(segments[index -1][0], 'Y').Size, left: 0}); + {top: getDimension(segments[index - 1][0], 'Y').Size, left: 0}); } return finalImage; }; - - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// const dataBlocks: Segment[] = require(`${extractionDirectory}outputjson.json`).czi.filter( (s: Segment) => s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty'); const inspect = require('util').inspect; const metaXML: parsexml.Document = parsexml(fs.readFileSync(`${extractionDirectory}FILE-META-1.xml`, 'utf8')); -let supportedViews: SupportedViews = {scalable_image: {width: -1, height: -1, channels: [{channel_id: '-1', channel_name: ''}], metadata: metaXML}}; +const supportedViews: SupportedViews = {scalable_image: {width: -1, height: -1, channels: [{channel_id: '-1', channel_name: ''}], metadata: metaXML}}; supportedViews.scalable_image.channels.pop(); let totalSizeX: number = -1; @@ -330,13 +384,13 @@ for (const child of metaXML.root.children) { totalSizeY = Number.parseInt(property.content, 10); supportedViews.scalable_image.height = totalSizeY; continue; - } else if(property.name === 'Dimensions') { + } else if (property.name === 'Dimensions') { for (const chan of property.children) { if (chan.name === 'Channels') { for (const channel of chan.children) { supportedViews.scalable_image.channels.push( { - channel_id: channel.attributes.Id.split(":")[1], + channel_id: channel.attributes.Id.split(':')[1], channel_name: channel.attributes.Name, metadata: channel.children } @@ -383,16 +437,15 @@ const filterC: Function = function(to: number): void { ); }; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Begin work on getting the new tiles all nice // Print out all of the related tiles to every new tile to be created. let filecoutner: number = 0; async function extrapolateDimension(cVal: number, totalCs: number, maxZoomLevel: number): Promise { - console.log(`Stage (${cVal + 1}/${totalCs}): Task(0/${Math.ceil(totalSizeY/tileSize)}): 0% complete.`) + console.log(`Stage (${cVal + 1}/${totalCs}): Task(0/${Math.ceil(totalSizeY / tileSize)}): 0% complete.`); for (let ys: number = 0; ys < totalSizeY;) { - var timing = process.hrtime(); + let timing = process.hrtime(); for (let xs: number = 0; xs < totalSizeX; xs += tileSize) { const desired = new TileBounds ( xs - tileOverlap, @@ -408,20 +461,19 @@ async function extrapolateDimension(cVal: number, totalCs: number, maxZoomLevel: } ys += tileSize; timing = process.hrtime(timing); - console.log(`Stage (${cVal + 1}/${totalCs}): Task(${ys/tileSize}/${Math.ceil(totalSizeY/tileSize)}): ${Math.ceil(((ys/totalSizeY)*100) *100)/100}% complete. (${timing[0]} sec/iter)`); + console.log(`Stage (${cVal + 1}/${totalCs}): Task(${ys / tileSize}/${Math.ceil(totalSizeY / tileSize)}): ${Math.ceil(((ys / totalSizeY) * 100) * 100) / 100}% complete. (${timing[0]} sec/iter)`); } return []; } -let finalCZIJson: WholeCZIHierarchy = {} as any; +const finalCZIJson: WholeCZIHierarchy = {} as any; async function main(): Promise { for (const cval of supportedViews.scalable_image.channels) { - await extrapolateDimension(Number.parseInt(cval.channel_id, 10), supportedViews.scalable_image.channels.length, maxZoom).then(v => - { + await extrapolateDimension(Number.parseInt(cval.channel_id, 10), supportedViews.scalable_image.channels.length, maxZoom).then((v) => { finalCZIJson.c_values.push({channel_id: cval.channel_id, height_map: v}); console.log(`Completed Tier: ${cval.channel_id}`); return; - }, err => { + }, (err) => { console.error(err); } ); -- cgit v1.2.1 From b9c3dd19483972c68adfe15f2370485f8535fece Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 29 Mar 2018 12:22:06 +0100 Subject: Clean up some of czi.ts --- src/conversion/czi/czi.ts | 895 +++++++++++++++-------------- src/conversion/czi/pyramidWorker.ts | 77 +-- src/conversion/czi/tileExtraction.ts | 19 +- src/conversion/types/customPyramidIndex.ts | 46 +- src/conversion/types/helperCZITypes.ts | 18 +- 5 files changed, 529 insertions(+), 526 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index 6e0b00c..c2d88ab 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -1,16 +1,16 @@ - +import { CZIHeightMap, CZITile, + WholeCZIHierarchy } from '../types/customPyramidIndex'; +import { Dimension, Segment } from '../types/cziBinaryTypings'; import * as fs from 'fs'; -import * as parsexml from 'xml-parser'; -import { logger } from '../../logger'; +import { SupportedViews, TileBounds } from '../types/helperCZITypes'; +import { logger } from '../../logging'; import * as sharp from 'sharp'; // tslint:disable-next-line:no-duplicate-imports import { SharpInstance } from 'sharp'; -import { CZITile, CZIHeightMap, WholeCZIHierarchy } from '../types/customPyramidIndex'; -import { Dimension, DirectoryEntry, SubBlock, Segment } from '../types/cziBinaryTypings'; -import { SupportedViews, TileBounds } from '../types/helperCZITypes'; import { isTileRelated, regionToExtract } from './tileExtraction'; +import * as parsexml from 'xml-parser'; -//various constants for placing files and defining tiles +// Various constants for placing files and defining tiles const baseDirname: string = '/cs/scratch/cjd24/0701-extraction'; const extractionDirectory: string = `${baseDirname}/`; const outputImageData: string = `${baseDirname}-processed/`; @@ -19,21 +19,24 @@ const tileOverlap: number = 0; // Overlap is only half implemented const tileSize: number = 1024; const maxZoom: number = 64; -/* - * Simple function to find the tile bounds version of an original tile in the base image +/** + * Simple function to find the tile bounds version of an original tile + * in the base image */ -const getOriginalTileBounds: Function = function(originalTile: Segment): (TileBounds | null) { +const getOriginalTileBounds: (originalTile: Segment) => TileBounds = ( + originalTile: Segment +): TileBounds => { const bounds: TileBounds = new TileBounds(-1, -1, -1, -1); - //loop over all dimensions to get the x and y + // Loop over all dimensions to get the x and y for (const dimension of originalTile.Data.DirectoryEntry.DimensionEntries) { switch (dimension.Dimension) { - //If we have found x, then match the start and width + // If we have found x, then match the start and width case 'X': bounds.left = dimension.Start; bounds.right = bounds.left + dimension.Size; continue; - //If we have found y, then match the top and bottom + // If we have found y, then match the top and bottom case 'Y': bounds.top = dimension.Start; bounds.bottom = bounds.top + dimension.Size; @@ -43,19 +46,21 @@ const getOriginalTileBounds: Function = function(originalTile: Segment): (TileBo } } - //If one of the bounds was not created, then there must have been an error + // If one of the bounds was not created, then there must have been an error if (bounds.left < 0 || bounds.right < 0 || bounds.top < 0 || bounds.bottom < 0 ) { - return null; + throw new Error( + `One of the bounds had a dimension less than zero: ${originalTile.Data.Data}` + ); } - //Successful return + // Successful return return bounds; }; -/* +/** * Function used to find which of the original base tiles are * overlapping with the area of the to-be-created tile */ @@ -65,16 +70,9 @@ const findRelatedTiles: (activeSegments: Segment[], desired: TileBounds) => ): Segment[] => { const relatedTiles: Segment[] = []; - //For all tiles within the region being checked + // For all tiles within the region being checked for (const baseTile of activeSegments) { - - let origCoords: TileBounds | null; - - if ((origCoords = getOriginalTileBounds(baseTile)) === null) { - throw new Error('There was a Sad Boi error'); - } - - if (isTileRelated(origCoords, desired)) { + if (isTileRelated(getOriginalTileBounds(baseTile), desired)) { relatedTiles.push(baseTile); } } @@ -82,23 +80,24 @@ const findRelatedTiles: (activeSegments: Segment[], desired: TileBounds) => return relatedTiles; }; -/* - * This gets the particular dimension from a segment given a segment and dimesnion ID +/** + * This gets the particular dimension from a segment given a segment + * and dimension ID */ const getDimension: (segment: Segment, name: string) => Dimension = ( segment: Segment, name: string ): Dimension => { for (const dimension of segment.Data.DirectoryEntry.DimensionEntries) { - //If the current dimension is the one we are looking for then return it. + // If the current dimension is the one we are looking for then return it. if (dimension.Dimension === name) { return dimension; } } - //If we have gotten to here, then the dimension doesnt exist, so throw error. - throw new Error('Dimension: ' + name + " doesn't exist for segment: " + segment); + // If we have gotten to here, then the dimension doesnt exist, so throw error. + throw new Error(`Dimension: ${name} doesn't exist for segment: ${segment}`); }; -/* +/** * This takes a selection of segments and ensures that they are ordered * left to right, and top to bottom like the words in a book, so that the * stiching process will take the correct slice from them all. @@ -109,14 +108,14 @@ const orderSegments: (segments: Segment[]) => Segment[][] = ( ): Segment[][] => { const output: Segment[][] = []; - //So long as there is at least 2 segments to order + // So long as there is at least 2 segments to order if (segments.length > 1) { let xCoords: number[] = []; let yCoords: number[] = []; // Get all x/y's; // However also ensure that all of the segments to be ordered, all come - // from the same value of 'C' dimension, otherwise there could be overlaps. + // From the same value of 'C' dimension, otherwise there could be overlaps. const initC: number = getDimension(segments[0], 'C').Start; for (const seg of segments) { if (getDimension(seg, 'C').Start !== initC) { @@ -164,18 +163,21 @@ const orderSegments: (segments: Segment[]) => Segment[][] = ( return output; } - //There is only one segment, so no need to re-order. + // There is only one segment, so no need to re-order. return [segments]; }; -/* +/** * Takes a base tile, and the whole bounds of a new tile, and uses this * to calculate the region within the base tile that is overlapping the new tile * to be extracted. */ -const findRegionToExtract: Function = function(segment: Segment, desired: TileBounds): TileBounds { - - //return the slice within the base tile for extraction +const findRegionToExtract: ( + segmanet: Segment, desired: TileBounds +) => TileBounds = ( + segment: Segment, desired: TileBounds +): TileBounds => { + // Return the slice within the base tile for extraction return regionToExtract(getOriginalTileBounds(segment), desired, 1); }; @@ -183,23 +185,26 @@ const findRegionToExtract: Function = function(segment: Segment, desired: TileBo * Take an ordered selection of segments and cookie cutter out a tile from this * into a new image */ -const extractAndStitchChunks: Function = async function(segments: Segment[][], desiredRegion: TileBounds): Promise { - - //create a buffer for the rows part of raw image data - let tileVerticalBuffer: Buffer[] = []; - - //for all ros (y coords) in the image +const extractAndStitchChunks: ( + segments: Segment[][], desiredRegion: TileBounds +) => Promise = async( + segments: Segment[][], desiredRegion: TileBounds +): Promise => { + // Create a buffer for the rows part of raw image data + const tileVerticalBuffer: Buffer[] = []; + + // For all ros (y coords) in the image for (const segRow of segments) { - //create a buffer for this row - let tileRow: Buffer[] = []; + // Create a buffer for this row + const tileRow: Buffer[] = []; let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); - //For all of the columns within this row + // For all of the columns within this row for (const segCol of segRow) { - //find out the region of the base tile to be added to the new image + // Find out the region of the base tile to be added to the new image chunkToExtract = findRegionToExtract(segCol, desiredRegion); - //extract this section of image data into a sharp buffer - let data: Promise = + // Extract this section of image data into a sharp buffer + const data: Promise = sharp(`${extractionDirectory}${segCol.Data.Data}`) .extract({ left: chunkToExtract.left, @@ -209,336 +214,344 @@ const extractAndStitchChunks: Function = async function(segments: Segment[][], d }) .toBuffer(); - //push this data into the row buffer + // Push this data into the row buffer tileRow.push(await data); } - //prepare variables to squash all of the column data into one, for this row + // Prepare variables to squash all of the column data into one, for this row let imageVerticalSlice: SharpInstance = sharp(tileRow[0]); - let bufferBound = findRegionToExtract(segRow[0], desiredRegion); - //check if the inital chunk needs to be extended to support the other columns + const bufferBound: TileBounds = findRegionToExtract(segRow[0], desiredRegion); + // Check if the inital chunk needs to be extended to support the other columns if ((bufferBound.right - bufferBound.left) < (tileSize - tileOverlap)) { - imageVerticalSlice = await imageVerticalSlice.extend( - {top:0, left:0, bottom:0, right: (tileSize - (bufferBound.right - bufferBound.left))}); + imageVerticalSlice = await imageVerticalSlice.extend({ + top: 0, + left: 0, + bottom: 0, + right: (tileSize - (bufferBound.right - bufferBound.left)) + }); } - //for every column along this row, join it to the previous column data - for (let index = 1; index < segRow.length; index++) { + // For every column along this row, join it to the previous column data + for (let index: number = 1; index < segRow.length; index++) { imageVerticalSlice = await imageVerticalSlice - .overlayWith(tileRow[index], - {top: 0, left: (bufferBound.right - bufferBound.left) + ((index -1) * tileSize)}); + .overlayWith(tileRow[index], { + top: 0, + left: (bufferBound.right - bufferBound.left) + + ((index - 1) * tileSize) + }); } - //add this horizontal data buffer to the vertical buffer + // Add this horizontal data buffer to the vertical buffer tileVerticalBuffer.push(await imageVerticalSlice.toBuffer()); } - //prepare variables used to combine all rows into one image + // Prepare variables used to combine all rows into one image let finalImage: SharpInstance = sharp(tileVerticalBuffer[0]); - let bufferBound = findRegionToExtract(segments[0][0], desiredRegion); - //Check if the inital row needs to be extended to support further rows + const bufferBound: TileBounds = + findRegionToExtract(segments[0][0], desiredRegion); + // Check if the inital row needs to be extended to support further rows if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) { - finalImage = await finalImage.background({r: 0, g: 0, b: 0, alpha: 0}).extend( - {top:0, left:0, bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), right: 0}); + finalImage = await finalImage.background({ + r: 0, + g: 0, + b: 0, + alpha: 0 + }).extend({ + top: 0, + left: 0, + bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), + right: 0 + }); } - //For all further rows in the image, combine it with the previous rows' data - for (let index = 1; index < segments.length; index++) { + // For all further rows in the image, combine it with the previous rows' data + for (let index: number = 1; index < segments.length; index++) { finalImage = finalImage.overlayWith( tileVerticalBuffer[index], - {top: getDimension(segments[index -1][0], 'Y').Size, left: 0}); + {top: getDimension(segments[index - 1][0], 'Y').Size, left: 0}); } - //return the finalised image. + // Return the finalised image. return finalImage; }; -/* - * Used to remove obtuse JSON data, where it is not needed in the SupportedView object +/** + * Used to remove obtuse JSON data, + * where it is not needed in the SupportedView object */ -const cleanSupportedViewObject: Function = function(obj: parsexml.Node[]): Object { - let newChild: any = {}; - let hasAttr: boolean = false, hasChildren: boolean = false, hasContent: boolean = false; - - //for all nodes in the json object - for (const node of obj) { - - //Check if this node has attributes - if (node.attributes !== undefined && node.attributes !== null && Object.keys(node.attributes).length !== 0) - {hasAttr = true;} else {hasAttr = false;} - //Check for further children - if (node.children !== undefined && node.children.length > 0) - {hasChildren = true;} else {hasChildren = false;} - //Check for simple content object - if (node.content !== undefined && node.content !== null && node.content !== '') - {hasContent = true;} else {hasContent = false;} - - //If the Node has further children, then deal with this - if (hasChildren) { - let soloChildren: boolean = true; - - //Check if this node just contains children, or its own data too - newChild[node.name] = {} - if (hasAttr) { - //IF there are also attributes, then set this in the output +const cleanSupportedViewObject: (obj: parsexml.Node[]) => object = ( + obj: parsexml.Node[] +): object => { + const newChild: any = {}; + let hasAttr: boolean = false; + let hasChildren: boolean = false; + let hasContent: boolean = false; + + // For all nodes in the json object + for (const node of obj) { + + // Check if this node has attributes + hasAttr = (node.attributes !== undefined + && node.attributes !== null + && Object.keys(node.attributes).length !== 0 + ); + // Check for further children + hasChildren = (node.children !== undefined && node.children.length > 0); + // Check for simple content object + hasContent = (node.content !== undefined + && node.content !== null + && node.content !== ''); + + // If the Node has further children, then deal with this + if (hasChildren) { + let soloChildren: boolean = true; + + // Check if this node just contains children, or its own data too + newChild[node.name] = {}; + if (hasAttr) { + // If there are also attributes, then set this in the output newChild[node.name].attributes = node.attributes; - soloChildren = false; - } - if (hasContent) { - //If there is also a 'content' then set this in the output - newChild[node.name].content = node.content; - soloChildren = false; - } - //If there are only chilren, then set this as this objects data - if (soloChildren) { - //recursively call this function to clean up sub-children too. - newChild[node.name] = cleanSupportedViewObject(node.children); - } else { - //Otherwise, if there is also data, then add a children object + soloChildren = false; + } + if (hasContent) { + // If there is also a 'content' then set this in the output + newChild[node.name].content = node.content; + soloChildren = false; + } + // If there are only chilren, then set this as this objects data + if (soloChildren) { + // Recursively call this function to clean up sub-children too. + newChild[node.name] = cleanSupportedViewObject(node.children); + } else { + // Otherwise, if there is also data, then add a children object newChild[node.name].children = cleanSupportedViewObject(node.children); - } - } - - //If this node only has attributes, then add this - else if (hasAttr) { + } + } else if (hasAttr) { newChild[node.name] = {}; - //Check for content too, if so, add a discrete child for this. - if (hasContent) { - newChild[node.name].content = node.content; - } - //add the attributes as a sub child regardless, - // since it exists on this key. + // Check for content too, if so, add a discrete child for this. + if (hasContent) { + newChild[node.name].content = node.content; + } + /* + * Add the attributes as a sub child regardless, + * since it exists on this key. + */ newChild[node.name].attributes = node.attributes; - } - - //If this node only has a content object then remove all other content - // and only attatch the content result as the value for this node key - else if (hasContent) { - newChild[node.name] = node.content; - } + } else if (hasContent) { + newChild[node.name] = node.content; + } } - return newChild; + return newChild; }; -/* +/** * Clean up all vales of C within the JSON for supported views */ -const cleanSupportedViews: Function = function(view: SupportedViews): void { +const cleanSupportedViews: (view: SupportedViews) => void = ( + view: SupportedViews +): void => { for (const channel of view.scalable_image.channels) { - channel.metadata = cleanSupportedViewObject(channel.metadata); - } + channel.metadata = cleanSupportedViewObject(channel.metadata); + } }; - - -//create the objects needed for parsing the XML object of the initial extraction. -const dataBlocks: Segment[] = require(`${extractionDirectory}outputjson.json`).czi.filter( - (s: Segment) => s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty'); +/** + * Create the objects needed for parsing the XML object + * of the initial extraction. + */ +// tslint:disable-next-line:no-var-requires +const dataBlocks: Segment[] = require(`${extractionDirectory}outputjson.json`) + .czi.filter( + (s: Segment) => s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty'); let totalSizeX: number = -1; let totalSizeY: number = -1; -let supportedViews: SupportedViews = {scalable_image: {width: -1, height: -1, channels: [{channel_id: '-1', channel_name: ''}], metadata: {}}}; +const supportedViews: SupportedViews = { + scalable_image: { + width: -1, + height: -1, + channels: [{ + channel_id: '-1', + channel_name: '' + }], + metadata: {} + } +}; supportedViews.scalable_image.channels.pop(); +/* tslint:disable:curly cyclomatic-complexity */ /* - * Function to parse the xml file from the original extraction from CZI, its nasty! + * Function to parse the xml file from the original extraction from CZI, + * its nasty! */ -const parseExtractedXML: Function = function(xmlFile: string): void { - // const inspect = require('util').inspect; // << Used when console logging stuff to prettify it - const metaXML: parsexml.Document = parsexml(fs.readFileSync(xmlFile, 'utf8')); - // parse the XML :( - // THE FOLLOWING 2 FOR LOOPS ARE DISGUSTING AND I HATE IT, AND I WISH I DIDNT WRITE IT BUT DON'T SEE ANY OTHER WAY TO DO IT LOL :'( - for (const child of metaXML.root.children) { - if (child.name === 'Metadata') { - for (const entry of child.children) { - if (entry.name === 'Information') { - for (const properties of entry.children) { - if (properties.name === 'Image') { - for (const property of properties.children) { - if (property.name === 'SizeX' && property.content) { - totalSizeX = Number.parseInt(property.content, 10); - supportedViews.scalable_image.width = totalSizeX; - continue; - } else if (property.name === 'SizeY' && property.content) { - totalSizeY = Number.parseInt(property.content, 10); - supportedViews.scalable_image.height = totalSizeY; - continue; - } else if(property.name === 'Dimensions') { - for (const chan of property.children) { - if (chan.name === 'Channels') { - for (const channel of chan.children) { - supportedViews.scalable_image.channels.push( - { - channel_id: channel.attributes.Id.split(":")[1], - channel_name: channel.attributes.Name, - metadata: channel.children - } - ); - } - } - } - } - } - } - } - } - } - } - } - for (const child of metaXML.root.children) { - if (child.name === 'Metadata') { - for (const entry of child.children) { - if (entry.name === 'Scaling') { - for (const properties of entry.children) { - if (properties.name === 'Items') { - for (const dist of properties.children) { - if (dist.name === 'Distance') { - if (dist.attributes.Id === 'X') { - supportedViews.scalable_image.real_width = {}; - for (const attr of dist.children) { - if (attr.name === 'Value' && attr.content !== undefined) - supportedViews.scalable_image.real_width.value = Number.parseFloat(attr.content) * 1000000 * totalSizeX; - if (attr.name === 'DefaultUnitFormat') - supportedViews.scalable_image.real_width.units = attr.content; - } - } - if (dist.attributes.Id === 'Y') { - supportedViews.scalable_image.real_height = {}; - for (const attr of dist.children) { - if (attr.name === 'Value' && attr.content !== undefined) - supportedViews.scalable_image.real_height.value = Number.parseFloat(attr.content) * 1000000 * totalSizeY; - if (attr.name === 'DefaultUnitFormat') - supportedViews.scalable_image.real_height.units = attr.content; - } - } - } - } - } - } - } - } - } - } - supportedViews.scalable_image.metadata = metaXML; +const parseExtractedXML: (xmlFile: string) => void = ( + xmlFile: string +): void => { + const metaXML: parsexml.Document = parsexml(fs.readFileSync(xmlFile, 'utf8')); + // Parse the XML :( + // THE FOLLOWING 2 FOR LOOPS ARE DISGUSTING AND I HATE IT, + // AND I WISH I DIDNT WRITE IT BUT DON'T SEE ANY OTHER WAY TO DO IT LOL :'( + for (const child of metaXML.root.children) if (child.name === 'Metadata') { + for (const entry of child.children) if (entry.name === 'Information') { + for (const properties of entry.children) if (properties.name === 'Image') { + for (const property of properties.children) if ( + property.name === 'SizeX' && property.content + ) { + totalSizeX = Number.parseInt(property.content, 10); + supportedViews.scalable_image.width = totalSizeX; + continue; + } else if (property.name === 'SizeY' && property.content) { + totalSizeY = Number.parseInt(property.content, 10); + supportedViews.scalable_image.height = totalSizeY; + continue; + } else if (property.name === 'Dimensions') { + for (const chan of property.children) if (chan.name === 'Channels') { + for (const channel of chan.children) { + supportedViews.scalable_image.channels.push({ + channel_id: channel.attributes.Id.split(':')[1], + channel_name: channel.attributes.Name, + metadata: channel.children + }); + } + } + } + break; + } + break; + } + break; + } + for (const child of metaXML.root.children) if (child.name === 'Metadata') { + for (const entry of child.children) if (entry.name === 'Scaling') { + for (const properties of entry.children) if (properties.name === 'Items') { + for (const dist of properties.children) if (dist.name === 'Distance') { + switch (dist.attributes.Id) { + case 'X': { + supportedViews.scalable_image.real_width = {}; + for (const attr of dist.children) { + if (attr.name === 'Value' && attr.content !== undefined) { + supportedViews.scalable_image.real_width.value = + Number.parseFloat(attr.content) * 1000000 * totalSizeX; + } else if (attr.name === 'DefaultUnitFormat') { + supportedViews.scalable_image.real_width.units = attr.content; + } + } + break; + } + case 'Y': { + supportedViews.scalable_image.real_height = {}; + for (const attr of dist.children) { + if (attr.name === 'Value' && attr.content !== undefined) { + supportedViews.scalable_image.real_height.value = + Number.parseFloat(attr.content) * 1000000 * totalSizeY; + } else if (attr.name === 'DefaultUnitFormat') { + supportedViews.scalable_image.real_height.units = attr.content; + } + } + break; + } + } + } + break; + } + break; + } + break; + } + supportedViews.scalable_image.metadata = metaXML; }; +/* tslint:enable:curly cyclomatic-complexity */ - - -// // Get all values of X and Y respectively. -// const uniqueX: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'X').Start).filter( -// (item: number, index: number, array: number[]) => array.indexOf(item) === index); -// const uniqueY: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'Y').Start).filter( -// (item: number, index: number, array: number[]) => array.indexOf(item) === index); -// -// const uniqueTileSizes: number[][] = []; -// for (const seg of dataBlocks) { -// -// const x: number = getDimension(seg, 'X').Size; -// const y: number = getDimension(seg, 'Y').Size; -// let found: boolean = false; -// for (const dimPair of uniqueTileSizes) { -// if (x === dimPair[0] && y === dimPair[1]) { -// found = true; -// break; -// } -// } -// if (!found) { -// uniqueTileSizes.push([x, y]); -// } -// } - - - -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// Begin work on getting the new tiles all nice // -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -//used to filter all databocks to get certain values of 'C'. -let filteredDataBlocks: Segment[] = []; -const filterC: Function = function(c_value_filter: number): void -{ - filteredDataBlocks = dataBlocks.filter( - (item: Segment, index: number, array: Segment[]) => getDimension(item, 'C').Start === c_value_filter - ); -}; +//////////////////////////////////////////////////////////////////////////////// +// Begin work on getting the new tiles all nice +//////////////////////////////////////////////////////////////////////////////// // Print out all of the related tiles to every new tile to be created. -let filecoutner: number = 0; -/* +let filecounter: number = 0; +/** * This is used to create the next zoomed out tier of the given height map */ -const zoomTier: Function = async function(previousHeightMap:CZIHeightMap): Promise { - - let ys:number = 0, timing = process.hrtime(), iterTimes: number[] = [50], avgItrTime: number;; - let newZoomTier: CZIHeightMap = {zoom_level: previousHeightMap.zoom_level * 2, plane: []}; - - //Check the condition where another zoom level does not make sense - if (previousHeightMap.plane.length === 1 && previousHeightMap.plane[0].length === 1) { - console.log( - ` Task(1/1): ` + - `Stage 100% complete. ` + - `(0 sec/iter) Stage was skipped as maximum sensible zoom level was reached.` - ); - return previousHeightMap; +const zoomTier: ( + previousHeightMap: CZIHeightMap +) => Promise = async( + previousHeightMap: CZIHeightMap +): Promise => { + let ys: number = 0; + let timing: [number, number] = process.hrtime(); + const iterTimes: number[] = [50]; + let avgItrTime: number; + const newZoomTier: CZIHeightMap = { + zoom_level: previousHeightMap.zoom_level * 2, plane: [] + }; + + // Check the condition where another zoom level does not make sense + if (previousHeightMap.plane.length === 1 + && previousHeightMap.plane[0].length === 1) { + logger.info( + ' Task(1/1): ' + + 'Stage 100% complete. ' + + '(0 sec/iter) Stage was skipped as maximum sensible zoom level was reached.' + ); + return previousHeightMap; } - //For all rows within the previous plane - for (;ys < previousHeightMap.plane.length; ys += 2) { + // For all rows within the previous plane + for (; ys < previousHeightMap.plane.length; ys += 2) { timing = process.hrtime(); - let cziRow: CZITile[] = []; - //for all columns within the previous plane + const cziRow: CZITile[] = []; + // For all columns within the previous plane for (let xs: number = 0; xs < previousHeightMap.plane[0].length; xs += 2) { -// console.error(`ys: ${ys} ymax:${previousHeightMap.plane.length} xs: ${xs} xmax: ${previousHeightMap.plane[0].length}`) - - //combine 4 tiles into a new tile and scale down for this tier - + // Combine 4 tiles into a new tile and scale down for this tier let combinedTile: SharpInstance; - //top left -// console.error(`SharpInitFile: ${previousHeightMap.plane[ys][xs].file}`) - combinedTile = await sharp(`${outputImageDirectory}${previousHeightMap.plane[ys][xs].file}`) - .background({r: 0, g: 0, b: 0, alpha: 0}).extend( - {top:0, left:0, bottom:tileSize, right: tileSize}); - - //combine top right - let moreToRight: boolean = (xs + 1) < previousHeightMap.plane[0].length; -// console.error(`More to right: ${moreToRight}`) + // Top left + combinedTile = await sharp( + `${outputImageDirectory}${previousHeightMap.plane[ys][xs].file}` + ).background({ + r: 0, + g: 0, + b: 0, + alpha: 0 + }).extend({ + top: 0, + left: 0, + bottom: tileSize, + right: tileSize + }); + + // Combine top right + const moreToRight: boolean = (xs + 1) < previousHeightMap.plane[0].length; if (moreToRight) { -// console.error(`Top Right: ${previousHeightMap.plane[ys][xs + 1].file}`) combinedTile = sharp(await combinedTile.overlayWith( `${outputImageDirectory}${previousHeightMap.plane[ys][xs + 1].file}`, {top: 0, left: tileSize}).toBuffer()); } - //combine bottom left - let moreToBottom: boolean = (ys + 1) < previousHeightMap.plane.length; -// console.error(`More to bottom: ${moreToBottom}`) + // Combine bottom left + const moreToBottom: boolean = (ys + 1) < previousHeightMap.plane.length; if (moreToBottom) { -// console.error(`Bottom Left: ${previousHeightMap.plane[ys + 1][xs].file}`) combinedTile = sharp(await combinedTile.overlayWith( `${outputImageDirectory}${previousHeightMap.plane[ys + 1][xs].file}`, {top: tileSize, left: 0}).toBuffer()); } - //combine bottom right + // Combine bottom right if (moreToBottom && moreToRight) { -// console.error(`Bottom Right: ${previousHeightMap.plane[ys + 1][xs + 1].file}`) combinedTile = sharp(await combinedTile.overlayWith( `${outputImageDirectory}${previousHeightMap.plane[ys + 1][xs + 1].file}`, {top: tileSize, left: tileSize}).toBuffer()); } -// console.error("\n\n"); - //rescale and push to file + // Rescale and push to file await combinedTile.resize(tileSize, tileSize) - .toFile(`${outputImageDirectory}img-${filecoutner}`);/*.toFile(`${outputImageData}/thing/img-${filecoutner}`);*/ + .toFile(`${outputImageDirectory}img-${filecounter}`); cziRow.push({ x_offset: previousHeightMap.plane[ys][xs].x_offset, y_offset: previousHeightMap.plane[ys][xs].y_offset, width: previousHeightMap.plane[ys][xs].width * 2, height: previousHeightMap.plane[ys][xs].height * 2, - file: `img-${filecoutner++}` + file: `img-${filecounter++}` }); finalCZIJson.total_files++; } @@ -546,43 +559,58 @@ const zoomTier: Function = async function(previousHeightMap:CZIHeightMap): Promi newZoomTier.plane.push(cziRow); timing = process.hrtime(timing); iterTimes.push(timing[0]); - if (iterTimes.length > 5) iterTimes.shift(); - avgItrTime = iterTimes.reduce((p, c, i) => {return p+(c-p)/(i+1)}, 0); - console.log( - ` Task(${ys/2 + 1}/${Math.floor(previousHeightMap.plane.length/2) + 1}): ` + - `Stage ${Math.ceil(((ys/previousHeightMap.plane.length)*100) *100)/100}% complete. ` + - `(${timing[0]} sec/iter, est: ${((avgItrTime * ((Math.floor(previousHeightMap.plane.length/2) + 1) - (ys/2 + 1)))/60).toFixed(2)} mins remain.)` + if (iterTimes.length > 5) { iterTimes.shift(); } + // tslint:disable-next-line:typedef + avgItrTime = iterTimes.reduce((p, c, i) => p + (c - p) / (i + 1), 0); + logger.info( + ` Task(${ys / 2 + 1}/${ + Math.floor(previousHeightMap.plane.length / 2) + 1}): ` + + `Stage ${Math.ceil(((ys / previousHeightMap.plane.length) + * 100) * 100) / 100}% complete. ` + + `(${timing[0]} sec/iter, est: ${((avgItrTime * + ((Math.floor(previousHeightMap.plane.length / 2) + 1) - + (ys / 2 + 1))) / 60).toFixed(2)} mins remain.)` ); } newZoomTier.tile_height_count = newZoomTier.plane.length; newZoomTier.tile_width_count = newZoomTier.plane[0].length; return newZoomTier; -} +}; -/* +/** * Big boi function to build up the base tier of each value of c, then builds * Our pre-computed pyramid of the rest of the zoom levels. */ -const extrapolateDimension:Function = async function(cVal: number, totalCs: number, maxZoom:number): Promise { - - let ys:number = 0, timing = process.hrtime(), iterTimes: number[] = [100], avgItrTime: number; - filterC(cVal); - //begin output for the base tier - console.log('========================================================='); - console.log(`>> Beginning Dimension Extrapolation for \'C\' : ${cVal}`); - console.log('========================================================='); - console.log(">> Computing base tier, this will take a while...\n") - let baseCZIHeightMap: CZIHeightMap = {zoom_level: 1, plane: []}, - width_in_tiles = 0, height_in_tiles = 0; - - console.log(`Stage (${cVal * Math.log2(maxZoom) + 1}/${totalCs}):`); - //For all rows within the total base pixel height - for (;ys < totalSizeY;) { +const extrapolateDimension: ( + cVal: number, totalCs: number, maxZoom: number +) => Promise = async( + cVal: number, totalCs: number, maxZoom: number +): Promise => { + let ys: number = 0; + let timing: [number, number] = process.hrtime(); + const iterTimes: number[] = [100]; + let avgItrTime: number; + const filteredDataBlocks: Segment[] = dataBlocks.filter( + (item: Segment, index: number, array: Segment[]) => + getDimension(item, 'C').Start === cVal + ); + // Begin output for the base tier + logger.info('========================================================='); + logger.info(`>> Beginning Dimension Extrapolation for \'C\' : ${cVal}`); + logger.info('========================================================='); + logger.info('>> Computing base tier, this will take a while...\n'); + const baseCZIHeightMap: CZIHeightMap = {zoom_level: 1, plane: []}; + let width_in_tiles = 0; + let height_in_tiles = 0; + + logger.info(`Stage (${cVal * Math.log2(maxZoom) + 1}/${totalCs}):`); + // For all rows within the total base pixel height + for (; ys < totalSizeY;) { timing = process.hrtime(); - let cziRow: CZITile[] = []; + const cziRow: CZITile[] = []; for (let xs: number = 0; xs < totalSizeX; xs += tileSize) { - const desired = new TileBounds ( + const desired: TileBounds = new TileBounds( xs - tileOverlap, xs + tileSize + tileOverlap, ys - tileOverlap, @@ -594,172 +622,183 @@ const extrapolateDimension:Function = async function(cVal: number, totalCs: numb y_offset: ys, width: tileSize, height: tileSize, - file: `img-${filecoutner}` + file: `img-${filecounter}` }); - const sortedSegments: Segment[][] = orderSegments(findRelatedTiles(filteredDataBlocks, desired)); - (await extractAndStitchChunks(sortedSegments, desired)).toFile(`${outputImageDirectory}img-${filecoutner++}`); - finalCZIJson.total_files++; - width_in_tiles = xs/tileSize; + const sortedSegments: Segment[][] = + orderSegments(findRelatedTiles(filteredDataBlocks, desired)); + (await extractAndStitchChunks(sortedSegments, desired)) + .toFile(`${outputImageDirectory}img-${filecounter++}`); + // tslint:disable-next-line:no-non-null-assertion + finalCZIJson.total_files!++; + width_in_tiles = xs / tileSize; } baseCZIHeightMap.plane.push(cziRow); ys += tileSize; timing = process.hrtime(timing); iterTimes.push(timing[0]); - if (iterTimes.length > 5) iterTimes.shift(); - avgItrTime = iterTimes.reduce((p, c, i) => {return p+(c-p)/(i+1)}, 0); - console.log( - ` Task(${ys/tileSize}/${Math.ceil(totalSizeY/tileSize)}): ` + - `Stage ${Math.ceil(((ys/totalSizeY)*100) *100)/100}% complete. ` + - `(${timing[0]} sec/iter, est: ${((avgItrTime * (Math.ceil(totalSizeY/tileSize) - ys/tileSize))/60).toFixed(2)} mins remain.)` + if (iterTimes.length > 5) { iterTimes.shift(); } + // tslint:disable-next-line:typedef + avgItrTime = iterTimes.reduce((p, c, i) => p + (c - p) / (i + 1), 0); + logger.info( + ` Task(${ys / tileSize}/${Math.ceil(totalSizeY / tileSize)}): ` + + `Stage ${Math.ceil(((ys / totalSizeY) * 100) * 100) / 100}% complete. ` + + `(${timing[0]} sec/iter, est: ${((avgItrTime * + (Math.ceil(totalSizeY / tileSize) - ys / tileSize)) / + 60).toFixed(2)} mins remain.)` ); - height_in_tiles = ys/tileSize; + height_in_tiles = ys / tileSize; } baseCZIHeightMap.tile_height_count = height_in_tiles; baseCZIHeightMap.tile_width_count = width_in_tiles; - //BUILD UP THE HIGHER ZOOM LAYERS. - console.log(">> Base tier complete for \'C\': " + cVal + "; Begin computing zoom tiers...\n") + // BUILD UP THE HIGHER ZOOM LAYERS. + logger.info(`>> Base tier complete for \'C\': ${cVal + }; Begin computing zoom tiers...\n`); - let retHeightMap: CZIHeightMap[] = [baseCZIHeightMap]; - for (let stage:number = 1; stage < Math.log2(maxZoom); stage++) { - console.log(`Stage (${cVal * Math.log2(maxZoom) + 1 + stage}/${totalCs}):`); + const retHeightMap: CZIHeightMap[] = [baseCZIHeightMap]; + for (let stage: number = 1; stage < Math.log2(maxZoom); stage++) { + logger.info(`Stage (${cVal * Math.log2(maxZoom) + 1 + stage}/${totalCs}):`); await zoomTier(retHeightMap[stage - 1]) - .then((v: CZIHeightMap) => - { + .then((v: CZIHeightMap) => { retHeightMap.push(v); return; } ); - writeJSONtoFile(`${outputImageData}stageMap-${cVal}-${stage}`, retHeightMap); + writeJSONToFile(`${outputImageData}stageMap-${cVal}-${stage}`, retHeightMap); } - console.log(`>> Completed Extrapolation for dimension, \'C\': ${cVal}\n\n`); + logger.info(`>> Completed Extrapolation for dimension, \'C\': ${cVal}\n\n`); return retHeightMap; -} +}; -/* +/** * function used to ensure that the directories required have been created */ -const checkForOutputDirectories: Function = function(directories: string[]): void -{ - for (const dir of directories) { - if (!fs.existsSync(`${dir}`)) { - fs.mkdirSync(`${dir}`); - } - } +const checkForOutputDirectories: (directories: string[]) => void = ( + directories: string[] +): void => { + for (const dir of directories) { + if (!fs.existsSync(`${dir}`)) { + fs.mkdirSync(`${dir}`); + } + } }; -/* +/** * Write given JSON object to given filepath */ -const writeJSONtoFile: Function = function(filePath:string, object:Object): void -{ - fs.writeFile(filePath, - JSON.stringify(object, null, 2), - (err) => - { +const writeJSONToFile: (filePath: string, obj: object) => void = ( + filePath: string, obj: object +): void => { + fs.writeFile( + filePath, + JSON.stringify(obj, null, 2), + (err: Error) => { if (err) { - console.error(err) + logger.error(err); throw err; } } ); -} +}; -/* +/** * used to write the supported views object to file both in total and "cleaned" */ -const createSupportedViewsObject: Function = function(): void -{ - //parse the xml - parseExtractedXML(`${extractionDirectory}FILE-META-1.xml`); - - //create the total supported Views object - writeJSONtoFile(`${outputImageData}supported_views.json`, supportedViews); - - //cleanup and create "smart" supported views object without whole metadata - cleanSupportedViews(supportedViews); - supportedViews.scalable_image.metadata = {}; - writeJSONtoFile(`${outputImageData}supported_views_minus_xml.json`, supportedViews); -} +const createSupportedViewsObject: () => void = (): void => { + // Parse the xml + parseExtractedXML(`${extractionDirectory}FILE-META-1.xml`); + + // Create the total supported Views object + writeJSONToFile(`${outputImageData}supported_views.json`, supportedViews); + + // Cleanup and create "smart" supported views object without whole metadata + cleanSupportedViews(supportedViews); + supportedViews.scalable_image.metadata = {}; + writeJSONToFile( + `${outputImageData}supported_views_minus_xml.json`, supportedViews); +}; -/* +/** * Used to build up a pyramid for each value of c from the base images */ -const buildCustomPyramids:Function = async function buildCustomPyramids(): Promise -{ - //set some variables for errors and and percent counts - let errorOccurred: Boolean; +const buildCustomPyramids: () => Promise = async(): Promise => { + // Set some variables for errors and and percent counts + let errorOccurred: Boolean; finalCZIJson.zoom_level_count = Math.log2(maxZoom); - finalCZIJson.c_values = [] as any; + finalCZIJson.c_values = []; finalCZIJson.c_value_count = 0; finalCZIJson.total_files = 0; finalCZIJson.complete = false; - //for all channels in the base image + // For all channels in the base image for (const cval of supportedViews.scalable_image.channels) { - errorOccurred = false; - if (!errorOccurred) { - //extract the base tiles and build up custom pyramid data - await extrapolateDimension(Number.parseInt(cval.channel_id, 10), supportedViews.scalable_image.channels.length * Math.log2(maxZoom), maxZoom) - .then((v: CZIHeightMap[]) => - { - // on success, add the new heightmap to the final json data block - finalCZIJson.c_values.push({channel_id: cval.channel_id, height_map: v}); - finalCZIJson.c_value_count++; - return; - } - ).catch((err: Error) => - { - // on error, write the error to console and set an error true. - if (err) { - console.error(err); - } - errorOccurred = true; - } - ); - } - else { - console.error("\nAn error occurred while extracting dimension: " + cval); - console.error("Skipping futher elements and moving to next dimension.\n\n"); - } - //write the final json data to file with most recent changes - writeJSONtoFile(`${outputImageData}layout.json`, finalCZIJson); + errorOccurred = false; + if (!errorOccurred) { + // Extract the base tiles and build up custom pyramid data + await extrapolateDimension( + Number.parseInt(cval.channel_id, 10), + supportedViews.scalable_image.channels.length * Math.log2(maxZoom), + maxZoom + ).then((v: CZIHeightMap[]) => { + // On success, add the new heightmap to the final json data block + // tslint:disable-next-line:no-non-null-assertion + finalCZIJson.c_values!.push({channel_id: cval.channel_id, height_map: v}); + // tslint:disable-next-line:no-non-null-assertion + finalCZIJson.c_value_count!++; + return; + }).catch((err: Error) => { + // On error, write the error to console and set an error true. + if (err) { + logger.error(err); + } + errorOccurred = true; + } + ); + } else { + logger.error(`\nAn error occurred while extracting dimension: ${cval}`); + logger.error('Skipping futher elements and moving to next dimension.\n\n'); + } + // Write the final json data to file with most recent changes + writeJSONToFile(`${outputImageData}layout.json`, finalCZIJson); } finalCZIJson.complete = true; -} +}; +const finalCZIJson: Partial = {}; -let finalCZIJson: WholeCZIHierarchy = {} as any; -/* - * Main function used to call the rest of the relevant code to crunch a CZI extraction. +/** + * Main function used to call the rest of the relevant code to crunch a CZI + * extraction. */ -const main: Function = function() { - console.log("\n"); +const main: () => void = (): void => { + logger.info('\n'); - console.log(">> Checking/Creating output directories...") - checkForOutputDirectories([outputImageData, outputImageDirectory]); + logger.info('>> Checking/Creating output directories...'); + checkForOutputDirectories([outputImageData, outputImageDirectory]); - console.log(">> Creating Supported Views and writing files...") - createSupportedViewsObject(); + logger.info('>> Creating Supported Views and writing files...'); + createSupportedViewsObject(); - console.log(""); - buildCustomPyramids(); -} + logger.info(''); + buildCustomPyramids(); +}; main(); + +/* tslint:disable */ // async function main2() { // // let layout: WholeCZIHierarchy = require(`${outputImageData}layout.json`); // let retHeightMap: any[] = [{}, {}, require(`${outputImageData}stageMap-2.json`)]; -// filecoutner = 5530; +// filecounter = 5530; // // for (let stage:number = 3; stage < Math.sqrt(maxZoom); stage++) { -// console.log(`Stage (${0 * Math.sqrt(maxZoom) + 1 + stage}/${1}):`); +// logger.info(`Stage (${0 * Math.sqrt(maxZoom) + 1 + stage}/${1}):`); // await zoomTier(retHeightMap[stage -1]) // .then((v: CZIHeightMap) => // { // retHeightMap.push(v); -// writeJSONtoFile(`${outputImageData}stageMap-${stage}.json`, v); +// writeJSONToFile(`${outputImageData}stageMap-${stage}.json`, v); // return; // } // ); diff --git a/src/conversion/czi/pyramidWorker.ts b/src/conversion/czi/pyramidWorker.ts index 286fd6b..459f8f9 100644 --- a/src/conversion/czi/pyramidWorker.ts +++ b/src/conversion/czi/pyramidWorker.ts @@ -1,8 +1,8 @@ -import { CZITile, CZIHeightMap, WholeCZIHierarchy } from '../types/customPyramidIndex'; +import { CZIHeightMap, CZITile, WholeCZIHierarchy } from '../types/customPyramidIndex'; +import * as fs from 'fs'; import { TileBounds } from '../types/helperCZITypes'; import * as sharp from 'sharp'; import { SharpInstance } from 'sharp'; -import * as fs from 'fs'; import { isTileRelated, regionToExtract } from './tileExtraction'; const processedDirname: string = '/cs/scratch/cjd24/0701-extraction-processed/'; @@ -13,13 +13,12 @@ const TEMP_REQUESTED_BOUNDS: TileBounds[] = [ new TileBounds(16386, 38000, 15000, 40000), new TileBounds(6000, 15000, 9000, 18000) -] +]; const TEMP_C_VALUE: number = 1, ZOOM_LEVEL: number = 8, TILE_SIZE: number = 1024, TILE_OVERLAP: number = 0; +const findRelatedTiles: Function = function(plane: CZIHeightMap, desired: TileBounds): CZITile[][] { -const findRelatedTiles:Function = function(plane: CZIHeightMap, desired: TileBounds): CZITile[][] { - - let relatedTiles: CZITile[][] = []; + const relatedTiles: CZITile[][] = []; for (const planeTileRow of plane.plane) { let tileRow: CZITile[] = [], foundTiles: boolean = false; for (const tile of planeTileRow) { @@ -34,17 +33,17 @@ const findRelatedTiles:Function = function(plane: CZIHeightMap, desired: TileBou } } return relatedTiles; -} -let help: number = 0; +}; +const help: number = 0; const extractAndStitch: Function = async function(tiles: CZITile[][], desiredRegion: TileBounds, zoom: number): Promise { //create a buffer for the rows part of raw image data - let tileHorizontalBuffer: Buffer[] = [], bufferBound: TileBounds, rowPixelWidth:number = 0, columnPixelHeight: number = 0; + let tileHorizontalBuffer: Buffer[] = [], bufferBound: TileBounds, rowPixelWidth: number = 0, columnPixelHeight: number = 0; //for all rows (y coords) in the image for (const row of tiles) { //create a buffer for this row - let tileRow: Buffer[] = []; + const tileRow: Buffer[] = []; let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); rowPixelWidth = 0; @@ -55,7 +54,7 @@ const extractAndStitch: Function = async function(tiles: CZITile[][], desiredReg rowPixelWidth += (chunkToExtract.right - chunkToExtract.left); //extract this section of image data into a sharp buffer - let data: Promise = + const data: Promise = sharp(`${processedImages}${tile.file}`) .extract({ left: chunkToExtract.left, @@ -75,17 +74,17 @@ const extractAndStitch: Function = async function(tiles: CZITile[][], desiredReg row[0].x_offset, row[0].x_offset + row[0].width, row[0].y_offset, - row[0].y_offset + row[0].height, - ), desiredRegion, zoom); + row[0].y_offset + row[0].height + ), desiredRegion, zoom); //check if the inital chunk needs to be extended to support the other columns if (row.length > 1) { imageVerticalSlice = await imageVerticalSlice.background({r: 0, g: 0, b: 0, alpha: 0}).extend( - {top:0, left:0, bottom:0, right: rowPixelWidth - (bufferBound.right - bufferBound.left)}); + {top: 0, left: 0, bottom: 0, right: rowPixelWidth - (bufferBound.right - bufferBound.left)}); } for (let index = 1; index < row.length; index++) { imageVerticalSlice = sharp(await imageVerticalSlice .overlayWith(tileRow[index], - {top: 0, left: ((bufferBound.right - bufferBound.left) + ((index -1) * TILE_SIZE))}).toBuffer()); + {top: 0, left: ((bufferBound.right - bufferBound.left) + ((index - 1) * TILE_SIZE))}).toBuffer()); } //add this horizontal data buffer to the vertical buffer @@ -100,22 +99,22 @@ const extractAndStitch: Function = async function(tiles: CZITile[][], desiredReg tiles[0][0].x_offset + tiles[0][0].width, tiles[0][0].y_offset, tiles[0][0].y_offset + tiles[0][0].height - ), desiredRegion, zoom); + ), desiredRegion, zoom); //Check if the inital row needs to be extended to support further rows if (tiles.length > 1) { finalImage = await finalImage.background({r: 0, g: 0, b: 0, alpha: 0}).extend( - {top:0, left:0, bottom: (columnPixelHeight - (bufferBound.bottom - bufferBound.top)), right: 0}); + {top: 0, left: 0, bottom: (columnPixelHeight - (bufferBound.bottom - bufferBound.top)), right: 0}); } //For all further rows in the image, combine it with the previous rows' data for (let index = 1; index < tiles.length; index++) { finalImage = sharp(await finalImage.overlayWith( tileHorizontalBuffer[index], - {top: ((bufferBound.bottom - bufferBound.top) + ((index -1) * TILE_SIZE)), left: 0}).toBuffer()); + {top: ((bufferBound.bottom - bufferBound.top) + ((index - 1) * TILE_SIZE)), left: 0}).toBuffer()); } // return the finalised image. - console.log(`Width: ${rowPixelWidth} Height: ${columnPixelHeight}`) - return await finalImage + console.log(`Width: ${rowPixelWidth} Height: ${columnPixelHeight}`); + return finalImage; // .resize( // rowPixelWidth, // columnPixelHeight @@ -123,42 +122,6 @@ const extractAndStitch: Function = async function(tiles: CZITile[][], desiredReg // .crop(sharp.gravity.northwest); }; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const main: Function = function() { if (!layout.complete) { console.error(`The files under: ${processedDirname} have not been finalised yet, please try again later`); @@ -175,5 +138,5 @@ const main: Function = function() { findRelatedTiles(layout.c_values[TEMP_C_VALUE].height_map[Math.log2(ZOOM_LEVEL)], bound), bound, ZOOM_LEVEL ).then((x: SharpInstance) => x.toFile(`${TEMP_OUTPUT_THING}request-${requestCount++}`)); } -} +}; main(); diff --git a/src/conversion/czi/tileExtraction.ts b/src/conversion/czi/tileExtraction.ts index be8bd3c..a768f6e 100644 --- a/src/conversion/czi/tileExtraction.ts +++ b/src/conversion/czi/tileExtraction.ts @@ -1,9 +1,6 @@ -import { CZITile } from '../types/customPyramidIndex'; import { TileBounds } from '../types/helperCZITypes'; -import { SharpInstance } from 'sharp'; -import * as sharp from 'sharp'; -export const isTileRelated:Function = function(origCoords: TileBounds, desired: TileBounds): boolean { +export const isTileRelated: Function = function(origCoords: TileBounds, desired: TileBounds): boolean { if (((desired.left >= origCoords.left) && (desired.left < origCoords.right)) || @@ -14,8 +11,7 @@ export const isTileRelated:Function = function(origCoords: TileBounds, desired: // Desired tile X overlaps base tile ((desired.left < origCoords.left) && - (desired.right > origCoords.right))) - { + (desired.right > origCoords.right))) { // Desired Y on top is within current tile if (((desired.top >= origCoords.top) && @@ -27,8 +23,7 @@ export const isTileRelated:Function = function(origCoords: TileBounds, desired: // Desired tile Y overlaps whole base tile ((desired.top < origCoords.top) && - (desired.bottom > origCoords.bottom))) - { + (desired.bottom > origCoords.bottom))) { //If all of the if statements have passed, then this tile //is part of the overlap for the new tile to be created. @@ -36,8 +31,7 @@ export const isTileRelated:Function = function(origCoords: TileBounds, desired: } } return false; -} - +}; /* * Takes a base tile, and the whole bounds of a new tile, and uses this @@ -47,7 +41,7 @@ export const isTileRelated:Function = function(origCoords: TileBounds, desired: export const regionToExtract: Function = function(baseBounds: TileBounds, desired: TileBounds, zoomLevel: number): TileBounds { //get the base tile area and create an object for the chunk to extract - let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); + const chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); // check if the new tile overlaps the leftmost boundary if (desired.left <= baseBounds.left) { @@ -78,7 +72,7 @@ export const regionToExtract: Function = function(baseBounds: TileBounds, desire } if (chunkToExtract.left < 0 || chunkToExtract.right < 0 || chunkToExtract.top < 0 || chunkToExtract.bottom < 0) { - throw new Error("Chunk to extract from base tile has invalid bound (< 0)."); + throw new Error('Chunk to extract from base tile has invalid bound (< 0).'); } chunkToExtract.left = Math.ceil(chunkToExtract.left / zoomLevel); @@ -90,7 +84,6 @@ export const regionToExtract: Function = function(baseBounds: TileBounds, desire return chunkToExtract; }; - // export const createHorizontalImageSlice: Function = async function (bufferBound: TileBounds, tileSize: number, tileOverlap: number, rowLength:number, row: Buffer[]): Promise { // //prepare variables to squash all of the column data into one, for this row // let imageVerticalSlice: SharpInstance = sharp(row[0]); diff --git a/src/conversion/types/customPyramidIndex.ts b/src/conversion/types/customPyramidIndex.ts index f362372..d209898 100644 --- a/src/conversion/types/customPyramidIndex.ts +++ b/src/conversion/types/customPyramidIndex.ts @@ -1,27 +1,27 @@ //The following are interfaces for the Custom object storing Information //about the CUSTOM pyramid being created for this image - export interface CZITile { - x_offset: number; - y_offset: number; - width: number; - height: number; - file: string; - } +export interface CZITile { + x_offset: number; + y_offset: number; + width: number; + height: number; + file: string; +} - export interface CZIHeightMap { - zoom_level: number, - tile_width_count?: number, - tile_height_count?: number, - plane: CZITile[][]; - } +export interface CZIHeightMap { + zoom_level: number; + tile_width_count?: number; + tile_height_count?: number; + plane: CZITile[][]; +} - export interface WholeCZIHierarchy { - c_values: [{ - channel_id: string, - height_map: CZIHeightMap[]; - }], - c_value_count: number, - zoom_level_count: number; - total_files: number; - complete: boolean; - } +export interface WholeCZIHierarchy { + c_values: { + channel_id: string, + height_map: CZIHeightMap[]; + }[]; + c_value_count: number; + zoom_level_count: number; + total_files: number; + complete: boolean; +} diff --git a/src/conversion/types/helperCZITypes.ts b/src/conversion/types/helperCZITypes.ts index 2d57b15..5403bf3 100644 --- a/src/conversion/types/helperCZITypes.ts +++ b/src/conversion/types/helperCZITypes.ts @@ -1,6 +1,9 @@ -//Interface used to define the structure of the "supportedViews" section -//of the protocol specification for scalable images import { Node } from 'xml-parser'; + +/** + * Interface used to define the structure of the "supportedViews" section + * of the protocol specification for scalable images + */ export interface SupportedViews { scalable_image: { width: number; @@ -21,16 +24,21 @@ export interface SupportedViews { units?: string; }; metadata?: {}; - } + }; } -//Interface used to define the pixel-bounds of a 'section' within the image +// Interface used to define the pixel-bounds of a 'section' within the image export class TileBounds { public left: number; public right: number; public top: number; public bottom: number; - public constructor(leftBound: number, rightBound: number, topBound: number, bottomBound: number) { + public constructor( + leftBound: number, + rightBound: number, + topBound: number, + bottomBound: number + ) { this.left = leftBound; this.right = rightBound; this.top = topBound; -- cgit v1.2.1 From 426befe551d563f7394f67e9053705a2bdd21126 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Thu, 29 Mar 2018 12:47:59 +0100 Subject: Small changes to fix up last type stuff --- src/conversion/czi/czi.ts | 13 ++++++++----- src/conversion/czi/pyramidWorker.ts | 1 + src/conversion/types/helperCZITypes.ts | 11 ++++++----- 3 files changed, 15 insertions(+), 10 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index c2d88ab..5682586 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -3,7 +3,7 @@ import { CZIHeightMap, CZITile, import { Dimension, Segment } from '../types/cziBinaryTypings'; import * as fs from 'fs'; import { SupportedViews, TileBounds } from '../types/helperCZITypes'; -import { logger } from '../../logging'; +import { logger } from '../../logger'; import * as sharp from 'sharp'; // tslint:disable-next-line:no-duplicate-imports import { SharpInstance } from 'sharp'; @@ -351,7 +351,9 @@ const cleanSupportedViews: (view: SupportedViews) => void = ( view: SupportedViews ): void => { for (const channel of view.scalable_image.channels) { - channel.metadata = cleanSupportedViewObject(channel.metadata); + channel.metadata = cleanSupportedViewObject( + channel.metadata as parsexml.Node[] + ); } }; @@ -553,7 +555,8 @@ const zoomTier: ( height: previousHeightMap.plane[ys][xs].height * 2, file: `img-${filecounter++}` }); - finalCZIJson.total_files++; + // tslint:disable-next-line:no-non-null-assertion + finalCZIJson.total_files!++; } newZoomTier.plane.push(cziRow); @@ -695,7 +698,7 @@ const writeJSONToFile: (filePath: string, obj: object) => void = ( JSON.stringify(obj, null, 2), (err: Error) => { if (err) { - logger.error(err); + logger.error(err.message); throw err; } } @@ -750,7 +753,7 @@ const buildCustomPyramids: () => Promise = async(): Promise => { }).catch((err: Error) => { // On error, write the error to console and set an error true. if (err) { - logger.error(err); + logger.error(err.message); } errorOccurred = true; } diff --git a/src/conversion/czi/pyramidWorker.ts b/src/conversion/czi/pyramidWorker.ts index 459f8f9..81110e7 100644 --- a/src/conversion/czi/pyramidWorker.ts +++ b/src/conversion/czi/pyramidWorker.ts @@ -4,6 +4,7 @@ import { TileBounds } from '../types/helperCZITypes'; import * as sharp from 'sharp'; import { SharpInstance } from 'sharp'; import { isTileRelated, regionToExtract } from './tileExtraction'; +import { logger } from '../../logger'; const processedDirname: string = '/cs/scratch/cjd24/0701-extraction-processed/'; const processedImages: string = `${processedDirname}data/`; diff --git a/src/conversion/types/helperCZITypes.ts b/src/conversion/types/helperCZITypes.ts index 5403bf3..51d5d85 100644 --- a/src/conversion/types/helperCZITypes.ts +++ b/src/conversion/types/helperCZITypes.ts @@ -8,13 +8,12 @@ export interface SupportedViews { scalable_image: { width: number; height: number; - channels: [ + channels: { channel_id: string; channel_name: string; - metadata?: Node[]; - } - ]; + metadata?: {}; + }[]; real_width?: { value?: number; units?: string; @@ -27,7 +26,9 @@ export interface SupportedViews { }; } -// Interface used to define the pixel-bounds of a 'section' within the image +/** + * Interface used to define the pixel-bounds of a 'section' within the image + */ export class TileBounds { public left: number; public right: number; -- cgit v1.2.1 From 709d6ec75364a51498139ed37f40b297e5fc9766 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Sun, 1 Apr 2018 19:05:00 +0100 Subject: first working iteration of final tile extraction --- src/conversion/czi/czi.ts | 2 +- src/conversion/czi/pyramidWorker.ts | 167 +++++++++-------------------- src/conversion/czi/tileDims.png | Bin 0 -> 292647 bytes src/conversion/types/customPyramidIndex.ts | 10 ++ src/conversion/types/helperCZITypes.ts | 18 ++++ 5 files changed, 79 insertions(+), 118 deletions(-) create mode 100644 src/conversion/czi/tileDims.png (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index 5682586..e6a4220 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -778,7 +778,7 @@ const main: () => void = (): void => { logger.info('\n'); logger.info('>> Checking/Creating output directories...'); - checkForOutputDirectories([outputImageData, outputImageDirectory]); + checkForOutputDirectories([outputImageData, outputImageDirectory, `${outputImageData}tmp/`]); logger.info('>> Creating Supported Views and writing files...'); createSupportedViewsObject(); diff --git a/src/conversion/czi/pyramidWorker.ts b/src/conversion/czi/pyramidWorker.ts index 81110e7..aea7936 100644 --- a/src/conversion/czi/pyramidWorker.ts +++ b/src/conversion/czi/pyramidWorker.ts @@ -1,30 +1,26 @@ -import { CZIHeightMap, CZITile, WholeCZIHierarchy } from '../types/customPyramidIndex'; -import * as fs from 'fs'; +import { CZIHeightMap, CZITile, CZITileRequest } from '../types/customPyramidIndex'; import { TileBounds } from '../types/helperCZITypes'; import * as sharp from 'sharp'; -import { SharpInstance } from 'sharp'; -import { isTileRelated, regionToExtract } from './tileExtraction'; -import { logger } from '../../logger'; - -const processedDirname: string = '/cs/scratch/cjd24/0701-extraction-processed/'; -const processedImages: string = `${processedDirname}data/`; -const layout: WholeCZIHierarchy = require(`${processedDirname}layout.json`); -const TEMP_OUTPUT_THING: string = `${processedDirname}finalisedTiles/`; -const TEMP_REQUESTED_BOUNDS: TileBounds[] = -[ - new TileBounds(16386, 38000, 15000, 40000), - new TileBounds(6000, 15000, 9000, 18000) -]; -const TEMP_C_VALUE: number = 1, ZOOM_LEVEL: number = 8, TILE_SIZE: number = 1024, TILE_OVERLAP: number = 0; +import { isTileRelated } from './tileExtraction'; +import { uuid } from '../../uuid' const findRelatedTiles: Function = function(plane: CZIHeightMap, desired: TileBounds): CZITile[][] { const relatedTiles: CZITile[][] = []; for (const planeTileRow of plane.plane) { - let tileRow: CZITile[] = [], foundTiles: boolean = false; + let tileRow: CZITile[] = []; + let foundTiles: boolean = false; + for (const tile of planeTileRow) { - if (isTileRelated(new TileBounds(tile.x_offset, tile.x_offset + tile.width, tile.y_offset, tile.y_offset + tile.height), desired)) { + if (isTileRelated( + new TileBounds( + tile.x_offset, + tile.x_offset + tile.width, + tile.y_offset, + tile.y_offset + tile.height + ), desired) + ) { tileRow.push(tile); foundTiles = true; } @@ -35,109 +31,46 @@ const findRelatedTiles: Function = function(plane: CZIHeightMap, desired: TileBo } return relatedTiles; }; -const help: number = 0; -const extractAndStitch: Function = async function(tiles: CZITile[][], desiredRegion: TileBounds, zoom: number): Promise { - //create a buffer for the rows part of raw image data - let tileHorizontalBuffer: Buffer[] = [], bufferBound: TileBounds, rowPixelWidth: number = 0, columnPixelHeight: number = 0; +const getFinalTile: Function = async function(imageDir: string, imageTier: CZIHeightMap, cVal: string, desiredRegion: TileBounds): Promise { - //for all rows (y coords) in the image - for (const row of tiles) { - //create a buffer for this row - const tileRow: Buffer[] = []; - let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); - rowPixelWidth = 0; + console.error("Has the calling function checked that the image has completed processing in WholeCZIHierarchy??"); - //For all of the columns within this row + let involvedTiles: string = ''; + for (const row of imageTier.plane) { for (const tile of row) { - //find out the region of the base tile to be added to the new image - chunkToExtract = regionToExtract(new TileBounds(tile.x_offset, tile.x_offset + tile.width, tile.y_offset, tile.y_offset + tile.height), desiredRegion, zoom); - rowPixelWidth += (chunkToExtract.right - chunkToExtract.left); - - //extract this section of image data into a sharp buffer - const data: Promise = - sharp(`${processedImages}${tile.file}`) - .extract({ - left: chunkToExtract.left, - top: chunkToExtract.top, - width: chunkToExtract.right - chunkToExtract.left, - height: chunkToExtract.bottom - chunkToExtract.top - }) - .toBuffer(); - - //push this data into the row buffer - tileRow.push(await data); - } - - //prepare variables to squash all of the column data into one, for this row - let imageVerticalSlice: SharpInstance = sharp(tileRow[0]); - bufferBound = regionToExtract(new TileBounds( - row[0].x_offset, - row[0].x_offset + row[0].width, - row[0].y_offset, - row[0].y_offset + row[0].height - ), desiredRegion, zoom); - //check if the inital chunk needs to be extended to support the other columns - if (row.length > 1) { - imageVerticalSlice = await imageVerticalSlice.background({r: 0, g: 0, b: 0, alpha: 0}).extend( - {top: 0, left: 0, bottom: 0, right: rowPixelWidth - (bufferBound.right - bufferBound.left)}); - } - for (let index = 1; index < row.length; index++) { - imageVerticalSlice = sharp(await imageVerticalSlice - .overlayWith(tileRow[index], - {top: 0, left: ((bufferBound.right - bufferBound.left) + ((index - 1) * TILE_SIZE))}).toBuffer()); + involvedTiles += `${imageDir}${tile.file} ` } - - //add this horizontal data buffer to the vertical buffer - tileHorizontalBuffer.push(await imageVerticalSlice.toBuffer()); - columnPixelHeight += bufferBound.bottom - bufferBound.top; } - // prepare variables used to combine all rows into one image - let finalImage: SharpInstance = sharp(tileHorizontalBuffer[0]); - bufferBound = regionToExtract(new TileBounds( - tiles[0][0].x_offset, - tiles[0][0].x_offset + tiles[0][0].width, - tiles[0][0].y_offset, - tiles[0][0].y_offset + tiles[0][0].height - ), desiredRegion, zoom); - //Check if the inital row needs to be extended to support further rows - if (tiles.length > 1) { - finalImage = await finalImage.background({r: 0, g: 0, b: 0, alpha: 0}).extend( - {top: 0, left: 0, bottom: (columnPixelHeight - (bufferBound.bottom - bufferBound.top)), right: 0}); - } - //For all further rows in the image, combine it with the previous rows' data - for (let index = 1; index < tiles.length; index++) { - finalImage = sharp(await finalImage.overlayWith( - tileHorizontalBuffer[index], - {top: ((bufferBound.bottom - bufferBound.top) + ((index - 1) * TILE_SIZE)), left: 0}).toBuffer()); - } - - // return the finalised image. - console.log(`Width: ${rowPixelWidth} Height: ${columnPixelHeight}`); - return finalImage; - // .resize( - // rowPixelWidth, - // columnPixelHeight - // ) - // .crop(sharp.gravity.northwest); -}; - -const main: Function = function() { - if (!layout.complete) { - console.error(`The files under: ${processedDirname} have not been finalised yet, please try again later`); - return; - } - - if (!fs.existsSync(`${TEMP_OUTPUT_THING}`)) { - fs.mkdirSync(`${TEMP_OUTPUT_THING}`); - } - - let requestCount: number = 0; - for (const bound of TEMP_REQUESTED_BOUNDS) { - extractAndStitch( - findRelatedTiles(layout.c_values[TEMP_C_VALUE].height_map[Math.log2(ZOOM_LEVEL)], bound), bound, ZOOM_LEVEL - ).then((x: SharpInstance) => x.toFile(`${TEMP_OUTPUT_THING}request-${requestCount++}`)); - } -}; -main(); + let outputFileName: string =`${imageDir}/tmp/${uuid.generate()}.png` + require('shelljs').exec(`./vips arrayjoin "${involvedTiles}" ${outputFileName} --across ${imageTier.plane[0].length}`) + + let extractionRegion = new TileBounds( + desiredRegion.left - imageTier.plane[0][0].width, + desiredRegion.right - imageTier.plane[0][0].width, + desiredRegion.top - imageTier.plane[0][0].height, + desiredRegion.bottom - imageTier.plane[0][0].height + ); + extractionRegion.scaleDown(imageTier.zoom_level); + + await sharp(outputFileName) + .extract({ + top: extractionRegion.top, + left: extractionRegion.left, + width: extractionRegion.width(), + height: extractionRegion.height() + }) + .toFile(outputFileName); + + return { + dimensions: new TileBounds( + 0, extractionRegion.width(), + 0, extractionRegion.height() + ), + original_bounds: desiredRegion, + zoom_level: imageTier.zoom_level, + c_value: cVal, + file_path: outputFileName + }; +} diff --git a/src/conversion/czi/tileDims.png b/src/conversion/czi/tileDims.png new file mode 100644 index 0000000..70e2484 Binary files /dev/null and b/src/conversion/czi/tileDims.png differ diff --git a/src/conversion/types/customPyramidIndex.ts b/src/conversion/types/customPyramidIndex.ts index d209898..9a3c8c3 100644 --- a/src/conversion/types/customPyramidIndex.ts +++ b/src/conversion/types/customPyramidIndex.ts @@ -1,3 +1,5 @@ +import { TileBounds } from './helperCZITypes' + //The following are interfaces for the Custom object storing Information //about the CUSTOM pyramid being created for this image export interface CZITile { @@ -25,3 +27,11 @@ export interface WholeCZIHierarchy { total_files: number; complete: boolean; } + +export interface CZITileRequest { + dimensions: TileBounds, + original_bounds: TileBounds, + zoom_level: number, + c_value: string, + file_path: string +} diff --git a/src/conversion/types/helperCZITypes.ts b/src/conversion/types/helperCZITypes.ts index 51d5d85..8f6310a 100644 --- a/src/conversion/types/helperCZITypes.ts +++ b/src/conversion/types/helperCZITypes.ts @@ -45,4 +45,22 @@ export class TileBounds { this.top = topBound; this.bottom = bottomBound; } + public width(): number { + return this.right - this.left; + } + public height(): number { + return this.bottom - this.top; + } + public scaleDown(level: number) { + this.left = Math.ceil(this.left / level), + this.right = Math.ceil(this.right / level), + this.top = Math.ceil(this.top / level), + this.bottom = Math.ceil(this.bottom / level) + } + public scaleUp(level: number) { + this.left = Math.floor(this.left * level), + this.right = Math.ceil(this.right * level), + this.top = Math.ceil(this.top * level), + this.bottom = Math.ceil(this.bottom * level) + } } -- cgit v1.2.1 From 740536ef8a9d3622180aa81c167a25e3c419fd26 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Sun, 1 Apr 2018 21:42:18 +0100 Subject: Swapped over the zoom tier section to use vips directly --- src/conversion/czi/czi.ts | 85 +++++++++++++----------------- src/conversion/czi/pyramidWorker.ts | 2 +- src/conversion/types/customPyramidIndex.ts | 8 +-- 3 files changed, 41 insertions(+), 54 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index e6a4220..c0a56f1 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -9,6 +9,7 @@ import * as sharp from 'sharp'; import { SharpInstance } from 'sharp'; import { isTileRelated, regionToExtract } from './tileExtraction'; import * as parsexml from 'xml-parser'; +import { uuid } from '../../uuid' // Various constants for placing files and defining tiles const baseDirname: string = '/cs/scratch/cjd24/0701-extraction'; @@ -18,6 +19,7 @@ const outputImageDirectory: string = `${baseDirname}-processed/data/`; const tileOverlap: number = 0; // Overlap is only half implemented const tileSize: number = 1024; const maxZoom: number = 64; +const shell = require('shelljs'); /** * Simple function to find the tile bounds version of an original tile @@ -505,48 +507,34 @@ const zoomTier: ( for (let xs: number = 0; xs < previousHeightMap.plane[0].length; xs += 2) { // Combine 4 tiles into a new tile and scale down for this tier - let combinedTile: SharpInstance; // Top left - combinedTile = await sharp( - `${outputImageDirectory}${previousHeightMap.plane[ys][xs].file}` - ).background({ - r: 0, - g: 0, - b: 0, - alpha: 0 - }).extend({ - top: 0, - left: 0, - bottom: tileSize, - right: tileSize - }); + let quadrents:string = `${outputImageDirectory}${previousHeightMap.plane[ys][xs].file} `; + let across:number = 1; // Combine top right const moreToRight: boolean = (xs + 1) < previousHeightMap.plane[0].length; if (moreToRight) { - combinedTile = sharp(await combinedTile.overlayWith( - `${outputImageDirectory}${previousHeightMap.plane[ys][xs + 1].file}`, - {top: 0, left: tileSize}).toBuffer()); + quadrents += `${outputImageDirectory}${previousHeightMap.plane[ys][xs + 1].file} `; + across++; } - // Combine bottom left const moreToBottom: boolean = (ys + 1) < previousHeightMap.plane.length; if (moreToBottom) { - combinedTile = sharp(await combinedTile.overlayWith( - `${outputImageDirectory}${previousHeightMap.plane[ys + 1][xs].file}`, - {top: tileSize, left: 0}).toBuffer()); + quadrents += `${outputImageDirectory}${previousHeightMap.plane[ys + 1][xs].file} `; } - // Combine bottom right if (moreToBottom && moreToRight) { - combinedTile = sharp(await combinedTile.overlayWith( - `${outputImageDirectory}${previousHeightMap.plane[ys + 1][xs + 1].file}`, - {top: tileSize, left: tileSize}).toBuffer()); + quadrents += `${outputImageDirectory}${previousHeightMap.plane[ys + 1][xs + 1].file} `; } + let outputFileName: string =`${outputImageData}/tmp/${uuid.generate()}.png` + shell.exec(`./vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`) + // Rescale and push to file - await combinedTile.resize(tileSize, tileSize) + await sharp(outputFileName) + .resize(tileSize, tileSize) .toFile(`${outputImageDirectory}img-${filecounter}`); + shell.rm(outputFileName); cziRow.push({ x_offset: previousHeightMap.plane[ys][xs].x_offset, @@ -556,7 +544,7 @@ const zoomTier: ( file: `img-${filecounter++}` }); // tslint:disable-next-line:no-non-null-assertion - finalCZIJson.total_files!++; + finalCZIJson.total_files++; } newZoomTier.plane.push(cziRow); @@ -690,20 +678,19 @@ const checkForOutputDirectories: (directories: string[]) => void = ( /** * Write given JSON object to given filepath */ -const writeJSONToFile: (filePath: string, obj: object) => void = ( - filePath: string, obj: object -): void => { - fs.writeFile( - filePath, - JSON.stringify(obj, null, 2), - (err: Error) => { - if (err) { - logger.error(err.message); - throw err; +const writeJSONToFile: (filePath: string, obj: object) => + void = (filePath: string, obj: object): void => { + fs.writeFile( + filePath, + JSON.stringify(obj, null, 2), + (err: Error) => { + if (err) { + logger.error(err.message); + throw err; + } } - } - ); -}; + ); + }; /** * used to write the supported views object to file both in total and "cleaned" @@ -729,10 +716,6 @@ const buildCustomPyramids: () => Promise = async(): Promise => { // Set some variables for errors and and percent counts let errorOccurred: Boolean; finalCZIJson.zoom_level_count = Math.log2(maxZoom); - finalCZIJson.c_values = []; - finalCZIJson.c_value_count = 0; - finalCZIJson.total_files = 0; - finalCZIJson.complete = false; // For all channels in the base image for (const cval of supportedViews.scalable_image.channels) { @@ -745,10 +728,8 @@ const buildCustomPyramids: () => Promise = async(): Promise => { maxZoom ).then((v: CZIHeightMap[]) => { // On success, add the new heightmap to the final json data block - // tslint:disable-next-line:no-non-null-assertion - finalCZIJson.c_values!.push({channel_id: cval.channel_id, height_map: v}); - // tslint:disable-next-line:no-non-null-assertion - finalCZIJson.c_value_count!++; + finalCZIJson.c_values.push({channel_id: cval.channel_id, height_map: v}); + finalCZIJson.c_value_count++; return; }).catch((err: Error) => { // On error, write the error to console and set an error true. @@ -768,7 +749,13 @@ const buildCustomPyramids: () => Promise = async(): Promise => { finalCZIJson.complete = true; }; -const finalCZIJson: Partial = {}; +const finalCZIJson: WholeCZIHierarchy = { + c_value_count: 0, + total_files: 0, + complete: false, + c_values: [], + zoom_level_count: 0 +}; /** * Main function used to call the rest of the relevant code to crunch a CZI diff --git a/src/conversion/czi/pyramidWorker.ts b/src/conversion/czi/pyramidWorker.ts index aea7936..fdaa038 100644 --- a/src/conversion/czi/pyramidWorker.ts +++ b/src/conversion/czi/pyramidWorker.ts @@ -39,7 +39,7 @@ const getFinalTile: Function = async function(imageDir: string, imageTier: CZIHe let involvedTiles: string = ''; for (const row of imageTier.plane) { for (const tile of row) { - involvedTiles += `${imageDir}${tile.file} ` + involvedTiles += `${imageDir}/data/${tile.file} ` } } diff --git a/src/conversion/types/customPyramidIndex.ts b/src/conversion/types/customPyramidIndex.ts index 9a3c8c3..68df252 100644 --- a/src/conversion/types/customPyramidIndex.ts +++ b/src/conversion/types/customPyramidIndex.ts @@ -18,14 +18,14 @@ export interface CZIHeightMap { } export interface WholeCZIHierarchy { - c_values: { - channel_id: string, - height_map: CZIHeightMap[]; - }[]; c_value_count: number; zoom_level_count: number; total_files: number; complete: boolean; + c_values: { + channel_id: string, + height_map: CZIHeightMap[]; + }[]; } export interface CZITileRequest { -- cgit v1.2.1 From 139b0299d016f8dab6738333c767a3add47bfc14 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Mon, 2 Apr 2018 04:37:05 +0100 Subject: Working on converting to Vips, didnt commit czi in this one as is sadly broken --- src/conversion/czi/convertJxrs.py | 15 ++++++++++----- src/conversion/czi/pyramidWorker.ts | 2 +- 2 files changed, 11 insertions(+), 6 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/convertJxrs.py b/src/conversion/czi/convertJxrs.py index d19a59a..2ba81b3 100644 --- a/src/conversion/czi/convertJxrs.py +++ b/src/conversion/czi/convertJxrs.py @@ -10,11 +10,16 @@ coutner = 0 def convertjxrs(filename): global counter global totalFiles - asTif = filename.rsplit('.',1)[0] + ".tif" - check_call(['./JxrDecApp', "-i", filename, "-o", asTif]) - check_call(['convert', asTif, filename.rsplit('.',1)[0] + ".png"]) - check_call(['rm', filename, asTif]) - counter += 1 + try: + asTif = filename.rsplit('.',1)[0] + ".tif" + check_call(['JxrDecApp', "-i", filename, "-o", asTif]) + check_call(['convert', asTif, filename.rsplit('.',1)[0] + ".png"]) + check_call(['rm', filename, asTif]) + counter += 1 + except: + print ("Processing Failed. Probably couldn't find decoder due to invalid system environment path, check this before debugging.") + exit(0); + print (f"> Processed File: {counter}/{totalFiles} : {filename} --> {filename.rsplit('.',1)[0]}.png") diff --git a/src/conversion/czi/pyramidWorker.ts b/src/conversion/czi/pyramidWorker.ts index fdaa038..19acbf9 100644 --- a/src/conversion/czi/pyramidWorker.ts +++ b/src/conversion/czi/pyramidWorker.ts @@ -44,7 +44,7 @@ const getFinalTile: Function = async function(imageDir: string, imageTier: CZIHe } let outputFileName: string =`${imageDir}/tmp/${uuid.generate()}.png` - require('shelljs').exec(`./vips arrayjoin "${involvedTiles}" ${outputFileName} --across ${imageTier.plane[0].length}`) + require('shelljs').exec(`vips arrayjoin "${involvedTiles}" ${outputFileName} --across ${imageTier.plane[0].length}`) let extractionRegion = new TileBounds( desiredRegion.left - imageTier.plane[0][0].width, -- cgit v1.2.1 From 8011117937a46075f834724510a8515b84509c7b Mon Sep 17 00:00:00 2001 From: cjd24 Date: Mon, 2 Apr 2018 04:38:13 +0100 Subject: FAILING COMMIT, this is just for backups - the current stage im at with converting czi.ts to use vips directly instead of sharp for converting and stitching :( --- src/conversion/czi/czi.ts | 245 ++++++++++++++++++++++------------------------ 1 file changed, 119 insertions(+), 126 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index c0a56f1..73c0577 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -3,7 +3,7 @@ import { CZIHeightMap, CZITile, import { Dimension, Segment } from '../types/cziBinaryTypings'; import * as fs from 'fs'; import { SupportedViews, TileBounds } from '../types/helperCZITypes'; -import { logger } from '../../logger'; +// import { logger } from '../../logger'; import * as sharp from 'sharp'; // tslint:disable-next-line:no-duplicate-imports import { SharpInstance } from 'sharp'; @@ -188,91 +188,88 @@ const findRegionToExtract: ( * into a new image */ const extractAndStitchChunks: ( - segments: Segment[][], desiredRegion: TileBounds -) => Promise = async( - segments: Segment[][], desiredRegion: TileBounds -): Promise => { - // Create a buffer for the rows part of raw image data - const tileVerticalBuffer: Buffer[] = []; - - // For all ros (y coords) in the image - for (const segRow of segments) { - // Create a buffer for this row - const tileRow: Buffer[] = []; - let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); + segments: Segment[][], desiredRegion: TileBounds, fileCount: number +) => Promise = async ( + segments: Segment[][], desiredRegion: TileBounds, fileCount: number +): Promise => { - // For all of the columns within this row + let involvedTiles: string = ''; + // For all rows (y coords) in the image + for (const segRow of segments) { for (const segCol of segRow) { - // Find out the region of the base tile to be added to the new image - chunkToExtract = findRegionToExtract(segCol, desiredRegion); - // Extract this section of image data into a sharp buffer - const data: Promise = - sharp(`${extractionDirectory}${segCol.Data.Data}`) + involvedTiles += `${extractionDirectory}${segCol.Data.Data} `; + } + } + + let originalRegion: TileBounds = new TileBounds( + getDimension(segments[0][0], 'X').Start, + getDimension(segments[0][0], 'X').Start + getDimension(segments[0][0], 'X').Size, + getDimension(segments[0][0], 'Y').Start, + getDimension(segments[0][0], 'Y').Start + getDimension(segments[0][0], 'Y').Size + ) + let finalImage: SharpInstance; + + try{ + let outputFileName: string = ''; + if (segments[0].length !== 1 || segments.length !== 1) { + outputFileName = `${outputImageDirectory}${uuid.generate()}.png` + shell.exec(`vips arrayjoin "${involvedTiles}" ${outputFileName} --across ${segments[0].length}`) + + finalImage = sharp(outputFileName) .extract({ - left: chunkToExtract.left, - top: chunkToExtract.top, - width: chunkToExtract.right - chunkToExtract.left, - height: chunkToExtract.bottom - chunkToExtract.top + top: desiredRegion.top - getDimension(segments[0][0], 'Y').Start, + left: desiredRegion.left - getDimension(segments[0][0], 'X').Start, + width: desiredRegion.width(), + height: desiredRegion.height() }) - .toBuffer(); - // Push this data into the row buffer - tileRow.push(await data); + } else { + desiredRegion = regionToExtract( + new TileBounds( + getDimension(segments[0][0], 'X').Start, + getDimension(segments[0][0], 'X').Start + getDimension(segments[0][0], 'X').Size, + getDimension(segments[0][0], 'Y').Start, + getDimension(segments[0][0], 'Y').Start + getDimension(segments[0][0], 'Y').Size + ), + desiredRegion, + 1 + ); + finalImage = sharp(`${extractionDirectory}${segments[0][0].Data.Data}`) + .extract({ + top: desiredRegion.top, + left: desiredRegion.left, + width: desiredRegion.width(), + height: desiredRegion.height() + }); } - // Prepare variables to squash all of the column data into one, for this row - let imageVerticalSlice: SharpInstance = sharp(tileRow[0]); - const bufferBound: TileBounds = findRegionToExtract(segRow[0], desiredRegion); - // Check if the inital chunk needs to be extended to support the other columns - if ((bufferBound.right - bufferBound.left) < (tileSize - tileOverlap)) { - imageVerticalSlice = await imageVerticalSlice.extend({ - top: 0, - left: 0, - bottom: 0, - right: (tileSize - (bufferBound.right - bufferBound.left)) - }); - } - // For every column along this row, join it to the previous column data - for (let index: number = 1; index < segRow.length; index++) { - imageVerticalSlice = await imageVerticalSlice - .overlayWith(tileRow[index], { + if (desiredRegion.width() < tileSize || desiredRegion.height() < tileSize) { + finalImage + .background({ + r: 0, g: 0, b: 0, alpha: 0}) + .extend({ + left: 0, + right: tileSize - desiredRegion.width(), top: 0, - left: (bufferBound.right - bufferBound.left) - + ((index - 1) * tileSize) + bottom: tileSize - desiredRegion.height() }); + } else { + finalImage.background({ + r: 0, g: 0, b: 0, alpha: 0}) } - // Add this horizontal data buffer to the vertical buffer - tileVerticalBuffer.push(await imageVerticalSlice.toBuffer()); - } - - // Prepare variables used to combine all rows into one image - let finalImage: SharpInstance = sharp(tileVerticalBuffer[0]); - const bufferBound: TileBounds = - findRegionToExtract(segments[0][0], desiredRegion); - // Check if the inital row needs to be extended to support further rows - if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) { - finalImage = await finalImage.background({ - r: 0, - g: 0, - b: 0, - alpha: 0 - }).extend({ - top: 0, - left: 0, - bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), - right: 0 - }); - } - // For all further rows in the image, combine it with the previous rows' data - for (let index: number = 1; index < segments.length; index++) { - finalImage = finalImage.overlayWith( - tileVerticalBuffer[index], - {top: getDimension(segments[index - 1][0], 'Y').Size, left: 0}); + await finalImage.toFile(`${outputImageDirectory}img-${fileCount}.png`); + if (segments[0].length !== 1 || segments.length !== 1) { + shell.rm(outputFileName); + } + } catch (error) { + console.log(); + console.log(error); + console.log(desiredRegion) + console.log(involvedTiles) + console.log(desiredRegion.top - getDimension(segments[0][0], 'Y').Start, desiredRegion.left - getDimension(segments[0][0], 'X').Start, desiredRegion.width(), desiredRegion.height()) + throw new Error("SAD BOI ERROR>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); } - - // Return the finalised image. - return finalImage; }; /** @@ -364,9 +361,11 @@ const cleanSupportedViews: (view: SupportedViews) => void = ( * of the initial extraction. */ // tslint:disable-next-line:no-var-requires -const dataBlocks: Segment[] = require(`${extractionDirectory}outputjson.json`) - .czi.filter( - (s: Segment) => s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty'); +const dataBlocks: Segment[] = + require(`${extractionDirectory}outputjson.json`) + .czi.filter((s: Segment) => + s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty' + ); let totalSizeX: number = -1; let totalSizeY: number = -1; @@ -491,7 +490,7 @@ const zoomTier: ( // Check the condition where another zoom level does not make sense if (previousHeightMap.plane.length === 1 && previousHeightMap.plane[0].length === 1) { - logger.info( + console.log( ' Task(1/1): ' + 'Stage 100% complete. ' + '(0 sec/iter) Stage was skipped as maximum sensible zoom level was reached.' @@ -527,13 +526,13 @@ const zoomTier: ( quadrents += `${outputImageDirectory}${previousHeightMap.plane[ys + 1][xs + 1].file} `; } - let outputFileName: string =`${outputImageData}/tmp/${uuid.generate()}.png` - shell.exec(`./vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`) + let outputFileName: string =`${outputImageData}tmp/${uuid.generate()}.png` + shell.exec(`vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`) // Rescale and push to file await sharp(outputFileName) .resize(tileSize, tileSize) - .toFile(`${outputImageDirectory}img-${filecounter}`); + .toFile(`${outputImageDirectory}img-${filecounter}.png`); shell.rm(outputFileName); cziRow.push({ @@ -541,19 +540,18 @@ const zoomTier: ( y_offset: previousHeightMap.plane[ys][xs].y_offset, width: previousHeightMap.plane[ys][xs].width * 2, height: previousHeightMap.plane[ys][xs].height * 2, - file: `img-${filecounter++}` + file: `img-${filecounter++}.png` }); - // tslint:disable-next-line:no-non-null-assertion finalCZIJson.total_files++; } newZoomTier.plane.push(cziRow); timing = process.hrtime(timing); - iterTimes.push(timing[0]); + iterTimes.push(timing[0] * 2); if (iterTimes.length > 5) { iterTimes.shift(); } // tslint:disable-next-line:typedef avgItrTime = iterTimes.reduce((p, c, i) => p + (c - p) / (i + 1), 0); - logger.info( + console.log( ` Task(${ys / 2 + 1}/${ Math.floor(previousHeightMap.plane.length / 2) + 1}): ` + `Stage ${Math.ceil(((ys / previousHeightMap.plane.length) @@ -587,19 +585,18 @@ const extrapolateDimension: ( getDimension(item, 'C').Start === cVal ); // Begin output for the base tier - logger.info('========================================================='); - logger.info(`>> Beginning Dimension Extrapolation for \'C\' : ${cVal}`); - logger.info('========================================================='); - logger.info('>> Computing base tier, this will take a while...\n'); + console.log('========================================================='); + console.log(`>> Beginning Dimension Extrapolation for \'C\' : ${cVal}`); + console.log('========================================================='); + console.log('>> Computing base tier, this will take a while...\n'); const baseCZIHeightMap: CZIHeightMap = {zoom_level: 1, plane: []}; - let width_in_tiles = 0; - let height_in_tiles = 0; - logger.info(`Stage (${cVal * Math.log2(maxZoom) + 1}/${totalCs}):`); + console.log(`Stage (${cVal * Math.log2(maxZoom) + 1}/${totalCs}):`); // For all rows within the total base pixel height for (; ys < totalSizeY;) { timing = process.hrtime(); const cziRow: CZITile[] = []; + process.stdout.write(`${Math.ceil(totalSizeX/tileSize)} : `); for (let xs: number = 0; xs < totalSizeX; xs += tileSize) { const desired: TileBounds = new TileBounds( xs - tileOverlap, @@ -613,42 +610,41 @@ const extrapolateDimension: ( y_offset: ys, width: tileSize, height: tileSize, - file: `img-${filecounter}` + file: `img-${filecounter}.png` }); const sortedSegments: Segment[][] = orderSegments(findRelatedTiles(filteredDataBlocks, desired)); - (await extractAndStitchChunks(sortedSegments, desired)) - .toFile(`${outputImageDirectory}img-${filecounter++}`); - // tslint:disable-next-line:no-non-null-assertion - finalCZIJson.total_files!++; - width_in_tiles = xs / tileSize; + + await extractAndStitchChunks(sortedSegments, desired, filecounter++); + process.stdout.write(">"); + finalCZIJson.total_files++; } baseCZIHeightMap.plane.push(cziRow); ys += tileSize; timing = process.hrtime(timing); - iterTimes.push(timing[0]); + iterTimes.push(timing[0] * 2); if (iterTimes.length > 5) { iterTimes.shift(); } // tslint:disable-next-line:typedef avgItrTime = iterTimes.reduce((p, c, i) => p + (c - p) / (i + 1), 0); - logger.info( + process.stdout.write("\r"); + console.log( ` Task(${ys / tileSize}/${Math.ceil(totalSizeY / tileSize)}): ` + `Stage ${Math.ceil(((ys / totalSizeY) * 100) * 100) / 100}% complete. ` + `(${timing[0]} sec/iter, est: ${((avgItrTime * (Math.ceil(totalSizeY / tileSize) - ys / tileSize)) / 60).toFixed(2)} mins remain.)` ); - height_in_tiles = ys / tileSize; } - baseCZIHeightMap.tile_height_count = height_in_tiles; - baseCZIHeightMap.tile_width_count = width_in_tiles; + baseCZIHeightMap.tile_height_count = baseCZIHeightMap.plane.length; + baseCZIHeightMap.tile_width_count = baseCZIHeightMap.plane[0].length; // BUILD UP THE HIGHER ZOOM LAYERS. - logger.info(`>> Base tier complete for \'C\': ${cVal + console.log(`>> Base tier complete for \'C\': ${cVal }; Begin computing zoom tiers...\n`); const retHeightMap: CZIHeightMap[] = [baseCZIHeightMap]; for (let stage: number = 1; stage < Math.log2(maxZoom); stage++) { - logger.info(`Stage (${cVal * Math.log2(maxZoom) + 1 + stage}/${totalCs}):`); + console.log(`Stage (${cVal * Math.log2(maxZoom) + 1 + stage}/${totalCs}):`); await zoomTier(retHeightMap[stage - 1]) .then((v: CZIHeightMap) => { retHeightMap.push(v); @@ -658,7 +654,7 @@ const extrapolateDimension: ( writeJSONToFile(`${outputImageData}stageMap-${cVal}-${stage}`, retHeightMap); } - logger.info(`>> Completed Extrapolation for dimension, \'C\': ${cVal}\n\n`); + console.log(`>> Completed Extrapolation for dimension, \'C\': ${cVal}\n\n`); return retHeightMap; }; @@ -685,7 +681,7 @@ const writeJSONToFile: (filePath: string, obj: object) => JSON.stringify(obj, null, 2), (err: Error) => { if (err) { - logger.error(err.message); + console.error(err.message); throw err; } } @@ -734,14 +730,14 @@ const buildCustomPyramids: () => Promise = async(): Promise => { }).catch((err: Error) => { // On error, write the error to console and set an error true. if (err) { - logger.error(err.message); + console.error(err.message); } errorOccurred = true; } ); } else { - logger.error(`\nAn error occurred while extracting dimension: ${cval}`); - logger.error('Skipping futher elements and moving to next dimension.\n\n'); + console.error(`\nAn error occurred while extracting dimension: ${cval}`); + console.error('Skipping futher elements and moving to next dimension.\n\n'); } // Write the final json data to file with most recent changes writeJSONToFile(`${outputImageData}layout.json`, finalCZIJson); @@ -762,36 +758,33 @@ const finalCZIJson: WholeCZIHierarchy = { * extraction. */ const main: () => void = (): void => { - logger.info('\n'); + console.log('\n'); - logger.info('>> Checking/Creating output directories...'); + console.log('>> Checking/Creating output directories...'); checkForOutputDirectories([outputImageData, outputImageDirectory, `${outputImageData}tmp/`]); - logger.info('>> Creating Supported Views and writing files...'); + console.log('>> Creating Supported Views and writing files...'); createSupportedViewsObject(); - logger.info(''); + console.log(''); buildCustomPyramids(); }; main(); -/* tslint:disable */ +// /* tslint:disable */ // async function main2() { // // let layout: WholeCZIHierarchy = require(`${outputImageData}layout.json`); -// let retHeightMap: any[] = [{}, {}, require(`${outputImageData}stageMap-2.json`)]; // filecounter = 5530; // -// for (let stage:number = 3; stage < Math.sqrt(maxZoom); stage++) { -// logger.info(`Stage (${0 * Math.sqrt(maxZoom) + 1 + stage}/${1}):`); -// await zoomTier(retHeightMap[stage -1]) -// .then((v: CZIHeightMap) => -// { -// retHeightMap.push(v); -// writeJSONToFile(`${outputImageData}stageMap-${stage}.json`, v); -// return; -// } -// ); +// for (let stage:number = 1; stage < Math.sqrt(maxZoom); stage++) { +// await zoomTier(layout.c_values[0].height_map[stage - 1]) +// .then((v: CZIHeightMap) => +// { +// writeJSONToFile(`${outputImageData}stageMap-${stage}.json`, v); +// return; +// } +// ); // } // } // -- cgit v1.2.1 From 9fe61e74a3dc28c7b4754f05d4c4b6bcd0f4e0c6 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Mon, 2 Apr 2018 06:59:02 +0100 Subject: almost fixed version of czi, v slow on first run round - and fails just toward the end of the second tier --- src/conversion/czi/czi.ts | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index 73c0577..1177e73 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -213,12 +213,30 @@ const extractAndStitchChunks: ( let outputFileName: string = ''; if (segments[0].length !== 1 || segments.length !== 1) { outputFileName = `${outputImageDirectory}${uuid.generate()}.png` + //top left of new image + let x1:number = getDimension(segments[0][0], 'X').Start; + let x2:number = getDimension( + segments[segments.length - 1][segments[0].length - 1], 'X').Start + + + getDimension(segments[segments.length - 1][segments[0].length - 1], 'X').Size; + //bottom right of new image + let y1:number = getDimension(segments[0][0], 'Y').Start; + let y2:number = getDimension( + segments[segments.length - 1][segments[0].length - 1], 'Y').Start + + + getDimension(segments[segments.length - 1][segments[0].length - 1], 'Y').Size; + + desiredRegion = regionToExtract( + new TileBounds(x1, x2, y1, y2), + desiredRegion, + 1 + ); shell.exec(`vips arrayjoin "${involvedTiles}" ${outputFileName} --across ${segments[0].length}`) finalImage = sharp(outputFileName) .extract({ - top: desiredRegion.top - getDimension(segments[0][0], 'Y').Start, - left: desiredRegion.left - getDimension(segments[0][0], 'X').Start, + top: desiredRegion.top, + left: desiredRegion.left, width: desiredRegion.width(), height: desiredRegion.height() }) @@ -547,7 +565,7 @@ const zoomTier: ( newZoomTier.plane.push(cziRow); timing = process.hrtime(timing); - iterTimes.push(timing[0] * 2); + iterTimes.push(timing[0]); if (iterTimes.length > 5) { iterTimes.shift(); } // tslint:disable-next-line:typedef avgItrTime = iterTimes.reduce((p, c, i) => p + (c - p) / (i + 1), 0); @@ -622,7 +640,7 @@ const extrapolateDimension: ( baseCZIHeightMap.plane.push(cziRow); ys += tileSize; timing = process.hrtime(timing); - iterTimes.push(timing[0] * 2); + iterTimes.push(timing[0]); if (iterTimes.length > 5) { iterTimes.shift(); } // tslint:disable-next-line:typedef avgItrTime = iterTimes.reduce((p, c, i) => p + (c - p) / (i + 1), 0); -- cgit v1.2.1 From 36e490b302f63ca82dfd8704ca828db742487fdf Mon Sep 17 00:00:00 2001 From: cjd24 Date: Tue, 10 Apr 2018 16:17:50 +0100 Subject: Reverting the ExtractAndStitchChunks to use Bufferbased method instead of VIPS --- src/conversion/czi/czi.ts | 168 +++++++++++++++++++++------------------------- 1 file changed, 77 insertions(+), 91 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index 1177e73..88a6814 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -187,107 +187,93 @@ const findRegionToExtract: ( * Take an ordered selection of segments and cookie cutter out a tile from this * into a new image */ -const extractAndStitchChunks: ( - segments: Segment[][], desiredRegion: TileBounds, fileCount: number -) => Promise = async ( - segments: Segment[][], desiredRegion: TileBounds, fileCount: number -): Promise => { - - let involvedTiles: string = ''; - // For all rows (y coords) in the image - for (const segRow of segments) { - for (const segCol of segRow) { - involvedTiles += `${extractionDirectory}${segCol.Data.Data} `; - } - } + const extractAndStitchChunks: ( + segments: Segment[][], desiredRegion: TileBounds + ) => Promise = async( + segments: Segment[][], desiredRegion: TileBounds + ): Promise => { - let originalRegion: TileBounds = new TileBounds( - getDimension(segments[0][0], 'X').Start, - getDimension(segments[0][0], 'X').Start + getDimension(segments[0][0], 'X').Size, - getDimension(segments[0][0], 'Y').Start, - getDimension(segments[0][0], 'Y').Start + getDimension(segments[0][0], 'Y').Size - ) - let finalImage: SharpInstance; - - try{ - let outputFileName: string = ''; - if (segments[0].length !== 1 || segments.length !== 1) { - outputFileName = `${outputImageDirectory}${uuid.generate()}.png` - //top left of new image - let x1:number = getDimension(segments[0][0], 'X').Start; - let x2:number = getDimension( - segments[segments.length - 1][segments[0].length - 1], 'X').Start - + - getDimension(segments[segments.length - 1][segments[0].length - 1], 'X').Size; - //bottom right of new image - let y1:number = getDimension(segments[0][0], 'Y').Start; - let y2:number = getDimension( - segments[segments.length - 1][segments[0].length - 1], 'Y').Start - + - getDimension(segments[segments.length - 1][segments[0].length - 1], 'Y').Size; - - desiredRegion = regionToExtract( - new TileBounds(x1, x2, y1, y2), - desiredRegion, - 1 - ); - shell.exec(`vips arrayjoin "${involvedTiles}" ${outputFileName} --across ${segments[0].length}`) + // Create a buffer for the rows part of raw image data + const tileVerticalBuffer: Buffer[] = []; - finalImage = sharp(outputFileName) + // For all ros (y coords) in the image + for (const segRow of segments) { + // Create a buffer for this row + const tileRow: Buffer[] = []; + let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); + + // For all of the columns within this row + for (const segCol of segRow) { + // Find out the region of the base tile to be added to the new image + chunkToExtract = findRegionToExtract(segCol, desiredRegion); + // Extract this section of image data into a sharp buffer + const data: Promise = + sharp(`${extractionDirectory}${segCol.Data.Data}`) .extract({ - top: desiredRegion.top, - left: desiredRegion.left, - width: desiredRegion.width(), - height: desiredRegion.height() + left: chunkToExtract.left, + top: chunkToExtract.top, + width: chunkToExtract.right - chunkToExtract.left, + height: chunkToExtract.bottom - chunkToExtract.top }) + .toBuffer(); - } else { - desiredRegion = regionToExtract( - new TileBounds( - getDimension(segments[0][0], 'X').Start, - getDimension(segments[0][0], 'X').Start + getDimension(segments[0][0], 'X').Size, - getDimension(segments[0][0], 'Y').Start, - getDimension(segments[0][0], 'Y').Start + getDimension(segments[0][0], 'Y').Size - ), - desiredRegion, - 1 - ); - finalImage = sharp(`${extractionDirectory}${segments[0][0].Data.Data}`) - .extract({ - top: desiredRegion.top, - left: desiredRegion.left, - width: desiredRegion.width(), - height: desiredRegion.height() - }); + // Push this data into the row buffer + tileRow.push(await data); } - if (desiredRegion.width() < tileSize || desiredRegion.height() < tileSize) { - finalImage - .background({ - r: 0, g: 0, b: 0, alpha: 0}) - .extend({ - left: 0, - right: tileSize - desiredRegion.width(), + // Prepare variables to squash all of the column data into one, for this row + let imageVerticalSlice: SharpInstance = sharp(tileRow[0]); + const bufferBound: TileBounds = findRegionToExtract(segRow[0], desiredRegion); + // Check if the inital chunk needs to be extended to support the other columns + if ((bufferBound.right - bufferBound.left) < (tileSize - tileOverlap)) { + imageVerticalSlice = await imageVerticalSlice.extend({ + top: 0, + left: 0, + bottom: 0, + right: (tileSize - (bufferBound.right - bufferBound.left)) + }); + } + // For every column along this row, join it to the previous column data + for (let index: number = 1; index < segRow.length; index++) { + imageVerticalSlice = await imageVerticalSlice + .overlayWith(tileRow[index], { top: 0, - bottom: tileSize - desiredRegion.height() + left: (bufferBound.right - bufferBound.left) + + ((index - 1) * tileSize) }); - } else { - finalImage.background({ - r: 0, g: 0, b: 0, alpha: 0}) } - await finalImage.toFile(`${outputImageDirectory}img-${fileCount}.png`); - if (segments[0].length !== 1 || segments.length !== 1) { - shell.rm(outputFileName); - } - } catch (error) { - console.log(); - console.log(error); - console.log(desiredRegion) - console.log(involvedTiles) - console.log(desiredRegion.top - getDimension(segments[0][0], 'Y').Start, desiredRegion.left - getDimension(segments[0][0], 'X').Start, desiredRegion.width(), desiredRegion.height()) - throw new Error("SAD BOI ERROR>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); + // Add this horizontal data buffer to the vertical buffer + tileVerticalBuffer.push(await imageVerticalSlice.toBuffer()); } + + // Prepare variables used to combine all rows into one image + let finalImage: SharpInstance = sharp(tileVerticalBuffer[0]); + const bufferBound: TileBounds = + findRegionToExtract(segments[0][0], desiredRegion); + // Check if the inital row needs to be extended to support further rows + if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) { + finalImage = await finalImage.background({ + r: 0, + g: 0, + b: 0, + alpha: 0 + }).extend({ + top: 0, + left: 0, + bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), + right: 0 + }); + } + // For all further rows in the image, combine it with the previous rows' data + for (let index: number = 1; index < segments.length; index++) { + finalImage = finalImage.overlayWith( + tileVerticalBuffer[index], + {top: getDimension(segments[index - 1][0], 'Y').Size, left: 0}); + } + + // Return the finalised image. + return finalImage; }; /** @@ -628,12 +614,12 @@ const extrapolateDimension: ( y_offset: ys, width: tileSize, height: tileSize, - file: `img-${filecounter}.png` + file: `img-${filecounter++}.png` }); const sortedSegments: Segment[][] = orderSegments(findRelatedTiles(filteredDataBlocks, desired)); - await extractAndStitchChunks(sortedSegments, desired, filecounter++); + await extractAndStitchChunks(sortedSegments, desired); process.stdout.write(">"); finalCZIJson.total_files++; } -- cgit v1.2.1 From 1d65ce003823143d33beba03cc82729a6c975ce7 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Thu, 19 Apr 2018 05:01:01 +0100 Subject: Added a write of the base teir JSON object, made the images actually write to file lol - still havent been able to tell if this is a working commit yet, need to try from the second teir onwards. --- src/conversion/czi/convertJxrs.py | 44 ++++++++++++++++++++------------------- src/conversion/czi/czi.ts | 18 +++++++++++----- 2 files changed, 36 insertions(+), 26 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/convertJxrs.py b/src/conversion/czi/convertJxrs.py index 2ba81b3..f4b897f 100644 --- a/src/conversion/czi/convertJxrs.py +++ b/src/conversion/czi/convertJxrs.py @@ -8,19 +8,21 @@ coutner = 0 def convertjxrs(filename): - global counter - global totalFiles + global counter + global totalFiles try: asTif = filename.rsplit('.',1)[0] + ".tif" - check_call(['JxrDecApp', "-i", filename, "-o", asTif]) - check_call(['convert', asTif, filename.rsplit('.',1)[0] + ".png"]) - check_call(['rm', filename, asTif]) - counter += 1 - except: - print ("Processing Failed. Probably couldn't find decoder due to invalid system environment path, check this before debugging.") + check_call(['JxrDecApp', "-i", filename, "-o", asTif]) + check_call(['convert', asTif, filename.rsplit('.',1)[0] + ".png"]) + check_call(['rm', filename, asTif]) + counter += 1 + except Exception as help: + print ("Processing Failed. Probably couldn't find decoder due to invalid system environment path, check this before debugging."); + print ("Actual error was:"); + print (help); exit(0); - print (f"> Processed File: {counter}/{totalFiles} : {filename} --> {filename.rsplit('.',1)[0]}.png") + print (f"> Processed File: {counter}/{totalFiles} : {filename} --> {filename.rsplit('.',1)[0]}.png") if __name__ == "__main__": @@ -29,15 +31,15 @@ if __name__ == "__main__": print("\nMissing Argument!\n\nUsage:\npython3 convertJxrs.py ") exit(0) else: - print("=========== BEGIN JXR CONVERSION ===========") - print ('Files Dir: ' + argv[1] + '\n') - - filenames = glob(argv[1] + 'data-*.jxr') - counter = 0 - totalFiles = len(filenames) - - pool = ThreadPoolExecutor(5) - for f in pool.map(convertjxrs, filenames): - pass - pool.shutdown(True) - print("=========== FINISH JXR CONVERSION ===========") + print("=========== BEGIN JXR CONVERSION ===========") + print ('Files Dir: ' + argv[1] + '\n') + + filenames = glob(argv[1] + 'data-*.jxr') + counter = 0 + totalFiles = len(filenames) + + pool = ThreadPoolExecutor(5) + for f in pool.map(convertjxrs, filenames): + pass + pool.shutdown(True) + print("=========== FINISH JXR CONVERSION ===========") diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index 88a6814..c10a6f7 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -13,6 +13,7 @@ import { uuid } from '../../uuid' // Various constants for placing files and defining tiles const baseDirname: string = '/cs/scratch/cjd24/0701-extraction'; +const extensionBinariesDir: string = __dirname + `/../../../ext/bin/`; const extractionDirectory: string = `${baseDirname}/`; const outputImageData: string = `${baseDirname}-processed/`; const outputImageDirectory: string = `${baseDirname}-processed/data/`; @@ -530,8 +531,8 @@ const zoomTier: ( quadrents += `${outputImageDirectory}${previousHeightMap.plane[ys + 1][xs + 1].file} `; } - let outputFileName: string =`${outputImageData}tmp/${uuid.generate()}.png` - shell.exec(`vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`) + let outputFileName: string =`${outputImageData}tmp/${uuid.generate()}.png`; + shell.exec(`${extensionBinariesDir}vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`); // Rescale and push to file await sharp(outputFileName) @@ -614,12 +615,14 @@ const extrapolateDimension: ( y_offset: ys, width: tileSize, height: tileSize, - file: `img-${filecounter++}.png` + file: `img-${filecounter}.png` }); const sortedSegments: Segment[][] = orderSegments(findRelatedTiles(filteredDataBlocks, desired)); - await extractAndStitchChunks(sortedSegments, desired); + (await extractAndStitchChunks(sortedSegments, desired)) + .toFile(`${outputImageDirectory}img-${filecounter++}`); + process.stdout.write(">"); finalCZIJson.total_files++; } @@ -647,6 +650,7 @@ const extrapolateDimension: ( }; Begin computing zoom tiers...\n`); const retHeightMap: CZIHeightMap[] = [baseCZIHeightMap]; + writeJSONToFile(`${outputImageData}stageMap-${cVal}-${0}`, retHeightMap); for (let stage: number = 1; stage < Math.log2(maxZoom); stage++) { console.log(`Stage (${cVal * Math.log2(maxZoom) + 1 + stage}/${totalCs}):`); await zoomTier(retHeightMap[stage - 1]) @@ -704,7 +708,11 @@ const createSupportedViewsObject: () => void = (): void => { // Cleanup and create "smart" supported views object without whole metadata cleanSupportedViews(supportedViews); - supportedViews.scalable_image.metadata = {}; + supportedViews.scalable_image.metadata = { + tile_size: tileSize, + max_zoom: maxZoom, + tile_overlap: tileOverlap + }; writeJSONToFile( `${outputImageData}supported_views_minus_xml.json`, supportedViews); }; -- cgit v1.2.1 From 32dede1bd9b84b46ffba8939cdb98641d06c4f20 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Fri, 20 Apr 2018 22:02:44 +0100 Subject: Seems to have got the big boi CZI working again, added support for lecia files --- src/conversion/czi/czi.ts | 92 +++++++++++----------------- src/conversion/czi/cziConvert.sh | 2 + src/conversion/czi/pyramidWorker.ts | 4 +- src/conversion/czi/tileExtraction.ts | 2 +- src/conversion/leica/requestconvertor.ts | 1 + src/conversion/leica/scn.ts | 100 ++++++++++++++++++++++++++++++ src/conversion/types/helperCZITypes.ts | 66 -------------------- src/conversion/types/helpers.ts | 102 +++++++++++++++++++++++++++++++ 8 files changed, 245 insertions(+), 124 deletions(-) create mode 100644 src/conversion/leica/requestconvertor.ts create mode 100644 src/conversion/leica/scn.ts delete mode 100644 src/conversion/types/helperCZITypes.ts create mode 100644 src/conversion/types/helpers.ts (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index c10a6f7..1d157ff 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -2,7 +2,7 @@ import { CZIHeightMap, CZITile, WholeCZIHierarchy } from '../types/customPyramidIndex'; import { Dimension, Segment } from '../types/cziBinaryTypings'; import * as fs from 'fs'; -import { SupportedViews, TileBounds } from '../types/helperCZITypes'; +import { SupportedViews, TileBounds, checkForOutputDirectories, writeJSONToFile, execpaths } from '../types/helpers'; // import { logger } from '../../logger'; import * as sharp from 'sharp'; // tslint:disable-next-line:no-duplicate-imports @@ -13,7 +13,6 @@ import { uuid } from '../../uuid' // Various constants for placing files and defining tiles const baseDirname: string = '/cs/scratch/cjd24/0701-extraction'; -const extensionBinariesDir: string = __dirname + `/../../../ext/bin/`; const extractionDirectory: string = `${baseDirname}/`; const outputImageData: string = `${baseDirname}-processed/`; const outputImageDirectory: string = `${baseDirname}-processed/data/`; @@ -189,9 +188,9 @@ const findRegionToExtract: ( * into a new image */ const extractAndStitchChunks: ( - segments: Segment[][], desiredRegion: TileBounds + segments: Segment[][], desiredRegion: TileBounds, tmp: number ) => Promise = async( - segments: Segment[][], desiredRegion: TileBounds + segments: Segment[][], desiredRegion: TileBounds, tmp: number ): Promise => { // Create a buffer for the rows part of raw image data @@ -254,17 +253,18 @@ const findRegionToExtract: ( findRegionToExtract(segments[0][0], desiredRegion); // Check if the inital row needs to be extended to support further rows if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) { - finalImage = await finalImage.background({ - r: 0, - g: 0, - b: 0, - alpha: 0 - }).extend({ - top: 0, - left: 0, - bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), - right: 0 - }); + finalImage = await finalImage + .background({ + r: 0, + g: 0, + b: 0, + alpha: 0 + }).extend({ + top: 0, + left: 0, + bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), + right: 0 + }); } // For all further rows in the image, combine it with the previous rows' data for (let index: number = 1; index < segments.length; index++) { @@ -274,8 +274,16 @@ const findRegionToExtract: ( } // Return the finalised image. - return finalImage; -}; + return sharp(Buffer.alloc(1,1), { + create: { + width: tileSize, + height: tileSize, + channels: 4, + background: { r: 0, g: 0, b: 0, alpha: 0 } + } + }).overlayWith(await finalImage.toBuffer()) + // .toFile("/cs/home/cjd24/Documents/current/groupPractical/project-code/src/conversion/czi/test1.png"); +} /** * Used to remove obtuse JSON data, @@ -532,7 +540,8 @@ const zoomTier: ( } let outputFileName: string =`${outputImageData}tmp/${uuid.generate()}.png`; - shell.exec(`${extensionBinariesDir}vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`); +// console.log(quadrents); + shell.exec(`${execpaths} vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`); // Rescale and push to file await sharp(outputFileName) @@ -601,7 +610,8 @@ const extrapolateDimension: ( for (; ys < totalSizeY;) { timing = process.hrtime(); const cziRow: CZITile[] = []; - process.stdout.write(`${Math.ceil(totalSizeX/tileSize)} : `); + let rowProgBar: string = `${Math.ceil(totalSizeX/tileSize)} : `; + let rowProgCount: number = 0; for (let xs: number = 0; xs < totalSizeX; xs += tileSize) { const desired: TileBounds = new TileBounds( xs - tileOverlap, @@ -620,10 +630,12 @@ const extrapolateDimension: ( const sortedSegments: Segment[][] = orderSegments(findRelatedTiles(filteredDataBlocks, desired)); - (await extractAndStitchChunks(sortedSegments, desired)) - .toFile(`${outputImageDirectory}img-${filecounter++}`); + (await extractAndStitchChunks(sortedSegments, desired, filecounter)) + .toFile(`${outputImageDirectory}img-${filecounter++}.png`); +// shell.exec(`${execpaths} vips addalpha "${outputImageDirectory}img-${filecounter}" "${outputImageDirectory}img-${filecounter++}"`); - process.stdout.write(">"); + rowProgBar += ">"; rowProgCount++; + process.stdout.write(`\r${rowProgBar} ${rowProgCount}`); finalCZIJson.total_files++; } baseCZIHeightMap.plane.push(cziRow); @@ -651,7 +663,7 @@ const extrapolateDimension: ( const retHeightMap: CZIHeightMap[] = [baseCZIHeightMap]; writeJSONToFile(`${outputImageData}stageMap-${cVal}-${0}`, retHeightMap); - for (let stage: number = 1; stage < Math.log2(maxZoom); stage++) { + for (let stage: number = 1; stage <= Math.log2(maxZoom); stage++) { console.log(`Stage (${cVal * Math.log2(maxZoom) + 1 + stage}/${totalCs}):`); await zoomTier(retHeightMap[stage - 1]) .then((v: CZIHeightMap) => { @@ -666,35 +678,6 @@ const extrapolateDimension: ( return retHeightMap; }; -/** - * function used to ensure that the directories required have been created - */ -const checkForOutputDirectories: (directories: string[]) => void = ( - directories: string[] -): void => { - for (const dir of directories) { - if (!fs.existsSync(`${dir}`)) { - fs.mkdirSync(`${dir}`); - } - } -}; - -/** - * Write given JSON object to given filepath - */ -const writeJSONToFile: (filePath: string, obj: object) => - void = (filePath: string, obj: object): void => { - fs.writeFile( - filePath, - JSON.stringify(obj, null, 2), - (err: Error) => { - if (err) { - console.error(err.message); - throw err; - } - } - ); - }; /** * used to write the supported views object to file both in total and "cleaned" @@ -787,17 +770,16 @@ main(); // async function main2() { // // let layout: WholeCZIHierarchy = require(`${outputImageData}layout.json`); -// filecounter = 5530; // // for (let stage:number = 1; stage < Math.sqrt(maxZoom); stage++) { // await zoomTier(layout.c_values[0].height_map[stage - 1]) // .then((v: CZIHeightMap) => // { -// writeJSONToFile(`${outputImageData}stageMap-${stage}.json`, v); +// writeJSONToFile(`${outputImageData}stageMap-${stage}.json`, v); // return; // } // ); // } // } // -// main2().then(); +// main2().then().catch(e => console.log(e)); diff --git a/src/conversion/czi/cziConvert.sh b/src/conversion/czi/cziConvert.sh index 2529d44..dd664d5 100755 --- a/src/conversion/czi/cziConvert.sh +++ b/src/conversion/czi/cziConvert.sh @@ -5,6 +5,8 @@ CZI_WORKING_DIR=${1:-"/cs/scratch"} CZI_EXTRACTION_DIR=${2:-${FILENAME}} CZI_FILE=${3:-${FILENAME}".czi"} +echo "about to try to convert: " + ${CZI_WORKING_DIR}/${USER}/${CZI_FILE} + gcc -Wall -Wextra --pedantic -std=c99 cziconvert.c mkdir -p ${CZI_WORKING_DIR}/${USER}/${CZI_EXTRACTION_DIR} ./a.out ${CZI_WORKING_DIR}/${USER}/${CZI_FILE} ${CZI_WORKING_DIR}/${USER}/${CZI_EXTRACTION_DIR}/ ${PWD}/convertJxrs.py diff --git a/src/conversion/czi/pyramidWorker.ts b/src/conversion/czi/pyramidWorker.ts index 19acbf9..5e6911c 100644 --- a/src/conversion/czi/pyramidWorker.ts +++ b/src/conversion/czi/pyramidWorker.ts @@ -1,5 +1,5 @@ import { CZIHeightMap, CZITile, CZITileRequest } from '../types/customPyramidIndex'; -import { TileBounds } from '../types/helperCZITypes'; +import { TileBounds, execpaths } from '../types/helpers'; import * as sharp from 'sharp'; import { isTileRelated } from './tileExtraction'; import { uuid } from '../../uuid' @@ -44,7 +44,7 @@ const getFinalTile: Function = async function(imageDir: string, imageTier: CZIHe } let outputFileName: string =`${imageDir}/tmp/${uuid.generate()}.png` - require('shelljs').exec(`vips arrayjoin "${involvedTiles}" ${outputFileName} --across ${imageTier.plane[0].length}`) + require('shelljs').exec(`${execpaths} vips arrayjoin "${involvedTiles}" ${outputFileName} --across ${imageTier.plane[0].length}`) let extractionRegion = new TileBounds( desiredRegion.left - imageTier.plane[0][0].width, diff --git a/src/conversion/czi/tileExtraction.ts b/src/conversion/czi/tileExtraction.ts index a768f6e..83f63a5 100644 --- a/src/conversion/czi/tileExtraction.ts +++ b/src/conversion/czi/tileExtraction.ts @@ -1,4 +1,4 @@ -import { TileBounds } from '../types/helperCZITypes'; +import { TileBounds } from '../types/helpers'; export const isTileRelated: Function = function(origCoords: TileBounds, desired: TileBounds): boolean { diff --git a/src/conversion/leica/requestconvertor.ts b/src/conversion/leica/requestconvertor.ts new file mode 100644 index 0000000..50002d7 --- /dev/null +++ b/src/conversion/leica/requestconvertor.ts @@ -0,0 +1 @@ +import { logger } from '../../logger'; diff --git a/src/conversion/leica/scn.ts b/src/conversion/leica/scn.ts new file mode 100644 index 0000000..e2125e1 --- /dev/null +++ b/src/conversion/leica/scn.ts @@ -0,0 +1,100 @@ +import * as fs from 'fs'; +import * as sharp from 'sharp'; +// tslint:disable-next-line:no-duplicate-imports +import { SharpInstance } from 'sharp'; +import { SupportedViews, TileBounds, writeJSONToFile, checkForOutputDirectories } from '../types/helpers'; +import { uuid } from '../../uuid' +import { logger } from '../../logger'; + +// CHANGE ME FOR TESTING!!!!! +const input: string = "test.tiff" +const baseDirname: string = '/cs/scratch/cjd24/tifers/'; + + + +// Various constants for placing files and defining tiles +const extensionBinariesDir: string = __dirname + `/../../../ext/bin/`; +const execpaths: string = `PATH="$PATH:${extensionBinariesDir}" LD_LIBRARY_PATH="$LD_LIBRARY_PATH:${extensionBinariesDir}../lib/" `; + +const tileOverlap: number = 0; // Overlap is only half implemented +const tileSize: number = 512; + + +const crunchLeica: () => void = async (): Promise => { + + try { + let output: string =`${baseDirname}${uuid.generate()}/`; + let leica: SharpInstance = sharp(baseDirname + input).png(); + logger.debug("Read new sharp instance for lecia: " + input); + + checkForOutputDirectories([output]); + logger.info("Creating new output directory for LECIA > DZI @ " + output); + + let meta: sharp.Metadata = await leica.metadata(); + + let width: number = -1; + let height: number = -1; + if (meta.width !== undefined) { + width = meta.width; + } + if (meta.height !== undefined) { + height = meta.height; + } + + let supportedViews: SupportedViews = { + scalable_image: { + width: width, + height: height, + channels: + [{ + channel_id: '-1', + channel_name: '-1', + metadata: {} + }], + metadata: { + tile_size: tileSize, + max_zoom: "Not yet supported in this version of convertor", + tile_overlap: tileOverlap, + exif: meta.exif + } + } + } + + let channels: any = []; + if (meta.channels !== undefined) { + for (let index: number = 0; index < meta.channels; index++) { + channels.push({ + channel_id: `${index}`, + channel_name: `${meta.space}`, + metadata: {} + }) + } + supportedViews.scalable_image.channels = channels; + } + + writeJSONToFile(`${output}supported_views.json`, supportedViews) + logger.info("Wrote supported_views object for: " + output); + + await sharp(baseDirname + input) + .png() + .tile({ + size: tileSize, + overlap: tileOverlap, + layout: "dz" + }) + .toFile(`${output}output.dzi`); + logger.success(`Finalised output of ${input} as .dzi`); + } + catch (err) { + logger.failure(`Lecia conversion failed with error: ${err}`) + } +}; + +/** + * Main function used to call the rest of the relevant code to crunch a CZI + * extraction. + */ +const main: () => void = (): void => { + crunchLeica(); +}; +main(); diff --git a/src/conversion/types/helperCZITypes.ts b/src/conversion/types/helperCZITypes.ts deleted file mode 100644 index 8f6310a..0000000 --- a/src/conversion/types/helperCZITypes.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { Node } from 'xml-parser'; - -/** - * Interface used to define the structure of the "supportedViews" section - * of the protocol specification for scalable images - */ -export interface SupportedViews { - scalable_image: { - width: number; - height: number; - channels: - { - channel_id: string; - channel_name: string; - metadata?: {}; - }[]; - real_width?: { - value?: number; - units?: string; - }; - real_height?: { - value?: number; - units?: string; - }; - metadata?: {}; - }; -} - -/** - * Interface used to define the pixel-bounds of a 'section' within the image - */ -export class TileBounds { - public left: number; - public right: number; - public top: number; - public bottom: number; - public constructor( - leftBound: number, - rightBound: number, - topBound: number, - bottomBound: number - ) { - this.left = leftBound; - this.right = rightBound; - this.top = topBound; - this.bottom = bottomBound; - } - public width(): number { - return this.right - this.left; - } - public height(): number { - return this.bottom - this.top; - } - public scaleDown(level: number) { - this.left = Math.ceil(this.left / level), - this.right = Math.ceil(this.right / level), - this.top = Math.ceil(this.top / level), - this.bottom = Math.ceil(this.bottom / level) - } - public scaleUp(level: number) { - this.left = Math.floor(this.left * level), - this.right = Math.ceil(this.right * level), - this.top = Math.ceil(this.top * level), - this.bottom = Math.ceil(this.bottom * level) - } -} diff --git a/src/conversion/types/helpers.ts b/src/conversion/types/helpers.ts new file mode 100644 index 0000000..8e07944 --- /dev/null +++ b/src/conversion/types/helpers.ts @@ -0,0 +1,102 @@ +import * as fs from 'fs'; +import { Node } from 'xml-parser'; + +/** + * Interface used to define the structure of the "supportedViews" section + * of the protocol specification for scalable images + */ +export interface SupportedViews { + scalable_image: { + width: number; + height: number; + channels: + { + channel_id: string; + channel_name: string; + metadata?: {}; + }[]; + real_width?: { + value?: number; + units?: string; + }; + real_height?: { + value?: number; + units?: string; + }; + metadata?: {}; + }; +} + +/** + * Interface used to define the pixel-bounds of a 'section' within the image + */ +export class TileBounds { + public left: number; + public right: number; + public top: number; + public bottom: number; + public constructor( + leftBound: number, + rightBound: number, + topBound: number, + bottomBound: number + ) { + this.left = leftBound; + this.right = rightBound; + this.top = topBound; + this.bottom = bottomBound; + } + public width(): number { + return this.right - this.left; + } + public height(): number { + return this.bottom - this.top; + } + public scaleDown(level: number) { + this.left = Math.ceil(this.left / level), + this.right = Math.ceil(this.right / level), + this.top = Math.ceil(this.top / level), + this.bottom = Math.ceil(this.bottom / level) + } + public scaleUp(level: number) { + this.left = Math.floor(this.left * level), + this.right = Math.ceil(this.right * level), + this.top = Math.ceil(this.top * level), + this.bottom = Math.ceil(this.bottom * level) + } +} + + + +/** + * function used to ensure that the directories required have been created + */ +export const checkForOutputDirectories: (directories: string[]) => void = ( + directories: string[] +): void => { + for (const dir of directories) { + if (!fs.existsSync(`${dir}`)) { + fs.mkdirSync(`${dir}`); + } + } +}; + +/** + * Write given JSON object to given filepath + */ +export const writeJSONToFile: (filePath: string, obj: object) => + void = (filePath: string, obj: object): void => { + fs.writeFile( + filePath, + JSON.stringify(obj, null, 2), + (err: Error) => { + if (err) { + console.error(err.message); + throw err; + } + } + ); + }; + +const extensionBinariesDir: string = __dirname + `/../../../ext/bin/`; +export const execpaths: string = `PATH="$PATH:${extensionBinariesDir}" LD_LIBRARY_PATH="$LD_LIBRARY_PATH:${extensionBinariesDir}../lib/" `; -- cgit v1.2.1 From 4aeb0e10055f5ffdfd15fe3f6ac599f977d4f101 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Sat, 21 Apr 2018 02:42:44 +0100 Subject: adding support for excel to csv stuff and fixed stage count of czi conversion --- src/conversion/csv/excel.ts | 97 +++++++++++++++++++++++++++++++++++++++++++++ src/conversion/czi/czi.ts | 2 +- 2 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 src/conversion/csv/excel.ts (limited to 'src/conversion') diff --git a/src/conversion/csv/excel.ts b/src/conversion/csv/excel.ts new file mode 100644 index 0000000..2764192 --- /dev/null +++ b/src/conversion/csv/excel.ts @@ -0,0 +1,97 @@ +import { logger } from '../../logger'; +import * as xlsx from 'xlsx'; +import * as fs from 'fs'; + +// const testDir: string = `/cs/scratch/cjd24/csv/`; +// const testFile: string = `test1.xlsx` + + +const toCSV: (file: string) => Promise = async (file: string): Promise => { + logger.info(`xls convertor received new file to convert to csv: ${file}`); + + let book: xlsx.WorkBook = xlsx.readFile(file); + try { + let sheetnames: string[] = []; + for (let name of book.SheetNames) { + fs.writeFile(`${file.split('.')[0]}-${name}.csv`, xlsx.utils.sheet_to_csv(book.Sheets[name])); + sheetnames.push(`${file.split('.')[0]}-${name}.csv`); + logger.info(`Wrote ${file.split('.')[1]} subsheet {${file} : ${name}} as CSV.`); + } + return sheetnames === [] ? ["__Empty_Book_Error"] : sheetnames; + } catch (err) { + logger.error(err); + return ["__Conversion_to_csv_Error_Occurred: " + err] + } +} + +const toJSON: (file: string) => Promise = async (file: string): Promise => { + logger.info(`xls convertor received new file to convert to json: ${file}`); + + let book: xlsx.WorkBook = xlsx.readFile(file); + try { + let sheetnames: string[] = []; + for (let name of book.SheetNames) { + fs.writeFile(`${file.split('.')[0]}-${name}.json`, xlsx.utils.sheet_to_json(book.Sheets[name])); + sheetnames.push(`${file.split('.')[0]}-${name}.json`); + logger.info(`Wrote ${file.split('.')[1]} subsheet {${file} : ${name}} as JSON.`); + } + return sheetnames === [] ? ["__Empty_Book_Error"] : sheetnames; + } catch (err) { + logger.error(err); + return ["__Conversion_to_json_Error_Occurred: " + err] + } +} + +const toHTML: (file: string) => Promise = async (file: string): Promise => { + logger.info(`xls convertor received new file to convert to html: ${file}`); + + let book: xlsx.WorkBook = xlsx.readFile(file); + try { + let sheetnames: string[] = []; + for (let name of book.SheetNames) { + fs.writeFile(`${file.split('.')[0]}-${name}.html`, xlsx.utils.sheet_to_html(book.Sheets[name])); + sheetnames.push(`${file.split('.')[0]}-${name}.html`); + logger.info(`Wrote ${file.split('.')[1]} subsheet {${file} : ${name}} as HTML.`); + } + return sheetnames === [] ? ["__Empty_Book_Error"] : sheetnames; + } catch (err) { + logger.error(err); + return ["__Conversion_to_html_Error_Occurred: " + err] + } +} + +const toAll: (file: string) => +Promise<{csv: string[], json: string[], html: string[]}> = +async (file: string): +Promise<{csv: string[], json: string[], html: string[]}> => { + return { + csv: await toCSV(file), + json: await toCSV(file), + html: await toCSV(file) + } +} + + +// const main: () => void = async (): Promise => { +// +// try { +// let file: xlsx.WorkBook = xlsx.readFile(`${testDir}${testFile}`); +// +// for (let name of file.SheetNames) { +// fs.writeFileSync(`${testDir}${testFile.split('.')[0]}-${name}.csv`, xlsx.utils.sheet_to_csv(file.Sheets[name])); +// logger.info(`Wrote ${testFile.split('.')[1]} subsheet {${testFile} : ${name}} as CSV.`); +// fs.writeFileSync(`${testDir}${testFile.split('.')[0]}-${name}.json`, xlsx.utils.sheet_to_json(file.Sheets[name])); +// logger.info(`Wrote ${testFile.split('.')[1]} subsheet {${testFile} : ${name}} as json.`); +// fs.writeFileSync(`${testDir}${testFile.split('.')[0]}-${name}.html`, xlsx.utils.sheet_to_html(file.Sheets[name])); +// logger.info(`Wrote ${testFile.split('.')[1]} subsheet {${testFile} : ${name}} as HTML.`); +// } +// +// logger.success(`Wrote ${testFile.split('.')[1]} {${testFile}} as CSV.`); +// logger.success(`Wrote ${testFile.split('.')[1]} {${testFile}} as JSON.`); +// logger.success(`Wrote ${testFile.split('.')[1]} {${testFile}} as HTML.`); +// } catch (err) { +// // console.log(err); +// logger.error(err); +// } +// }; +// main(); diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index 1d157ff..1a92fa6 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -715,7 +715,7 @@ const buildCustomPyramids: () => Promise = async(): Promise => { // Extract the base tiles and build up custom pyramid data await extrapolateDimension( Number.parseInt(cval.channel_id, 10), - supportedViews.scalable_image.channels.length * Math.log2(maxZoom), + supportedViews.scalable_image.channels.length * Math.log2(maxZoom * 2), maxZoom ).then((v: CZIHeightMap[]) => { // On success, add the new heightmap to the final json data block -- cgit v1.2.1 From 6d8328fcaeb01603a8ab2e45b0b3ac5f0801e58d Mon Sep 17 00:00:00 2001 From: cjd24 Date: Sat, 21 Apr 2018 14:02:33 +0100 Subject: apparent fix of CRITICAL czi bug, along with small redundancy based performance enhancements & minor changes to progress bar --- src/conversion/czi/czi.ts | 78 ++++++++++++++++++++++++++++++++++----------- src/conversion/leica/scn.ts | 17 ++++------ 2 files changed, 66 insertions(+), 29 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index 1a92fa6..c453a23 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -20,6 +20,8 @@ const tileOverlap: number = 0; // Overlap is only half implemented const tileSize: number = 1024; const maxZoom: number = 64; const shell = require('shelljs'); +let filecounter: number = 0; + /** * Simple function to find the tile bounds version of an original tile @@ -274,14 +276,18 @@ const findRegionToExtract: ( } // Return the finalised image. - return sharp(Buffer.alloc(1,1), { - create: { - width: tileSize, - height: tileSize, - channels: 4, - background: { r: 0, g: 0, b: 0, alpha: 0 } - } - }).overlayWith(await finalImage.toBuffer()) + if ((await finalImage.metadata()).channels != 4) { + return sharp(Buffer.alloc(tileSize, tileSize), { + create: { + width: tileSize, + height: tileSize, + channels: 4, + background: { r: 0, g: 0, b: 0, alpha: 0 } + } + }).overlayWith(await finalImage.toBuffer()) + } else { + return finalImage; + } // .toFile("/cs/home/cjd24/Documents/current/groupPractical/project-code/src/conversion/czi/test1.png"); } @@ -482,8 +488,6 @@ const parseExtractedXML: (xmlFile: string) => void = ( // Begin work on getting the new tiles all nice //////////////////////////////////////////////////////////////////////////////// -// Print out all of the related tiles to every new tile to be created. -let filecounter: number = 0; /** * This is used to create the next zoomed out tier of the given height map */ @@ -511,10 +515,13 @@ const zoomTier: ( return previousHeightMap; } + let quadrentCount: number; + // For all rows within the previous plane for (; ys < previousHeightMap.plane.length; ys += 2) { timing = process.hrtime(); const cziRow: CZITile[] = []; + let rowProgBar: string = `${Math.ceil(previousHeightMap.plane[0].length / 2)} : `, rowProgCount: number = 0; // For all columns within the previous plane for (let xs: number = 0; xs < previousHeightMap.plane[0].length; xs += 2) { @@ -522,17 +529,20 @@ const zoomTier: ( // Top left let quadrents:string = `${outputImageDirectory}${previousHeightMap.plane[ys][xs].file} `; let across:number = 1; + quadrentCount = 1; // Combine top right const moreToRight: boolean = (xs + 1) < previousHeightMap.plane[0].length; if (moreToRight) { quadrents += `${outputImageDirectory}${previousHeightMap.plane[ys][xs + 1].file} `; across++; + quadrentCount++; } // Combine bottom left const moreToBottom: boolean = (ys + 1) < previousHeightMap.plane.length; if (moreToBottom) { quadrents += `${outputImageDirectory}${previousHeightMap.plane[ys + 1][xs].file} `; + quadrentCount++; } // Combine bottom right if (moreToBottom && moreToRight) { @@ -544,9 +554,28 @@ const zoomTier: ( shell.exec(`${execpaths} vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`); // Rescale and push to file - await sharp(outputFileName) - .resize(tileSize, tileSize) - .toFile(`${outputImageDirectory}img-${filecounter}.png`); + if (quadrentCount !== 3) { + + let extRight: number = 0, extBottom: number = 0; + if (moreToRight) { + extBottom = tileSize; + } else if (moreToBottom){ + extRight = tileSize; + } + + sharp(await sharp(outputFileName) + .background({r: 0, g: 0, b: 0, alpha: 0}) + .extend({ + top: 0, left: 0, + bottom: extBottom, right: extRight + }).toBuffer()) + .resize(tileSize, tileSize) + .toFile(`${outputImageDirectory}img-${filecounter}.png`); + } else { + await sharp(outputFileName) + .resize(tileSize, tileSize) + .toFile(`${outputImageDirectory}img-${filecounter}.png`); + } shell.rm(outputFileName); cziRow.push({ @@ -557,6 +586,8 @@ const zoomTier: ( file: `img-${filecounter++}.png` }); finalCZIJson.total_files++; + rowProgBar += ">"; rowProgCount++; + process.stdout.write(`\r${rowProgBar} ${rowProgCount}`); } newZoomTier.plane.push(cziRow); @@ -565,6 +596,7 @@ const zoomTier: ( if (iterTimes.length > 5) { iterTimes.shift(); } // tslint:disable-next-line:typedef avgItrTime = iterTimes.reduce((p, c, i) => p + (c - p) / (i + 1), 0); + process.stdout.write("\r"); console.log( ` Task(${ys / 2 + 1}/${ Math.floor(previousHeightMap.plane.length / 2) + 1}): ` + @@ -610,9 +642,19 @@ const extrapolateDimension: ( for (; ys < totalSizeY;) { timing = process.hrtime(); const cziRow: CZITile[] = []; - let rowProgBar: string = `${Math.ceil(totalSizeX/tileSize)} : `; - let rowProgCount: number = 0; + let rowProgBar: string = `${Math.ceil(totalSizeX/tileSize)} : `, rowProgCount: number = 0; for (let xs: number = 0; xs < totalSizeX; xs += tileSize) { + if (fs.existsSync(`${outputImageDirectory}img-${filecounter}.png`) && (ys + tileSize < totalSizeY)) { + ///////////////////////////////////////////////////////////////////////////////////This if statement should be temporary??????????????????????????????????/ + cziRow.push({ + x_offset: xs, + y_offset: ys, + width: tileSize, + height: tileSize, + file: `img-${filecounter++}.png` + }); + continue; + } const desired: TileBounds = new TileBounds( xs - tileOverlap, xs + tileSize + tileOverlap, @@ -662,7 +704,7 @@ const extrapolateDimension: ( }; Begin computing zoom tiers...\n`); const retHeightMap: CZIHeightMap[] = [baseCZIHeightMap]; - writeJSONToFile(`${outputImageData}stageMap-${cVal}-${0}`, retHeightMap); + writeJSONToFile(`${outputImageData}intermediate-stage-map.json`, retHeightMap); for (let stage: number = 1; stage <= Math.log2(maxZoom); stage++) { console.log(`Stage (${cVal * Math.log2(maxZoom) + 1 + stage}/${totalCs}):`); await zoomTier(retHeightMap[stage - 1]) @@ -671,7 +713,7 @@ const extrapolateDimension: ( return; } ); - writeJSONToFile(`${outputImageData}stageMap-${cVal}-${stage}`, retHeightMap); + writeJSONToFile(`${outputImageData}intermediate-stage-map.json`, retHeightMap); } console.log(`>> Completed Extrapolation for dimension, \'C\': ${cVal}\n\n`); @@ -706,7 +748,7 @@ const createSupportedViewsObject: () => void = (): void => { const buildCustomPyramids: () => Promise = async(): Promise => { // Set some variables for errors and and percent counts let errorOccurred: Boolean; - finalCZIJson.zoom_level_count = Math.log2(maxZoom); + finalCZIJson.zoom_level_count = Math.log2(maxZoom) + 1; // For all channels in the base image for (const cval of supportedViews.scalable_image.channels) { diff --git a/src/conversion/leica/scn.ts b/src/conversion/leica/scn.ts index e2125e1..b235a79 100644 --- a/src/conversion/leica/scn.ts +++ b/src/conversion/leica/scn.ts @@ -2,7 +2,7 @@ import * as fs from 'fs'; import * as sharp from 'sharp'; // tslint:disable-next-line:no-duplicate-imports import { SharpInstance } from 'sharp'; -import { SupportedViews, TileBounds, writeJSONToFile, checkForOutputDirectories } from '../types/helpers'; +import { SupportedViews, TileBounds, writeJSONToFile, checkForOutputDirectories, execpaths } from '../types/helpers'; import { uuid } from '../../uuid' import { logger } from '../../logger'; @@ -14,13 +14,12 @@ const baseDirname: string = '/cs/scratch/cjd24/tifers/'; // Various constants for placing files and defining tiles const extensionBinariesDir: string = __dirname + `/../../../ext/bin/`; -const execpaths: string = `PATH="$PATH:${extensionBinariesDir}" LD_LIBRARY_PATH="$LD_LIBRARY_PATH:${extensionBinariesDir}../lib/" `; const tileOverlap: number = 0; // Overlap is only half implemented const tileSize: number = 512; -const crunchLeica: () => void = async (): Promise => { +const crunchLeica: () => Promise = async (): Promise => { try { let output: string =`${baseDirname}${uuid.generate()}/`; @@ -84,17 +83,13 @@ const crunchLeica: () => void = async (): Promise => { }) .toFile(`${output}output.dzi`); logger.success(`Finalised output of ${input} as .dzi`); + return `${output}output.dzi`; } catch (err) { logger.failure(`Lecia conversion failed with error: ${err}`) + return `Lecia conversion failed with error: ${err}`; } }; -/** - * Main function used to call the rest of the relevant code to crunch a CZI - * extraction. - */ -const main: () => void = (): void => { - crunchLeica(); -}; -main(); + +crunchLeica().then((ret:string) => console.log(ret)); -- cgit v1.2.1 From d6aab3a101ff855043f0a5a4b870d84a13f85dfc Mon Sep 17 00:00:00 2001 From: cjd24 Date: Sat, 21 Apr 2018 23:20:45 +0100 Subject: WORKING VERSION OF CONVERSIONgit add src/conversion/leica/scn.ts git add src/conversion/leica/scn.ts ! --- src/conversion/czi/czi.ts | 6 ++++-- src/conversion/leica/scn.ts | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index c453a23..b128fa3 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -729,7 +729,9 @@ const createSupportedViewsObject: () => void = (): void => { parseExtractedXML(`${extractionDirectory}FILE-META-1.xml`); // Create the total supported Views object - writeJSONToFile(`${outputImageData}supported_views.json`, supportedViews); + // !!!!! This line was removed in order to reduce the output file size and + // !!!!! increase the usability by only giving the striped down version + // writeJSONToFile(`${outputImageData}supported_views.json`, supportedViews); // Cleanup and create "smart" supported views object without whole metadata cleanSupportedViews(supportedViews); @@ -739,7 +741,7 @@ const createSupportedViewsObject: () => void = (): void => { tile_overlap: tileOverlap }; writeJSONToFile( - `${outputImageData}supported_views_minus_xml.json`, supportedViews); + `${outputImageData}supported_views.json`, supportedViews); }; /** diff --git a/src/conversion/leica/scn.ts b/src/conversion/leica/scn.ts index b235a79..5d75cb3 100644 --- a/src/conversion/leica/scn.ts +++ b/src/conversion/leica/scn.ts @@ -7,7 +7,7 @@ import { uuid } from '../../uuid' import { logger } from '../../logger'; // CHANGE ME FOR TESTING!!!!! -const input: string = "test.tiff" +const input: string = "diseessse1.scn" const baseDirname: string = '/cs/scratch/cjd24/tifers/'; @@ -81,7 +81,7 @@ const crunchLeica: () => Promise = async (): Promise => { overlap: tileOverlap, layout: "dz" }) - .toFile(`${output}output.dzi`); + .toFile(`${output}output`); logger.success(`Finalised output of ${input} as .dzi`); return `${output}output.dzi`; } -- cgit v1.2.1 From be331a19ef57600efe69aa0edcaf34a380c75988 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Sun, 22 Apr 2018 02:20:55 +0100 Subject: HOLY ASYNCHRONOUS FILE CONVERSION BATMAN --- src/conversion/czi/czi.ts | 179 +++++++++++++++++++++++----------------------- 1 file changed, 89 insertions(+), 90 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index b128fa3..650a931 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -11,6 +11,9 @@ import { isTileRelated, regionToExtract } from './tileExtraction'; import * as parsexml from 'xml-parser'; import { uuid } from '../../uuid' +const readFile = require('util').promisify(fs.readFile); +const exists = require('util').promisify(fs.exists); + // Various constants for placing files and defining tiles const baseDirname: string = '/cs/scratch/cjd24/0701-extraction'; const extractionDirectory: string = `${baseDirname}/`; @@ -20,8 +23,25 @@ const tileOverlap: number = 0; // Overlap is only half implemented const tileSize: number = 1024; const maxZoom: number = 64; const shell = require('shelljs'); -let filecounter: number = 0; +const finalCZIJson: WholeCZIHierarchy = { + c_value_count: 0, + total_files: 0, + complete: false, + c_values: [], + zoom_level_count: 0 +}; +const exec = (cmd: string) => { + return new Promise((res, rej) => { + shell.exec(cmd, (code: number, stdout: any, stderr: any) => { + if (code !== 0) { + rej(stdout); + } else { + res({ code , stdout, stderr }); + } + }) + }) +} /** * Simple function to find the tile bounds version of an original tile @@ -190,9 +210,9 @@ const findRegionToExtract: ( * into a new image */ const extractAndStitchChunks: ( - segments: Segment[][], desiredRegion: TileBounds, tmp: number + segments: Segment[][], desiredRegion: TileBounds ) => Promise = async( - segments: Segment[][], desiredRegion: TileBounds, tmp: number + segments: Segment[][], desiredRegion: TileBounds ): Promise => { // Create a buffer for the rows part of raw image data @@ -260,7 +280,7 @@ const findRegionToExtract: ( r: 0, g: 0, b: 0, - alpha: 0 + alpha: 1 }).extend({ top: 0, left: 0, @@ -282,7 +302,7 @@ const findRegionToExtract: ( width: tileSize, height: tileSize, channels: 4, - background: { r: 0, g: 0, b: 0, alpha: 0 } + background: { r: 0, g: 0, b: 0, alpha: 1 } } }).overlayWith(await finalImage.toBuffer()) } else { @@ -406,10 +426,10 @@ supportedViews.scalable_image.channels.pop(); * Function to parse the xml file from the original extraction from CZI, * its nasty! */ -const parseExtractedXML: (xmlFile: string) => void = ( +const parseExtractedXML: (xmlFile: string) => void = async( xmlFile: string -): void => { - const metaXML: parsexml.Document = parsexml(fs.readFileSync(xmlFile, 'utf8')); +): Promise => { + const metaXML: parsexml.Document = parsexml(await readFile(xmlFile, 'utf8')); // Parse the XML :( // THE FOLLOWING 2 FOR LOOPS ARE DISGUSTING AND I HATE IT, // AND I WISH I DIDNT WRITE IT BUT DON'T SEE ANY OTHER WAY TO DO IT LOL :'( @@ -492,14 +512,11 @@ const parseExtractedXML: (xmlFile: string) => void = ( * This is used to create the next zoomed out tier of the given height map */ const zoomTier: ( - previousHeightMap: CZIHeightMap + previousHeightMap: CZIHeightMap, p: number ) => Promise = async( - previousHeightMap: CZIHeightMap + previousHeightMap: CZIHeightMap, p: number ): Promise => { - let ys: number = 0; - let timing: [number, number] = process.hrtime(); - const iterTimes: number[] = [50]; - let avgItrTime: number; + const newZoomTier: CZIHeightMap = { zoom_level: previousHeightMap.zoom_level * 2, plane: [] }; @@ -518,10 +535,8 @@ const zoomTier: ( let quadrentCount: number; // For all rows within the previous plane - for (; ys < previousHeightMap.plane.length; ys += 2) { - timing = process.hrtime(); + for (let ys: number = 0; ys < previousHeightMap.plane.length; ys += 2) { const cziRow: CZITile[] = []; - let rowProgBar: string = `${Math.ceil(previousHeightMap.plane[0].length / 2)} : `, rowProgCount: number = 0; // For all columns within the previous plane for (let xs: number = 0; xs < previousHeightMap.plane[0].length; xs += 2) { @@ -551,7 +566,8 @@ const zoomTier: ( let outputFileName: string =`${outputImageData}tmp/${uuid.generate()}.png`; // console.log(quadrents); - shell.exec(`${execpaths} vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`); + + await exec(`${execpaths} vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`); // Rescale and push to file if (quadrentCount !== 3) { @@ -564,17 +580,17 @@ const zoomTier: ( } sharp(await sharp(outputFileName) - .background({r: 0, g: 0, b: 0, alpha: 0}) + .background({r: 0, g: 0, b: 0, alpha: 1}) .extend({ top: 0, left: 0, bottom: extBottom, right: extRight }).toBuffer()) .resize(tileSize, tileSize) - .toFile(`${outputImageDirectory}img-${filecounter}.png`); + .toFile(`${outputImageDirectory}img-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`); } else { await sharp(outputFileName) .resize(tileSize, tileSize) - .toFile(`${outputImageDirectory}img-${filecounter}.png`); + .toFile(`${outputImageDirectory}img-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`); } shell.rm(outputFileName); @@ -583,7 +599,7 @@ const zoomTier: ( y_offset: previousHeightMap.plane[ys][xs].y_offset, width: previousHeightMap.plane[ys][xs].width * 2, height: previousHeightMap.plane[ys][xs].height * 2, - file: `img-${filecounter++}.png` + file: `img-p${p}-y${ys * tileSize}-x${xs * tileSize}.png` }); finalCZIJson.total_files++; rowProgBar += ">"; rowProgCount++; @@ -591,20 +607,13 @@ const zoomTier: ( } newZoomTier.plane.push(cziRow); - timing = process.hrtime(timing); - iterTimes.push(timing[0]); - if (iterTimes.length > 5) { iterTimes.shift(); } // tslint:disable-next-line:typedef - avgItrTime = iterTimes.reduce((p, c, i) => p + (c - p) / (i + 1), 0); process.stdout.write("\r"); console.log( ` Task(${ys / 2 + 1}/${ Math.floor(previousHeightMap.plane.length / 2) + 1}): ` + `Stage ${Math.ceil(((ys / previousHeightMap.plane.length) - * 100) * 100) / 100}% complete. ` + - `(${timing[0]} sec/iter, est: ${((avgItrTime * - ((Math.floor(previousHeightMap.plane.length / 2) + 1) - - (ys / 2 + 1))) / 60).toFixed(2)} mins remain.)` + * 100) * 100) / 100}% complete. ` ); } newZoomTier.tile_height_count = newZoomTier.plane.length; @@ -622,38 +631,20 @@ const extrapolateDimension: ( ) => Promise = async( cVal: number, totalCs: number, maxZoom: number ): Promise => { - let ys: number = 0; - let timing: [number, number] = process.hrtime(); - const iterTimes: number[] = [100]; - let avgItrTime: number; - const filteredDataBlocks: Segment[] = dataBlocks.filter( - (item: Segment, index: number, array: Segment[]) => - getDimension(item, 'C').Start === cVal - ); - // Begin output for the base tier - console.log('========================================================='); - console.log(`>> Beginning Dimension Extrapolation for \'C\' : ${cVal}`); - console.log('========================================================='); - console.log('>> Computing base tier, this will take a while...\n'); - const baseCZIHeightMap: CZIHeightMap = {zoom_level: 1, plane: []}; - console.log(`Stage (${cVal * Math.log2(maxZoom) + 1}/${totalCs}):`); - // For all rows within the total base pixel height - for (; ys < totalSizeY;) { - timing = process.hrtime(); - const cziRow: CZITile[] = []; - let rowProgBar: string = `${Math.ceil(totalSizeX/tileSize)} : `, rowProgCount: number = 0; - for (let xs: number = 0; xs < totalSizeX; xs += tileSize) { - if (fs.existsSync(`${outputImageDirectory}img-${filecounter}.png`) && (ys + tileSize < totalSizeY)) { + const doOneRow = (ys: number, filteredDataBlocks: Segment[]): Promise => { + + const doOneBaseTile = async(xs: number, ys: number, filteredDataBlocks: Segment[]): Promise => { + if (await exists(`${outputImageDirectory}img-p0-y${ys}-x${xs}.png`) && (ys + tileSize < totalSizeY)) { ///////////////////////////////////////////////////////////////////////////////////This if statement should be temporary??????????????????????????????????/ - cziRow.push({ + finalCZIJson.total_files++; + return { x_offset: xs, y_offset: ys, width: tileSize, height: tileSize, - file: `img-${filecounter++}.png` - }); - continue; + file: `img-p0-y${ys}-x${xs}.png` + }; } const desired: TileBounds = new TileBounds( xs - tileOverlap, @@ -662,40 +653,55 @@ const extrapolateDimension: ( ys + tileSize + tileOverlap ); - cziRow.push({ + const sortedSegments: Segment[][] = + orderSegments(findRelatedTiles(filteredDataBlocks, desired)); + + (await extractAndStitchChunks(sortedSegments, desired)) + .toFile(`${outputImageDirectory}img-p0-y${ys}-x${xs}.png`); + + return { x_offset: xs, y_offset: ys, width: tileSize, height: tileSize, - file: `img-${filecounter}.png` - }); - const sortedSegments: Segment[][] = - orderSegments(findRelatedTiles(filteredDataBlocks, desired)); + file: `img-p0-y${ys}-x${xs}.png` + }; + } - (await extractAndStitchChunks(sortedSegments, desired, filecounter)) - .toFile(`${outputImageDirectory}img-${filecounter++}.png`); -// shell.exec(`${execpaths} vips addalpha "${outputImageDirectory}img-${filecounter}" "${outputImageDirectory}img-${filecounter++}"`); + const rowPromises: Promise[] = []; - rowProgBar += ">"; rowProgCount++; - process.stdout.write(`\r${rowProgBar} ${rowProgCount}`); + for (let xs: number = 0; xs < totalSizeX; xs += tileSize) { + rowPromises.push(doOneBaseTile(xs, ys, filteredDataBlocks)); finalCZIJson.total_files++; } - baseCZIHeightMap.plane.push(cziRow); - ys += tileSize; - timing = process.hrtime(timing); - iterTimes.push(timing[0]); - if (iterTimes.length > 5) { iterTimes.shift(); } - // tslint:disable-next-line:typedef - avgItrTime = iterTimes.reduce((p, c, i) => p + (c - p) / (i + 1), 0); + + return Promise.all(rowPromises); + } + + const filteredDataBlocks: Segment[] = dataBlocks.filter( + (item: Segment, index: number, array: Segment[]) => + getDimension(item, 'C').Start === cVal + ); + // Begin output for the base tier + console.log('========================================================='); + console.log(`>> Beginning Dimension Extrapolation for \'C\' : ${cVal}`); + console.log('========================================================='); + console.log('>> Computing base tier, this will take a while...\n'); + const baseCZIHeightMap: CZIHeightMap = {zoom_level: 1, plane: []}; + + console.log(`Stage (${cVal * Math.log2(maxZoom) + 1}/${totalCs}):`); + // For all rows within the total base pixel height + const plane: CZITile[][] = []; + for (let ys: number = 0; ys < totalSizeY; ys += tileSize) { + plane.push(await doOneRow(ys, filteredDataBlocks)); + process.stdout.write("\r"); console.log( ` Task(${ys / tileSize}/${Math.ceil(totalSizeY / tileSize)}): ` + - `Stage ${Math.ceil(((ys / totalSizeY) * 100) * 100) / 100}% complete. ` + - `(${timing[0]} sec/iter, est: ${((avgItrTime * - (Math.ceil(totalSizeY / tileSize) - ys / tileSize)) / - 60).toFixed(2)} mins remain.)` + `Stage ${Math.ceil(((ys / totalSizeY) * 100) * 100) / 100}% complete. ` ); } + baseCZIHeightMap.plane = await Promise.all(plane); baseCZIHeightMap.tile_height_count = baseCZIHeightMap.plane.length; baseCZIHeightMap.tile_width_count = baseCZIHeightMap.plane[0].length; @@ -707,7 +713,7 @@ const extrapolateDimension: ( writeJSONToFile(`${outputImageData}intermediate-stage-map.json`, retHeightMap); for (let stage: number = 1; stage <= Math.log2(maxZoom); stage++) { console.log(`Stage (${cVal * Math.log2(maxZoom) + 1 + stage}/${totalCs}):`); - await zoomTier(retHeightMap[stage - 1]) + await zoomTier(retHeightMap[stage - 1], stage) .then((v: CZIHeightMap) => { retHeightMap.push(v); return; @@ -724,9 +730,9 @@ const extrapolateDimension: ( /** * used to write the supported views object to file both in total and "cleaned" */ -const createSupportedViewsObject: () => void = (): void => { +const createSupportedViewsObject: () => void = async(): Promise => { // Parse the xml - parseExtractedXML(`${extractionDirectory}FILE-META-1.xml`); + await parseExtractedXML(`${extractionDirectory}FILE-META-1.xml`); // Create the total supported Views object // !!!!! This line was removed in order to reduce the output file size and @@ -754,6 +760,7 @@ const buildCustomPyramids: () => Promise = async(): Promise => { // For all channels in the base image for (const cval of supportedViews.scalable_image.channels) { + errorOccurred = false; if (!errorOccurred) { // Extract the base tiles and build up custom pyramid data @@ -784,26 +791,18 @@ const buildCustomPyramids: () => Promise = async(): Promise => { finalCZIJson.complete = true; }; -const finalCZIJson: WholeCZIHierarchy = { - c_value_count: 0, - total_files: 0, - complete: false, - c_values: [], - zoom_level_count: 0 -}; - /** * Main function used to call the rest of the relevant code to crunch a CZI * extraction. */ -const main: () => void = (): void => { +const main: () => Promise = async (): Promise => { console.log('\n'); console.log('>> Checking/Creating output directories...'); checkForOutputDirectories([outputImageData, outputImageDirectory, `${outputImageData}tmp/`]); console.log('>> Creating Supported Views and writing files...'); - createSupportedViewsObject(); + await createSupportedViewsObject(); console.log(''); buildCustomPyramids(); -- cgit v1.2.1 From c26efcd5f8cf82d062c260bb9751f49e5827cb17 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Sun, 22 Apr 2018 10:10:14 +0100 Subject: Backing up - compressed the shellscript into node, and made some other unification changes. Also made the ZoomTiers be async for batman, and found and maaaayyyybe squashed a few super critical bugs - needs a final full run validation test though which takes too long :( --- src/conversion/czi/czi.ts | 263 ++++++++++++++++++----------- src/conversion/czi/cziconvert.c | 14 +- src/conversion/types/customPyramidIndex.ts | 2 +- 3 files changed, 164 insertions(+), 115 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index 650a931..429f60d 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -12,13 +12,14 @@ import * as parsexml from 'xml-parser'; import { uuid } from '../../uuid' const readFile = require('util').promisify(fs.readFile); +const readdir = require('util').promisify(fs.readdir); const exists = require('util').promisify(fs.exists); // Various constants for placing files and defining tiles -const baseDirname: string = '/cs/scratch/cjd24/0701-extraction'; -const extractionDirectory: string = `${baseDirname}/`; -const outputImageData: string = `${baseDirname}-processed/`; -const outputImageDirectory: string = `${baseDirname}-processed/data/`; +const testFile: string = '/cs/scratch/cjd24/0701.czi' +let extractDirectory: string = ""; +let outputImageData: string = ""; +let outputImageDirectory: string = ""; const tileOverlap: number = 0; // Overlap is only half implemented const tileSize: number = 1024; const maxZoom: number = 64; @@ -30,18 +31,7 @@ const finalCZIJson: WholeCZIHierarchy = { c_values: [], zoom_level_count: 0 }; - -const exec = (cmd: string) => { - return new Promise((res, rej) => { - shell.exec(cmd, (code: number, stdout: any, stderr: any) => { - if (code !== 0) { - rej(stdout); - } else { - res({ code , stdout, stderr }); - } - }) - }) -} +let dataBlocks: Segment[] = []; /** * Simple function to find the tile bounds version of an original tile @@ -229,8 +219,8 @@ const findRegionToExtract: ( // Find out the region of the base tile to be added to the new image chunkToExtract = findRegionToExtract(segCol, desiredRegion); // Extract this section of image data into a sharp buffer - const data: Promise = - sharp(`${extractionDirectory}${segCol.Data.Data}`) + let data: Promise = + sharp(`${extractDirectory}${segCol.Data.Data}`) .extract({ left: chunkToExtract.left, top: chunkToExtract.top, @@ -395,17 +385,6 @@ const cleanSupportedViews: (view: SupportedViews) => void = ( } }; -/** - * Create the objects needed for parsing the XML object - * of the initial extraction. - */ -// tslint:disable-next-line:no-var-requires -const dataBlocks: Segment[] = - require(`${extractionDirectory}outputjson.json`) - .czi.filter((s: Segment) => - s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty' - ); - let totalSizeX: number = -1; let totalSizeY: number = -1; const supportedViews: SupportedViews = { @@ -512,62 +491,50 @@ const parseExtractedXML: (xmlFile: string) => void = async( * This is used to create the next zoomed out tier of the given height map */ const zoomTier: ( - previousHeightMap: CZIHeightMap, p: number + previousHeightMap: CZIHeightMap, p: number, c: number ) => Promise = async( - previousHeightMap: CZIHeightMap, p: number + previousHeightMap: CZIHeightMap, p: number, c: number ): Promise => { - const newZoomTier: CZIHeightMap = { - zoom_level: previousHeightMap.zoom_level * 2, plane: [] - }; - - // Check the condition where another zoom level does not make sense - if (previousHeightMap.plane.length === 1 - && previousHeightMap.plane[0].length === 1) { - console.log( - ' Task(1/1): ' + - 'Stage 100% complete. ' + - '(0 sec/iter) Stage was skipped as maximum sensible zoom level was reached.' - ); - return previousHeightMap; - } - - let quadrentCount: number; - - // For all rows within the previous plane - for (let ys: number = 0; ys < previousHeightMap.plane.length; ys += 2) { - const cziRow: CZITile[] = []; - // For all columns within the previous plane - for (let xs: number = 0; xs < previousHeightMap.plane[0].length; xs += 2) { + const squashRow = async (previousPlane: CZITile[][], ys: number, p: number): Promise => { + + const squashQuad = async (previousPlane: CZITile[][], ys: number, xs: number, p: number): Promise => { + if (await exists(`${outputImageDirectory}img-c${c}-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`) && (ys < previousPlane.length)) { + finalCZIJson.total_files++; + return { + x_offset: xs * tileSize, + y_offset: ys * tileSize, + width: tileSize, + height: tileSize, + file: `img-c${c}-p${p}-y${ys}-x${xs}.png` + }; + } // Combine 4 tiles into a new tile and scale down for this tier // Top left - let quadrents:string = `${outputImageDirectory}${previousHeightMap.plane[ys][xs].file} `; + let quadrents:string = `${outputImageDirectory}${previousPlane[ys][xs].file} `; let across:number = 1; - quadrentCount = 1; + let quadrentCount: number = 1; // Combine top right - const moreToRight: boolean = (xs + 1) < previousHeightMap.plane[0].length; + const moreToRight: boolean = (xs + 1) < previousPlane[0].length; if (moreToRight) { - quadrents += `${outputImageDirectory}${previousHeightMap.plane[ys][xs + 1].file} `; - across++; - quadrentCount++; + quadrents += `${outputImageDirectory}${previousPlane[ys][xs + 1].file} `; + across++; quadrentCount++; } // Combine bottom left - const moreToBottom: boolean = (ys + 1) < previousHeightMap.plane.length; + const moreToBottom: boolean = (ys + 1) < previousPlane.length; if (moreToBottom) { - quadrents += `${outputImageDirectory}${previousHeightMap.plane[ys + 1][xs].file} `; + quadrents += `${outputImageDirectory}${previousPlane[ys + 1][xs].file} `; quadrentCount++; } // Combine bottom right if (moreToBottom && moreToRight) { - quadrents += `${outputImageDirectory}${previousHeightMap.plane[ys + 1][xs + 1].file} `; + quadrents += `${outputImageDirectory}${previousPlane[ys + 1][xs + 1].file} `; } - let outputFileName: string =`${outputImageData}tmp/${uuid.generate()}.png`; -// console.log(quadrents); - - await exec(`${execpaths} vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`); + let outputFileName: string =`${outputImageData}/tmp/${uuid.generate()}.png`; + shell.exec(`${execpaths} vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`, {silent: true}); // Rescale and push to file if (quadrentCount !== 3) { @@ -586,29 +553,53 @@ const zoomTier: ( bottom: extBottom, right: extRight }).toBuffer()) .resize(tileSize, tileSize) - .toFile(`${outputImageDirectory}img-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`); + .toFile(`${outputImageDirectory}img-c${c}-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`); } else { await sharp(outputFileName) .resize(tileSize, tileSize) - .toFile(`${outputImageDirectory}img-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`); + .toFile(`${outputImageDirectory}img-c${c}-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`); } - shell.rm(outputFileName); - - cziRow.push({ - x_offset: previousHeightMap.plane[ys][xs].x_offset, - y_offset: previousHeightMap.plane[ys][xs].y_offset, - width: previousHeightMap.plane[ys][xs].width * 2, - height: previousHeightMap.plane[ys][xs].height * 2, - file: `img-p${p}-y${ys * tileSize}-x${xs * tileSize}.png` - }); + shell.exec(`rm ${outputFileName}`, {silent: true}); + finalCZIJson.total_files++; - rowProgBar += ">"; rowProgCount++; - process.stdout.write(`\r${rowProgBar} ${rowProgCount}`); + return { + x_offset: previousPlane[ys][xs].x_offset, + y_offset: previousPlane[ys][xs].y_offset, + width: previousPlane[ys][xs].width * 2, + height: previousPlane[ys][xs].height * 2, + file: `img-c${c}-p${p}-y${ys * tileSize}-x${xs * tileSize}.png` + }; } - newZoomTier.plane.push(cziRow); - // tslint:disable-next-line:typedef - process.stdout.write("\r"); + const cziRow: Promise[] = []; + // For all columns within the previous plane + for (let xs: number = 0; xs < previousPlane[0].length; xs += 2) { + cziRow.push(squashQuad(previousPlane, ys, xs, p)); + } + + return await Promise.all(cziRow); + } + + const newZoomTier: CZIHeightMap = { + zoom_level: previousHeightMap.zoom_level * 2, plane: [] + }; + + // Check the condition where another zoom level does not make sense + if (previousHeightMap.plane.length === 1 + && previousHeightMap.plane[0].length === 1) { + console.log( + ' Task(1/1): ' + + 'Stage 100% complete. ' + + 'Stage was skipped as maximum sensible zoom level was reached.' + ); + return previousHeightMap; + } + + const newplane: CZITile[][] = []; + // For all rows within the previous plane + for (let ys: number = 0; ys < previousHeightMap.plane.length; ys += 2) { + newplane.push(await squashRow(previousHeightMap.plane, ys, p)); + console.log( ` Task(${ys / 2 + 1}/${ Math.floor(previousHeightMap.plane.length / 2) + 1}): ` + @@ -616,6 +607,8 @@ const zoomTier: ( * 100) * 100) / 100}% complete. ` ); } + + newZoomTier.plane = newplane; newZoomTier.tile_height_count = newZoomTier.plane.length; newZoomTier.tile_width_count = newZoomTier.plane[0].length; @@ -635,7 +628,7 @@ const extrapolateDimension: ( const doOneRow = (ys: number, filteredDataBlocks: Segment[]): Promise => { const doOneBaseTile = async(xs: number, ys: number, filteredDataBlocks: Segment[]): Promise => { - if (await exists(`${outputImageDirectory}img-p0-y${ys}-x${xs}.png`) && (ys + tileSize < totalSizeY)) { + if (await exists(`${outputImageDirectory}img-c${cVal}-p0-y${ys}-x${xs}.png`) && (ys + tileSize < totalSizeY)) { ///////////////////////////////////////////////////////////////////////////////////This if statement should be temporary??????????????????????????????????/ finalCZIJson.total_files++; return { @@ -643,7 +636,7 @@ const extrapolateDimension: ( y_offset: ys, width: tileSize, height: tileSize, - file: `img-p0-y${ys}-x${xs}.png` + file: `img-c${cVal}-p0-y${ys}-x${xs}.png` }; } const desired: TileBounds = new TileBounds( @@ -657,14 +650,14 @@ const extrapolateDimension: ( orderSegments(findRelatedTiles(filteredDataBlocks, desired)); (await extractAndStitchChunks(sortedSegments, desired)) - .toFile(`${outputImageDirectory}img-p0-y${ys}-x${xs}.png`); + .toFile(`${outputImageDirectory}img-c${cVal}-p0-y${ys}-x${xs}.png`); return { x_offset: xs, y_offset: ys, width: tileSize, height: tileSize, - file: `img-p0-y${ys}-x${xs}.png` + file: `img-c${cVal}-p0-y${ys}-x${xs}.png` }; } @@ -701,7 +694,7 @@ const extrapolateDimension: ( `Stage ${Math.ceil(((ys / totalSizeY) * 100) * 100) / 100}% complete. ` ); } - baseCZIHeightMap.plane = await Promise.all(plane); + baseCZIHeightMap.plane = plane; baseCZIHeightMap.tile_height_count = baseCZIHeightMap.plane.length; baseCZIHeightMap.tile_width_count = baseCZIHeightMap.plane[0].length; @@ -710,16 +703,16 @@ const extrapolateDimension: ( }; Begin computing zoom tiers...\n`); const retHeightMap: CZIHeightMap[] = [baseCZIHeightMap]; - writeJSONToFile(`${outputImageData}intermediate-stage-map.json`, retHeightMap); + writeJSONToFile(`${outputImageData}/intermediate-stage-map.json`, retHeightMap); for (let stage: number = 1; stage <= Math.log2(maxZoom); stage++) { console.log(`Stage (${cVal * Math.log2(maxZoom) + 1 + stage}/${totalCs}):`); - await zoomTier(retHeightMap[stage - 1], stage) + await zoomTier(retHeightMap[stage - 1], stage, cVal) .then((v: CZIHeightMap) => { retHeightMap.push(v); return; } ); - writeJSONToFile(`${outputImageData}intermediate-stage-map.json`, retHeightMap); + writeJSONToFile(`${outputImageData}/intermediate-stage-map.json`, retHeightMap); } console.log(`>> Completed Extrapolation for dimension, \'C\': ${cVal}\n\n`); @@ -731,13 +724,17 @@ const extrapolateDimension: ( * used to write the supported views object to file both in total and "cleaned" */ const createSupportedViewsObject: () => void = async(): Promise => { + dataBlocks = require(`${extractDirectory}outputjson.json`) + .czi.filter((s: Segment) => + s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty' + ); // Parse the xml - await parseExtractedXML(`${extractionDirectory}FILE-META-1.xml`); + await parseExtractedXML(`${extractDirectory}FILE-META-1.xml`); // Create the total supported Views object // !!!!! This line was removed in order to reduce the output file size and // !!!!! increase the usability by only giving the striped down version - // writeJSONToFile(`${outputImageData}supported_views.json`, supportedViews); + // writeJSONToFile(`${outputImageData}/supported_views.json`, supportedViews); // Cleanup and create "smart" supported views object without whole metadata cleanSupportedViews(supportedViews); @@ -747,15 +744,15 @@ const createSupportedViewsObject: () => void = async(): Promise => { tile_overlap: tileOverlap }; writeJSONToFile( - `${outputImageData}supported_views.json`, supportedViews); + `${outputImageData}/supported_views.json`, supportedViews); }; /** * Used to build up a pyramid for each value of c from the base images */ -const buildCustomPyramids: () => Promise = async(): Promise => { +const buildCustomPyramids: () => Promise = async(): Promise => { // Set some variables for errors and and percent counts - let errorOccurred: Boolean; + let errorOccurred: boolean = false; finalCZIJson.zoom_level_count = Math.log2(maxZoom) + 1; // For all channels in the base image @@ -786,11 +783,60 @@ const buildCustomPyramids: () => Promise = async(): Promise => { console.error('Skipping futher elements and moving to next dimension.\n\n'); } // Write the final json data to file with most recent changes - writeJSONToFile(`${outputImageData}layout.json`, finalCZIJson); + writeJSONToFile(`${outputImageData}/layout.json`, finalCZIJson); } finalCZIJson.complete = true; + return errorOccurred; }; +const initialExtractAndConvert: (absFilePath: string) => Promise = async (absFilePath: string): Promise => { + + outputImageData = `${absFilePath.split('.')[0]}-processed`; + extractDirectory = outputImageData + "/extract/"; + outputImageDirectory = outputImageData + "/data/"; + + checkForOutputDirectories([outputImageData, extractDirectory]); + console.log(">> This will complete at roughly 2GB/min"); + shell.exec(`${execpaths} CZICrunch ${absFilePath} ${extractDirectory}`); + + shell.exec(`${execpaths} python3 convertJxrs.py ${extractDirectory}`); + + // let totalFiles: number = 0, counter: number = 0; + // console.log("=========== BEGIN JXR CONVERSION ===========") + // + // let filenames: string[] = (await readdir(extractDirectory)).filter((x: string) => x.endsWith(".jxr")); + // counter = 0 + // totalFiles = filenames.length; + // + // const doOne: (n: number, file: string, asTif: string) => Promise = async(n: number, file: string, asTif: string): Promise => { + // shell.exec(`${execpaths} JxrDecApp -i ${file} -o ${asTif}`); + // shell.exec(`convert ${asTif} ${file.substring(0, file.lastIndexOf('.'))}.png`); + // shell.exec(`rm ${file} ${asTif}`); + // console.log (`> Processed File: ${n}/${totalFiles} : ${file} --> ${file.substring(0, file.lastIndexOf('.'))}.png`); + // } + // + // try { + // let promises: Promise[] = []; + // for (let index: number = 0; index < filenames.length; index++) { + // + // if (promises.length < 30) { + // let file = extractDirectory + filenames[index]; + // promises.push(doOne(counter++, file, file.substring(0, file.lastIndexOf('.')) + ".tif")); + // } else { + // index--; + // await Promise.all(promises); + // promises.length = 0; + // } + // } + // await Promise.all(promises); + // } catch (err) { + // console.log("Processing Failed. Probably couldn't find decoder due to invalid system environment path, check this before debugging. Actual Err:"); + // console.error(err); + // } + // console.log("=========== FINISH JXR CONVERSION ===========") +} + +process.on("warning", (err: any) => console.warn(err)) /** * Main function used to call the rest of the relevant code to crunch a CZI * extraction. @@ -798,14 +844,27 @@ const buildCustomPyramids: () => Promise = async(): Promise => { const main: () => Promise = async (): Promise => { console.log('\n'); - console.log('>> Checking/Creating output directories...'); - checkForOutputDirectories([outputImageData, outputImageDirectory, `${outputImageData}tmp/`]); + try { + console.log('>> Extracting from CZI and Converting to PNG'); + await initialExtractAndConvert(testFile); - console.log('>> Creating Supported Views and writing files...'); - await createSupportedViewsObject(); + console.log('\n>> Checking/Creating output directories...'); + checkForOutputDirectories([outputImageDirectory, `${outputImageData}/tmp/`]); - console.log(''); - buildCustomPyramids(); + console.log('\n>> Creating Supported Views and writing files...'); + await createSupportedViewsObject(); + + console.log('\n'); + if (await buildCustomPyramids()) { + console.log('>> Removing the initial extraction bloat'); + shell.exec(`rm -rf ${outputImageData}/extract/`, { async: true }) + }; + + console.log("\n>> Done"); + } catch (Err) { + console.error("This was a really big boi error, and something is sad: "); + console.error(Err); + } }; main(); diff --git a/src/conversion/czi/cziconvert.c b/src/conversion/czi/cziconvert.c index 85b925c..3024e7c 100644 --- a/src/conversion/czi/cziconvert.c +++ b/src/conversion/czi/cziconvert.c @@ -284,8 +284,8 @@ int functionRouter(FILE* imageFile, FILE* jsonOutput, long* fileOffset) { int main(int argc, char* argv[]) { //Check program input arguments. - if (argc < 2 || argc > 4) { - printf("Invalid number of arguments passed in.\nUsage:\n\n./prog \n\n"); + if (argc < 2 || argc > 3) { + printf("Invalid number of arguments passed in.\nUsage:\n\n./prog \n\n"); exit(1); } @@ -340,15 +340,5 @@ int main(int argc, char* argv[]) { fclose(jsonOutput); printf("\n=========== FINISH CZI EXTRACTION ===========\n\n\n\n"); - - //convert all the data's to jxr; - char jxrLoc[200]; - sprintf(jxrLoc, "%s %s %s", "python3", argv[3], argv[2]); - system(jxrLoc); - - - //begin work on re-factoring the image structure into a "smooth" grid - - return 0; } diff --git a/src/conversion/types/customPyramidIndex.ts b/src/conversion/types/customPyramidIndex.ts index 68df252..3c367b7 100644 --- a/src/conversion/types/customPyramidIndex.ts +++ b/src/conversion/types/customPyramidIndex.ts @@ -1,4 +1,4 @@ -import { TileBounds } from './helperCZITypes' +import { TileBounds } from './helpers' //The following are interfaces for the Custom object storing Information //about the CUSTOM pyramid being created for this image -- cgit v1.2.1 From 9c47bd66c75e6ec88bfc1ab1925dc8422f5ea4b7 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Mon, 23 Apr 2018 00:12:59 +0100 Subject: DO NOT USE, this is an intermediate commit to do sad last min stuff lol --- src/conversion/csv/excel.ts | 34 +++++++++++++++++++++++++++------- src/conversion/types/helpers.ts | 6 +++++- 2 files changed, 32 insertions(+), 8 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/csv/excel.ts b/src/conversion/csv/excel.ts index 2764192..e5b1c62 100644 --- a/src/conversion/csv/excel.ts +++ b/src/conversion/csv/excel.ts @@ -1,26 +1,46 @@ import { logger } from '../../logger'; import * as xlsx from 'xlsx'; import * as fs from 'fs'; +import { SupportedViews } from '../types/helpers'; +import * as csv from 'csv-parser'; // const testDir: string = `/cs/scratch/cjd24/csv/`; // const testFile: string = `test1.xlsx` +const generateProtoViews: (sheet: xlsx.WorkSheet) => SupportedViews = (sheet: xlsx.WorkSheet): SupportedViews => { + return { + tabular: { + columns: [''], + rows: sheet['!rows'].length; + } + } +} -const toCSV: (file: string) => Promise = async (file: string): Promise => { +const toCSV: (file: string) => Promise = async (file: string): Promise => { logger.info(`xls convertor received new file to convert to csv: ${file}`); + let shortFile: string = file.split('.')[0].split('/')[1]; + let path: string = file.split('/')[0] + '/'; let book: xlsx.WorkBook = xlsx.readFile(file); + try { - let sheetnames: string[] = []; + let views: any = {}; views.items = []; + for (let name of book.SheetNames) { - fs.writeFile(`${file.split('.')[0]}-${name}.csv`, xlsx.utils.sheet_to_csv(book.Sheets[name])); - sheetnames.push(`${file.split('.')[0]}-${name}.csv`); - logger.info(`Wrote ${file.split('.')[1]} subsheet {${file} : ${name}} as CSV.`); + await fs.writeFile(`${path}${shortFile}-${name}.csv`, xlsx.utils.sheet_to_csv(book.Sheets[name])); + views.items.push(name); + let parse = csv(`${path}${shortFile}-${name}.csv`); + + views[name] = generateProtoViews(book.Sheets[name]); + logger.info(`Wrote subsheet {${shortFile} : ${name}} as CSV.`); } - return sheetnames === [] ? ["__Empty_Book_Error"] : sheetnames; + fs.writeFile(`${path}${shortFile}-BASE.supported_views.json`, views[views.items[0]]); + await fs.writeFile(`${path}${shortFile}-ALL.supported_views.json`, views); + + return views.items === [] ? "__Empty_Book_Error" : `${path}${shortFile}-ALL.supported_views.json`; } catch (err) { logger.error(err); - return ["__Conversion_to_csv_Error_Occurred: " + err] + return "__conversion_to_csv_error_occurred: " + err } } diff --git a/src/conversion/types/helpers.ts b/src/conversion/types/helpers.ts index 8e07944..bb10e58 100644 --- a/src/conversion/types/helpers.ts +++ b/src/conversion/types/helpers.ts @@ -6,7 +6,7 @@ import { Node } from 'xml-parser'; * of the protocol specification for scalable images */ export interface SupportedViews { - scalable_image: { + scalable_image?: { width: number; height: number; channels: @@ -25,6 +25,10 @@ export interface SupportedViews { }; metadata?: {}; }; + tabular?: { + columns: string[]; + rows: number; + } } /** -- cgit v1.2.1 From fc0b2e57eb313774eb16c473208a15581e535001 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Mon, 23 Apr 2018 01:38:27 +0100 Subject: fixing stuff in the csv conversion and adding supported views capability --- src/conversion/csv/excel.ts | 154 +++++++++++++++++++------------------------- 1 file changed, 65 insertions(+), 89 deletions(-) (limited to 'src/conversion') diff --git a/src/conversion/csv/excel.ts b/src/conversion/csv/excel.ts index e5b1c62..1912109 100644 --- a/src/conversion/csv/excel.ts +++ b/src/conversion/csv/excel.ts @@ -1,117 +1,93 @@ import { logger } from '../../logger'; import * as xlsx from 'xlsx'; import * as fs from 'fs'; -import { SupportedViews } from '../types/helpers'; -import * as csv from 'csv-parser'; +import { SupportedViews, writeJSONToFile } from '../types/helpers'; +import * as csv from 'csv-parse'; -// const testDir: string = `/cs/scratch/cjd24/csv/`; -// const testFile: string = `test1.xlsx` +const writeFile = require('util').promisify(fs.writeFile); +const readFile = require('util').promisify(fs.readFile); -const generateProtoViews: (sheet: xlsx.WorkSheet) => SupportedViews = (sheet: xlsx.WorkSheet): SupportedViews => { - return { - tabular: { - columns: [''], - rows: sheet['!rows'].length; - } - } + +const supportedViewsFromMem: (content: string) => Promise = (content: string): Promise => { + return new Promise((res, rej) => { + csv(content, {}, function(err: any, output: any) { + res({ + tabular: { + columns: output[0], + rows: output.length - 1 + } + }); + }); + }); +} + +const supportedViewsFromDsk: (path: string) => Promise = async(path: string): Promise => { + return supportedViewsFromMem((await readFile(path)).toString()); } const toCSV: (file: string) => Promise = async (file: string): Promise => { - logger.info(`xls convertor received new file to convert to csv: ${file}`); + // logger.info(`xls convertor received new file to convert to csv: ${file}`); - let shortFile: string = file.split('.')[0].split('/')[1]; - let path: string = file.split('/')[0] + '/'; + let temp: string[] = file.split('.')[0].split('/'); + let shortFile: string = temp[temp.length - 1]; + let path: string = file.substring(0, file.lastIndexOf('/')) + '/'; let book: xlsx.WorkBook = xlsx.readFile(file); try { let views: any = {}; views.items = []; for (let name of book.SheetNames) { - await fs.writeFile(`${path}${shortFile}-${name}.csv`, xlsx.utils.sheet_to_csv(book.Sheets[name])); + let csvify:string = xlsx.utils.sheet_to_csv(book.Sheets[name]); + await writeFile(`${path}${shortFile}-${name}.csv`, csvify); views.items.push(name); - let parse = csv(`${path}${shortFile}-${name}.csv`); - - views[name] = generateProtoViews(book.Sheets[name]); - logger.info(`Wrote subsheet {${shortFile} : ${name}} as CSV.`); + views[name] = await supportedViewsFromMem(csvify); + // logger.info(`Wrote subsheet {${shortFile} : ${name}} as CSV.`); } - fs.writeFile(`${path}${shortFile}-BASE.supported_views.json`, views[views.items[0]]); - await fs.writeFile(`${path}${shortFile}-ALL.supported_views.json`, views); + writeJSONToFile(`${path}${shortFile}-BASE.supported_views.json`, views[views.items[0]]); + await writeJSONToFile(`${path}${shortFile}-ALL.supported_views.json`, views); return views.items === [] ? "__Empty_Book_Error" : `${path}${shortFile}-ALL.supported_views.json`; } catch (err) { - logger.error(err); + // logger.error(err); return "__conversion_to_csv_error_occurred: " + err } } -const toJSON: (file: string) => Promise = async (file: string): Promise => { - logger.info(`xls convertor received new file to convert to json: ${file}`); - - let book: xlsx.WorkBook = xlsx.readFile(file); - try { - let sheetnames: string[] = []; - for (let name of book.SheetNames) { - fs.writeFile(`${file.split('.')[0]}-${name}.json`, xlsx.utils.sheet_to_json(book.Sheets[name])); - sheetnames.push(`${file.split('.')[0]}-${name}.json`); - logger.info(`Wrote ${file.split('.')[1]} subsheet {${file} : ${name}} as JSON.`); - } - return sheetnames === [] ? ["__Empty_Book_Error"] : sheetnames; - } catch (err) { - logger.error(err); - return ["__Conversion_to_json_Error_Occurred: " + err] - } -} - -const toHTML: (file: string) => Promise = async (file: string): Promise => { - logger.info(`xls convertor received new file to convert to html: ${file}`); - let book: xlsx.WorkBook = xlsx.readFile(file); - try { - let sheetnames: string[] = []; - for (let name of book.SheetNames) { - fs.writeFile(`${file.split('.')[0]}-${name}.html`, xlsx.utils.sheet_to_html(book.Sheets[name])); - sheetnames.push(`${file.split('.')[0]}-${name}.html`); - logger.info(`Wrote ${file.split('.')[1]} subsheet {${file} : ${name}} as HTML.`); - } - return sheetnames === [] ? ["__Empty_Book_Error"] : sheetnames; - } catch (err) { - logger.error(err); - return ["__Conversion_to_html_Error_Occurred: " + err] - } -} +// const toAll: (file: string) => +// Promise<{csv: string, json: string, html: string}> = +// async (file: string): +// Promise<{csv: string, json: string, html: string}> => { +// return { +// csv: await toCSV(file).then(), +// html: await toCSV(file).then() +// } +// } +// -const toAll: (file: string) => -Promise<{csv: string[], json: string[], html: string[]}> = -async (file: string): -Promise<{csv: string[], json: string[], html: string[]}> => { - return { - csv: await toCSV(file), - json: await toCSV(file), - html: await toCSV(file) - } -} -// const main: () => void = async (): Promise => { -// -// try { -// let file: xlsx.WorkBook = xlsx.readFile(`${testDir}${testFile}`); -// -// for (let name of file.SheetNames) { -// fs.writeFileSync(`${testDir}${testFile.split('.')[0]}-${name}.csv`, xlsx.utils.sheet_to_csv(file.Sheets[name])); -// logger.info(`Wrote ${testFile.split('.')[1]} subsheet {${testFile} : ${name}} as CSV.`); -// fs.writeFileSync(`${testDir}${testFile.split('.')[0]}-${name}.json`, xlsx.utils.sheet_to_json(file.Sheets[name])); -// logger.info(`Wrote ${testFile.split('.')[1]} subsheet {${testFile} : ${name}} as json.`); -// fs.writeFileSync(`${testDir}${testFile.split('.')[0]}-${name}.html`, xlsx.utils.sheet_to_html(file.Sheets[name])); -// logger.info(`Wrote ${testFile.split('.')[1]} subsheet {${testFile} : ${name}} as HTML.`); -// } -// -// logger.success(`Wrote ${testFile.split('.')[1]} {${testFile}} as CSV.`); -// logger.success(`Wrote ${testFile.split('.')[1]} {${testFile}} as JSON.`); -// logger.success(`Wrote ${testFile.split('.')[1]} {${testFile}} as HTML.`); -// } catch (err) { -// // console.log(err); -// logger.error(err); -// } -// }; -// main(); +// const main: () => Promise = async (): Promise => { +// console.log(await toCSV('/cs/scratch/cjd24/t.xlsx')); +// } +// // try { +// // let file: xlsx.WorkBook = xlsx.readFile(`${testDir}${testFile}`); +// // +// // for (let name of file.SheetNames) { +// // fs.writeFileSync(`${testDir}${testFile.split('.')[0]}-${name}.csv`, xlsx.utils.sheet_to_csv(file.Sheets[name])); +// // logger.info(`Wrote ${testFile.split('.')[1]} subsheet {${testFile} : ${name}} as CSV.`); +// // fs.writeFileSync(`${testDir}${testFile.split('.')[0]}-${name}.json`, xlsx.utils.sheet_to_json(file.Sheets[name])); +// // logger.info(`Wrote ${testFile.split('.')[1]} subsheet {${testFile} : ${name}} as json.`); +// // fs.writeFileSync(`${testDir}${testFile.split('.')[0]}-${name}.html`, xlsx.utils.sheet_to_html(file.Sheets[name])); +// // logger.info(`Wrote ${testFile.split('.')[1]} subsheet {${testFile} : ${name}} as HTML.`); +// // } +// // +// // logger.success(`Wrote ${testFile.split('.')[1]} {${testFile}} as CSV.`); +// // logger.success(`Wrote ${testFile.split('.')[1]} {${testFile}} as JSON.`); +// // logger.success(`Wrote ${testFile.split('.')[1]} {${testFile}} as HTML.`); +// // } catch (err) { +// // // console.log(err); +// // logger.error(err); +// // } +// // }; +// main().then(); -- cgit v1.2.1