clustering-tfjs
Version:
High-performance TypeScript clustering algorithms (K-Means, Spectral, Agglomerative) with TensorFlow.js acceleration and scikit-learn compatibility
91 lines (90 loc) • 2.39 kB
JavaScript
/**
* TensorFlow.js backend manager
*
* Manages a singleton instance of TensorFlow.js with support for
* multiple backends and environments.
*/
// Singleton storage
let tfInstance = null;
let initializationPromise = null;
/**
* Initialize the TensorFlow.js backend
*/
export async function initializeBackend(config = {}) {
// Return existing instance if already initialized
if (tfInstance) {
return tfInstance;
}
// Return existing initialization promise if in progress
if (initializationPromise) {
return initializationPromise;
}
// Start initialization
initializationPromise = loadBackend(config);
try {
tfInstance = await initializationPromise;
return tfInstance;
}
catch (error) {
// Reset on error to allow retry
initializationPromise = null;
throw error;
}
}
/**
* Get the current TensorFlow instance
* @throws Error if not initialized
*/
export function getTensorFlow() {
if (!tfInstance) {
throw new Error('TensorFlow.js not initialized. Please call Clustering.init() first.');
}
return tfInstance;
}
/**
* Check if TensorFlow is initialized
*/
export function isInitialized() {
return tfInstance !== null;
}
/**
* Reset the backend (mainly for testing)
*/
export function resetBackend() {
tfInstance = null;
initializationPromise = null;
}
/**
* Load the appropriate backend based on environment and config
*/
async function loadBackend(config) {
// Detect environment
const isNode = typeof window === 'undefined' &&
typeof process !== 'undefined' &&
process.versions &&
process.versions.node;
let tf;
if (isNode) {
// Node.js environment
const loader = await import('./tf-loader.node');
tf = await loader.loadTensorFlow();
}
else {
// Browser environment
const loader = await import('./tf-loader.browser');
tf = await loader.loadTensorFlow();
}
// Set custom flags if provided
if (config.flags) {
Object.entries(config.flags).forEach(([flag, value]) => {
tf.env().setFlags({ [flag]: value });
});
}
// Set specific backend if requested
if (config.backend) {
await tf.setBackend(config.backend);
}
// Wait for backend to be ready
await tf.ready();
return tf;
}