All files / Sources/Common/DataModel/ImageData index.js

65.17% Statements 131/201
38.8% Branches 26/67
73.91% Functions 17/23
64.39% Lines 123/191

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446                1x               361x   361x 290x         290x   290x       290x 580x     290x 290x 290x     290x   290x     361x         25x         25x 24x 24x 24x 24x 1x 1x 1x 1x           25x     361x           361x 2x 2x   2x 2x 2x                   361x 9x 9x     361x                                                                                                                                                                             361x 7435x   361x 7437x   361x 7544x     361x 869x   869x 869x 869x   869x 869x 869x   869x 869x 869x   869x   869x     361x 22x 22x   361x   361x 13x 13x   361x   361x     361x 3x     361x 361x   361x   361x 3x 3x   3x 3x 3x   3x 3x   3x   3x           3x             3x 3x   3x   3x 3x 3x 3x 3x   3x 153x 7803x 7803x 397953x 210681x   210681x 210681x 210681x 210681x 210681x     397953x         3x 3x     3x   3x                       361x                                 361x                                         361x                                           361x                                                       1x                         361x     361x   361x 347x 14x 12x     361x 361x     361x 361x 361x 361x     361x         1x          
import macro from 'vtk.js/Sources/macros';
import * as vtkMath from 'vtk.js/Sources/Common/Core/Math';
import vtkBoundingBox from 'vtk.js/Sources/Common/DataModel/BoundingBox';
import vtkDataSet from 'vtk.js/Sources/Common/DataModel/DataSet';
import vtkStructuredData from 'vtk.js/Sources/Common/DataModel/StructuredData';
import { StructuredType } from 'vtk.js/Sources/Common/DataModel/StructuredData/Constants';
import { vec3, mat3, mat4 } from 'gl-matrix';
 
const { vtkErrorMacro } = macro;
 
// ----------------------------------------------------------------------------
// vtkImageData methods
// ----------------------------------------------------------------------------
 
function vtkImageData(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkImageData');
 
  publicAPI.setExtent = (...inExtent) => {
    Iif (model.deleted) {
      vtkErrorMacro('instance deleted - cannot call any method');
      return false;
    }
 
    const extentArray = inExtent.length === 1 ? inExtent[0] : inExtent;
 
    Iif (extentArray.length !== 6) {
      return false;
    }
 
    const changeDetected = model.extent.some(
      (item, index) => item !== extentArray[index]
    );
 
    if (changeDetected) {
      model.extent = extentArray.slice();
      model.dataDescription = vtkStructuredData.getDataDescriptionFromExtent(
        model.extent
      );
      publicAPI.modified();
    }
    return changeDetected;
  };
 
  publicAPI.setDimensions = (...dims) => {
    let i;
    let j;
    let k;
 
    Iif (model.deleted) {
      vtkErrorMacro('instance deleted - cannot call any method');
      return;
    }
 
    if (dims.length === 1) {
      const array = dims[0];
      i = array[0];
      j = array[1];
      k = array[2];
    } else if (dims.length === 3) {
      i = dims[0];
      j = dims[1];
      k = dims[2];
    } else E{
      vtkErrorMacro('Bad dimension specification');
      return;
    }
 
    publicAPI.setExtent(0, i - 1, 0, j - 1, 0, k - 1);
  };
 
  publicAPI.getDimensions = () => [
    model.extent[1] - model.extent[0] + 1,
    model.extent[3] - model.extent[2] + 1,
    model.extent[5] - model.extent[4] + 1,
  ];
 
  publicAPI.getNumberOfCells = () => {
    const dims = publicAPI.getDimensions();
    let nCells = 1;
 
    for (let i = 0; i < 3; i++) {
      if (dims[i] === 0) {
        return 0;
      }
      if (dims[i] > 1) {
        nCells *= dims[i] - 1;
      }
    }
 
    return nCells;
  };
 
  publicAPI.getNumberOfPoints = () => {
    const dims = publicAPI.getDimensions();
    return dims[0] * dims[1] * dims[2];
  };
 
  publicAPI.getPoint = (index) => {
    const dims = publicAPI.getDimensions();
 
    if (dims[0] === 0 || dims[1] === 0 || dims[2] === 0) {
      vtkErrorMacro('Requesting a point from an empty image.');
      return null;
    }
 
    const ijk = new Float64Array(3);
 
    switch (model.dataDescription) {
      case StructuredType.EMPTY:
        return null;
 
      case StructuredType.SINGLE_POINT:
        break;
 
      case StructuredType.X_LINE:
        ijk[0] = index;
        break;
 
      case StructuredType.Y_LINE:
        ijk[1] = index;
        break;
 
      case StructuredType.Z_LINE:
        ijk[2] = index;
        break;
 
      case StructuredType.XY_PLANE:
        ijk[0] = index % dims[0];
        ijk[1] = index / dims[0];
        break;
 
      case StructuredType.YZ_PLANE:
        ijk[1] = index % dims[1];
        ijk[2] = index / dims[1];
        break;
 
      case StructuredType.XZ_PLANE:
        ijk[0] = index % dims[0];
        ijk[2] = index / dims[0];
        break;
 
      case StructuredType.XYZ_GRID:
        ijk[0] = index % dims[0];
        ijk[1] = (index / dims[0]) % dims[1];
        ijk[2] = index / (dims[0] * dims[1]);
        break;
 
      default:
        vtkErrorMacro('Invalid dataDescription');
        break;
    }
 
    const coords = [0, 0, 0];
    publicAPI.indexToWorld(ijk, coords);
    return coords;
  };
 
  // vtkCell *GetCell(vtkIdType cellId) VTK_OVERRIDE;
  // void GetCell(vtkIdType cellId, vtkGenericCell *cell) VTK_OVERRIDE;
  // void GetCellBounds(vtkIdType cellId, double bounds[6]) VTK_OVERRIDE;
  // virtual vtkIdType FindPoint(double x, double y, double z)
  // {
  //   return this->vtkDataSet::FindPoint(x, y, z);
  // }
  // vtkIdType FindPoint(double x[3]) VTK_OVERRIDE;
  // vtkIdType FindCell(
  //   double x[3], vtkCell *cell, vtkIdType cellId, double tol2,
  //   int& subId, double pcoords[3], double *weights) VTK_OVERRIDE;
  // vtkIdType FindCell(
  //   double x[3], vtkCell *cell, vtkGenericCell *gencell,
  //   vtkIdType cellId, double tol2, int& subId,
  //   double pcoords[3], double *weights) VTK_OVERRIDE;
  // vtkCell *FindAndGetCell(double x[3], vtkCell *cell, vtkIdType cellId,
  //                                 double tol2, int& subId, double pcoords[3],
  //                                 double *weights) VTK_OVERRIDE;
  // int GetCellType(vtkIdType cellId) VTK_OVERRIDE;
  // void GetCellPoints(vtkIdType cellId, vtkIdList *ptIds) VTK_OVERRIDE
  //   {vtkStructuredData::GetCellPoints(cellId,ptIds,this->DataDescription,
  //                                     this->GetDimensions());}
  // void GetPointCells(vtkIdType ptId, vtkIdList *cellIds) VTK_OVERRIDE
  //   {vtkStructuredData::GetPointCells(ptId,cellIds,this->GetDimensions());}
  // void ComputeBounds() VTK_OVERRIDE;
  // int GetMaxCellSize() VTK_OVERRIDE {return 8;}; //voxel is the largest
 
  publicAPI.getBounds = () =>
    publicAPI.extentToBounds(publicAPI.getSpatialExtent());
 
  publicAPI.extentToBounds = (ex) =>
    vtkBoundingBox.transformBounds(ex, model.indexToWorld);
 
  publicAPI.getSpatialExtent = () =>
    vtkBoundingBox.inflate([...model.extent], 0.5);
 
  // Internal, shouldn't need to call this manually.
  publicAPI.computeTransforms = () => {
    mat4.fromTranslation(model.indexToWorld, model.origin);
 
    model.indexToWorld[0] = model.direction[0];
    model.indexToWorld[1] = model.direction[1];
    model.indexToWorld[2] = model.direction[2];
 
    model.indexToWorld[4] = model.direction[3];
    model.indexToWorld[5] = model.direction[4];
    model.indexToWorld[6] = model.direction[5];
 
    model.indexToWorld[8] = model.direction[6];
    model.indexToWorld[9] = model.direction[7];
    model.indexToWorld[10] = model.direction[8];
 
    mat4.scale(model.indexToWorld, model.indexToWorld, model.spacing);
 
    mat4.invert(model.worldToIndex, model.indexToWorld);
  };
 
  publicAPI.indexToWorld = (ain, aout = []) => {
    vec3.transformMat4(aout, ain, model.indexToWorld);
    return aout;
  };
  publicAPI.indexToWorldVec3 = publicAPI.indexToWorld;
 
  publicAPI.worldToIndex = (ain, aout = []) => {
    vec3.transformMat4(aout, ain, model.worldToIndex);
    return aout;
  };
  publicAPI.worldToIndexVec3 = publicAPI.worldToIndex;
 
  publicAPI.indexToWorldBounds = (bin, bout = []) =>
    vtkBoundingBox.transformBounds(bin, model.indexToWorld, bout);
 
  publicAPI.worldToIndexBounds = (bin, bout = []) =>
    vtkBoundingBox.transformBounds(bin, model.worldToIndex, bout);
 
  // Make sure the transform is correct
  publicAPI.onModified(publicAPI.computeTransforms);
  publicAPI.computeTransforms();
 
  publicAPI.getCenter = () => vtkBoundingBox.getCenter(publicAPI.getBounds());
 
  publicAPI.computeHistogram = (worldBounds, voxelFunc = null) => {
    const bounds = [0, 0, 0, 0, 0, 0];
    publicAPI.worldToIndexBounds(worldBounds, bounds);
 
    const point1 = [0, 0, 0];
    const point2 = [0, 0, 0];
    vtkBoundingBox.computeCornerPoints(bounds, point1, point2);
 
    vtkMath.roundVector(point1, point1);
    vtkMath.roundVector(point2, point2);
 
    const dimensions = publicAPI.getDimensions();
 
    vtkMath.clampVector(
      point1,
      [0, 0, 0],
      [dimensions[0] - 1, dimensions[1] - 1, dimensions[2] - 1],
      point1
    );
    vtkMath.clampVector(
      point2,
      [0, 0, 0],
      [dimensions[0] - 1, dimensions[1] - 1, dimensions[2] - 1],
      point2
    );
 
    const yStride = dimensions[0];
    const zStride = dimensions[0] * dimensions[1];
 
    const pixels = publicAPI.getPointData().getScalars().getData();
 
    let maximum = -Infinity;
    let minimum = Infinity;
    let sumOfSquares = 0;
    let isum = 0;
    let inum = 0;
 
    for (let z = point1[2]; z <= point2[2]; z++) {
      for (let y = point1[1]; y <= point2[1]; y++) {
        let index = point1[0] + y * yStride + z * zStride;
        for (let x = point1[0]; x <= point2[0]; x++) {
          if (!voxelFunc || voxelFunc([x, y, z], bounds)) {
            const pixel = pixels[index];
 
            if (pixel > maximum) maximum = pixel;
            if (pixel < minimum) minimum = pixel;
            sumOfSquares += pixel * pixel;
            isum += pixel;
            inum += 1;
          }
 
          ++index;
        }
      }
    }
 
    const average = inum > 0 ? isum / inum : 0;
    const variance = inum
      ? Math.abs(sumOfSquares / inum - average * average)
      : 0;
    const sigma = Math.sqrt(variance);
 
    return {
      minimum,
      maximum,
      average,
      variance,
      sigma,
      count: inum,
    };
  };
 
  // TODO: use the unimplemented `vtkDataSetAttributes` for scalar length, that is currently also a TODO (GetNumberOfComponents).
  // Scalar data could be tuples for color information?
  publicAPI.computeIncrements = (extent, numberOfComponents = 1) => {
    const increments = [];
    let incr = numberOfComponents;
 
    // Calculate array increment offsets
    // similar to c++ vtkImageData::ComputeIncrements
    for (let idx = 0; idx < 3; ++idx) {
      increments[idx] = incr;
      incr *= extent[idx * 2 + 1] - extent[idx * 2] + 1;
    }
    return increments;
  };
 
  /**
   * @param {Number[]} index the localized `[i,j,k]` pixel array position. Float values will be rounded.
   * @return {Number} the corresponding flattened index in the scalar array
   */
  publicAPI.computeOffsetIndex = ([i, j, k]) => {
    const extent = publicAPI.getExtent();
    const numberOfComponents = publicAPI
      .getPointData()
      .getScalars()
      .getNumberOfComponents();
    const increments = publicAPI.computeIncrements(extent, numberOfComponents);
    // Use the array increments to find the pixel index
    // similar to c++ vtkImageData::GetArrayPointer
    // Math.floor to catch "practically 0" e^-15 scenarios.
    return Math.floor(
      (Math.round(i) - extent[0]) * increments[0] +
        (Math.round(j) - extent[2]) * increments[1] +
        (Math.round(k) - extent[4]) * increments[2]
    );
  };
 
  /**
   * @param {Number[]} xyz the [x,y,z] Array in world coordinates
   * @return {Number|NaN} the corresponding pixel's index in the scalar array
   */
  publicAPI.getOffsetIndexFromWorld = (xyz) => {
    const extent = publicAPI.getExtent();
    const index = publicAPI.worldToIndex(xyz);
 
    // Confirm indexed i,j,k coords are within the bounds of the volume
    for (let idx = 0; idx < 3; ++idx) {
      if (index[idx] < extent[idx * 2] || index[idx] > extent[idx * 2 + 1]) {
        vtkErrorMacro(
          `GetScalarPointer: Pixel ${index} is not in memory. Current extent = ${extent}`
        );
        return NaN;
      }
    }
 
    // Assumed the index here is within 0 <-> scalarData.length, but doesn't hurt to check upstream
    return publicAPI.computeOffsetIndex(index);
  };
  /**
   * @param {Number[]} xyz the [x,y,z] Array in world coordinates
   * @param {Number?} comp the scalar component index for multi-component scalars
   * @return {Number|NaN} the corresponding pixel's scalar value
   */
  publicAPI.getScalarValueFromWorld = (xyz, comp = 0) => {
    const numberOfComponents = publicAPI
      .getPointData()
      .getScalars()
      .getNumberOfComponents();
    if (comp < 0 || comp >= numberOfComponents) {
      vtkErrorMacro(
        `GetScalarPointer: Scalar Component ${comp} is not within bounds. Current Scalar numberOfComponents: ${numberOfComponents}`
      );
      return NaN;
    }
    const offsetIndex = publicAPI.getOffsetIndexFromWorld(xyz);
    if (Number.isNaN(offsetIndex)) {
      // VTK Error Macro will have been tripped already, no need to do it again,
      return offsetIndex;
    }
 
    return publicAPI
      .getPointData()
      .getScalars()
      .getComponent(offsetIndex, comp);
  };
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
const DEFAULT_VALUES = {
  direction: null, // a mat3
  indexToWorld: null, // a mat4
  worldToIndex: null, // a mat4
  spacing: [1.0, 1.0, 1.0],
  origin: [0.0, 0.0, 0.0],
  extent: [0, -1, 0, -1, 0, -1],
  dataDescription: StructuredType.EMPTY,
};
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);
 
  // Inheritance
  vtkDataSet.extend(publicAPI, model, initialValues);
 
  if (!model.direction) {
    model.direction = mat3.identity(new Float64Array(9));
  } else if (Array.isArray(model.direction)) {
    model.direction = new Float64Array(model.direction.slice(0, 9));
  }
 
  model.indexToWorld = new Float64Array(16);
  model.worldToIndex = new Float64Array(16);
 
  // Set/Get methods
  macro.get(publicAPI, model, ['indexToWorld', 'worldToIndex']);
  macro.setGetArray(publicAPI, model, ['origin', 'spacing'], 3);
  macro.setGetArray(publicAPI, model, ['direction'], 9);
  macro.getArray(publicAPI, model, ['extent'], 6);
 
  // Object specific methods
  vtkImageData(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(extend, 'vtkImageData');
 
// ----------------------------------------------------------------------------
 
export default { newInstance, extend };