license import { DataType , keep , scalar , stack , Tensor , tidy , unstack , util } from '@tensorflow/tfjs-core' ; import * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter' ; /**
 * Hashtable contains a set of tensors, which can be accessed by key.
 */ export class HashTable { readonly handle : Tensor ; private tensorMap : Map < any , Tensor > ; get id ( ) { return this . handle . id ; } param keyDType param valueDType constructor ( readonly keyDType , readonly valueDType ) { this . handle = scalar ( 0 ) ; this . tensorMap = new Map < any , Tensor > ( ) ; keep ( this . handle ) ; } /**
     * Dispose the tensors and handle and clear the hashtable.
     */ clearAndClose ( ) { this . tensorMap . forEach ( value => value . dispose ( ) ) ; this . tensorMap . clear ( ) ; this . handle . dispose ( ) ; } /**
     * The number of items in the hash table.
     */ size ( ) { return this . tensorMap . size ; } /**
     * The number of items in the hash table as a rank-0 tensor.
     */ tensorSize ( ) { return tfOps . scalar ( this . size ( ) , 'int32' ) ; } param keys param values async import ( keys , values ) { this . checkKeyAndValueTensor ( keys , values ) ; const $keys = await keys . data ( ) ; this . tensorMap . forEach ( value => value . dispose ( ) ) ; this . tensorMap . clear ( ) ; return tidy ( ( ) => { const $values = unstack ( values ) ; const keysLength = $keys . length ; const valuesLength = $values . length ; util . assert ( keysLength === valuesLength , ( ) => `The number of elements doesn't match, keys has ` + `${ keysLength } elements, the values has ${ valuesLength } ` + `elements.` ) ; for ( let i = 0 ; i < keysLength ; i ++ ) { const key = $keys [ i ] ; const value = $values [ i ] ; keep ( value ) ; this . tensorMap . set ( key , value ) ; } return this . handle ; } ) ; } param keys param defaultValue async find ( keys , defaultValue ) { this . checkKeyAndValueTensor ( keys , defaultValue ) ; const $keys = await keys . data ( ) ; return tidy ( ( ) => { const result = [ ] ; for ( let i = 0 ; i < $keys . length ; i ++ ) { const key = $keys [ i ] ; const value = this . findWithDefault ( key , defaultValue ) ; result . push ( value ) ; } return stack ( result ) ; } ) ; } private findWithDefault ( key , defaultValue ) { const result = this . tensorMap . get ( key ) ; return result != null ? result : defaultValue ; } private checkKeyAndValueTensor ( key , value ) { if ( key . dtype !== this . keyDType ) { throw new Error ( `Expect key dtype ${ this . keyDType }, but got ` + `${ key . dtype }` ) ; } if ( value . dtype !== this . valueDType ) { throw new Error ( `Expect value dtype ${ this . valueDType }, but got ` + `${ value . dtype }` ) ; } } }