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 +- 3 files changed, 493 insertions(+), 498 deletions(-) (limited to 'src/conversion/czi') 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]); -- cgit v1.2.1