Add Salesman Problem algorithms.

This commit is contained in:
Oleg Sh committed 2025-10-18 19:46:39 +02:00
1 parent 46c05d94fd
commit 31e676fd22
27 files changed
+386 -11

No files matched your search

+3 -1
View File
@@ -30,7 +30,9 @@ function loadAsyncAlgorithms(onFinish) {
"ShortestPath.js",
"VerticesDegree.js",
"MaxIndependentSet.js",
"FindAllShortestPatches.js"];
"FindAllShortestPatches.js",
"SalesmanProblem.js",
"SalesmanProblemPath.js"];
doIncludeAsync (pluginsList.map((plugin) => include ("model/plugins/" + plugin, modulDir)), onFinish);
}
@@ -0,0 +1,125 @@
/**
* Find Salesman Problem Loop.
*
*/
function SalesmanProblem(graph, app)
{
BaseAlgorithmEx.apply(this, arguments);
this.message = g_processing;
this.selectedObjects = [];
}
// inheritance.
SalesmanProblem.prototype = Object.create(BaseAlgorithmEx.prototype);
SalesmanProblem.prototype.getName = function(local)
{
return g_salesmanProblem;
}
SalesmanProblem.prototype.getId = function()
{
return "OlegSh.SalesmanProblem";
}
// @return message for user.
SalesmanProblem.prototype.getMessage = function(local)
{
return this.message;
}
SalesmanProblem.prototype.getCategory = function()
{
return 1;
}
SalesmanProblem.prototype.MaxGraphSize = function()
{
return 18;
}
SalesmanProblem.prototype.MaxEgdeNumber = function()
{
return 50;
}
SalesmanProblem.prototype.result = function(resultCallback)
{
this.outResultCallback = function (result ) { resultCallback(result); };
self = this;
this.CalculateAlgorithm("slsmen",
[
{name: "start", value: 0}
], function (pathObjects, properties, results)
{
self.resultCallback(pathObjects, properties, results);
});
return true;
}
SalesmanProblem.prototype.resultCallback = function(pathObjects, properties, results)
{
let result = results.length > 0 && results[0].value > 0 && results[0].type == 1;
let dist = results.length > 1 && (results[1].type == 1 || results[1].type == 2) ? results[1].value : 0;
var outputResult = {};
outputResult["version"] = 1;
this.message = result > 0 ? g_shortestLoopIs + (dist * 1).toString() : g_noSolution;
if (result > 0)
{
var nodesEdgesPath = this.GetNodesEdgesPath(results, 1, results.length - 1);
var nodesPath = this.GetNodesPath(results, 1, results.length - 1);
this.message = this.message + ": ";
outputResult["pathsWithEdges"] = [];
outputResult["pathsWithEdges"].push(nodesEdgesPath);
for (var i = 0; i < nodesPath.length; i++)
{
this.message = this.message + this.graph.FindVertex(nodesPath[i]).mainText + ((i < nodesPath.length - 1) ? "&rArr;" : "");
}
this.selectedObjects = [];
for (var i = 0; i < pathObjects.length; i++)
{
this.selectedObjects[pathObjects[i].id] = 1;
}
}
this.outResultCallback(outputResult);
}
SalesmanProblem.prototype.getObjectSelectedGroup = function(object)
{
return (object.id in this.selectedObjects) ? this.selectedObjects[object.id] : 0;
}
SalesmanProblem.prototype.getPriority = function()
{
return -1;
}
// Algorithm support multi graph
SalesmanProblem.prototype.IsSupportMultiGraph = function()
{
return false;
}
SalesmanProblem.prototype.IsSupportNegativeWeight = function()
{
return true;
}
// Factory for connected components.
function CreateSalesmanProblem(graph, app)
{
return new SalesmanProblem(graph, app)
}
// Gerister connected component.
RegisterAlgorithm (CreateSalesmanProblem);
@@ -0,0 +1,144 @@
/**
* Find Salesman Problem Path.
*
*/
function SalesmanProblemPath(graph, app)
{
BaseAlgorithmEx.apply(this, arguments);
this.message = g_startTraversal;
this.selectedObjects = [];
this.startVertex = null
}
// inheritance.
SalesmanProblemPath.prototype = Object.create(BaseAlgorithmEx.prototype);
SalesmanProblemPath.prototype.getName = function(local)
{
return g_salesmanProblemPath;
}
SalesmanProblemPath.prototype.getId = function()
{
return "OlegSh.SalesmanProblemPath";
}
// @return message for user.
SalesmanProblemPath.prototype.getMessage = function(local)
{
return this.message;
}
SalesmanProblemPath.prototype.getCategory = function()
{
return 1;
}
SalesmanProblemPath.prototype.MaxGraphSize = function()
{
return 20;
}
SalesmanProblemPath.prototype.MaxEgdeNumber = function()
{
return 50;
}
SalesmanProblemPath.prototype.result = function(resultCallback)
{
if (!this.startVertex)
{
return false;
}
this.outResultCallback = function (result ) { resultCallback(result); };
self = this;
this.CalculateAlgorithm("slsmenpath",
[
{name: "start", value: this.startVertex.id}
], function (pathObjects, properties, results)
{
self.resultCallback(pathObjects, properties, results);
});
this.startVertex = false;
return true;
}
SalesmanProblemPath.prototype.selectVertex = function(vertex)
{
this.startVertex = vertex;
this.message = g_processing;
return true;
}
SalesmanProblemPath.prototype.resultCallback = function(pathObjects, properties, results)
{
let result = results.length > 0 && results[0].value > 0 && results[0].type == 1;
let dist = results.length > 1 && (results[1].type == 1 || results[1].type == 2) ? results[1].value : 0;
var outputResult = {};
outputResult["version"] = 1;
this.message = result > 0 ? g_shortestPathIs + (dist * 1).toString() : g_noSolution;
if (result > 0)
{
var nodesEdgesPath = this.GetNodesEdgesPath(results, 1, results.length - 1);
var nodesPath = this.GetNodesPath(results, 1, results.length - 1);
this.message = this.message + ": ";
outputResult["pathsWithEdges"] = [];
outputResult["pathsWithEdges"].push(nodesEdgesPath);
for (var i = 0; i < nodesPath.length; i++)
{
this.message = this.message + this.graph.FindVertex(nodesPath[i]).mainText + ((i < nodesPath.length - 1) ? "&rArr;" : "");
}
this.selectedObjects = [];
for (var i = 0; i < pathObjects.length; i++)
{
this.selectedObjects[pathObjects[i].id] = 1;
}
}
this.outResultCallback(outputResult);
}
SalesmanProblemPath.prototype.getObjectSelectedGroup = function(object)
{
return (object.id in this.selectedObjects) ? this.selectedObjects[object.id] : 0;
}
SalesmanProblemPath.prototype.getPriority = function()
{
return -0.9;
}
// Algorithm support multi graph
SalesmanProblemPath.prototype.IsSupportMultiGraph = function()
{
return false;
}
SalesmanProblemPath.prototype.IsSupportNegativeWeight = function()
{
return true;
}
SalesmanProblemPath.prototype.instance = function()
{
return false;
}
// Factory for connected components.
function CreateSalesmanProblemPath(graph, app)
{
return new SalesmanProblemPath(graph, app)
}
// Gerister connected component.
RegisterAlgorithm (CreateSalesmanProblemPath);
@@ -1 +1 @@
var Module=typeof Module!="undefined"?Module:{};var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope!="undefined";var ENVIRONMENT_IS_NODE=typeof process=="object"&&process.versions?.node&&process.type!="renderer";var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=typeof document!="undefined"?document.currentScript?.src:undefined;if(typeof __filename!="undefined"){_scriptName=__filename}else if(ENVIRONMENT_IS_WORKER){_scriptName=self.location.href}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);if(typeof module!="undefined"){module["exports"]=Module}quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");var wasmMemory;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["o"]();FS.ignorePermissions=false}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}var runDependencies=0;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("Graphoffline.Emscripten.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiLine truncated
var Module=typeof Module!="undefined"?Module:{};var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=globalThis.document?.currentScript?.src;if(typeof __filename!="undefined"){_scriptName=__filename}else if(ENVIRONMENT_IS_WORKER){_scriptName=self.location.href}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);if(typeof module!="undefined"){module["exports"]=Module}quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["o"]();FS.ignorePermissions=false}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("Graphoffline.Emscripten.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){return receiveInstance(result["instance"]Line truncated