-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #64 from BruceDai/add_triangular
Implement triangular
- Loading branch information
Showing
3 changed files
with
507 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
'use strict'; | ||
|
||
import {Tensor, sizeOfShape} from './lib/tensor.js'; | ||
import {validateTriangularParams} from './lib/validate-input.js'; | ||
|
||
/** | ||
* Get retained boolean flag. | ||
* @param {Array} location | ||
* @param {Boolean} upper | ||
* @param {Number} diagonal | ||
* @return {Boolean} | ||
*/ | ||
function isRetainedValue(location, upper, diagonal) { | ||
const i = location[location.length - 2]; | ||
const j = location[location.length - 1]; | ||
return upper ? j >= i + diagonal : j <= i + diagonal; | ||
} | ||
|
||
/** | ||
* Given a 2-D tensor (matrix), return a 2-D tensor containing either the upper or lower triangular | ||
* part of the input tensor. | ||
* @param {Tensor} input | ||
* @param {MLTriangularOptions} [options] | ||
* @return {Tensor} | ||
*/ | ||
export function triangular(input, {upper = true, diagonal = 0} = {}) { | ||
validateTriangularParams(...arguments); | ||
const shapeOutput = input.shape.slice(); | ||
const output = new Tensor(shapeOutput); | ||
|
||
for (let outputIndex = 0; outputIndex < sizeOfShape(shapeOutput); ++outputIndex) { | ||
const outputLoc = output.locationFromIndex(outputIndex); | ||
const retainedFlag = isRetainedValue(outputLoc, upper, diagonal); | ||
const inputValue = retainedFlag ? input.getValueByLocation(outputLoc) : 0; | ||
output.setValueByLocation(outputLoc, inputValue); | ||
} | ||
|
||
return output; | ||
} |
Oops, something went wrong.