omlSA.mjs

import map from 'lodash-es/map.js'
import cloneDeep from 'lodash-es/cloneDeep.js'
import isestr from 'wsemi/src/isestr.mjs'
import isfun from 'wsemi/src/isfun.mjs'
import ispm from 'wsemi/src/ispm.mjs'
import { kNum, kPint, kBol, kFun, chkParams } from './_checkParam.mjs'
import { kModeOutLimit } from './_optDecl.mjs'
import { kDps, kInitSolution } from './_validateDps.mjs'
import _genSolution from './_genSolution.mjs'
import _randPickNeighbor from './_randPickNeighbor.mjs'
import { _makeRandom } from './_random.mjs'


/**
 * 模擬退火(Simulated Annealing)
 *
 * 此版本同時支援「主演算法」與「LocalSearch helper」雙用途:
 * 主演算法不傳opt.initSolution,內部隨機初始化;LocalSearch傳opt.initSolution與opt.calcFitness(共享caller之iExecute counter)
 *
 * Unit Test: {@link https://github.com/yuda-lyu/w-optimization/blob/master/test/p2.omlSA.test.mjs Github}
 * @memberOf w-optimization
 * @param {Array} dps 輸入設計變數陣列,各元素為{ values: [可用值], n: 可用值數量 }。種類:非空陣列,必給;元素為一般物件,values為非空陣列(元素為可用值,任意值,由funFit自行解讀,不檢),n為有效數字,正整數(數字字串轉換後使用)且須等於values長度;不改寫呼叫端之陣列
 * @param {Function} funFit 輸入適應函數,將傳入各設計變數所取之值陣列,需回傳適應函數值,以求解最小值為目標。種類:函數,必給
 * @param {Object} [opt={}] 輸入設定物件,預設{}。種類:一般物件,undefined或null視為未給,其餘非一般物件為無效;未宣告之鍵忽略;各鍵給了而不符種類即為無效,不改用預設
 * @param {Number|String} [opt.Nl=10000] 輸入最大總迴圈數,預設10000。種類:有效數字,正整數
 * @param {Number|String} [opt.NContiguous=200] 輸入最大最佳解連續未更新次數,預設200。種類:有效數字,正整數
 * @param {Number|String} [opt.NCore=1000000] 輸入最大核心執行次數,預設1000000。種類:有效數字,正整數
 * @param {String} [opt.ModeOutLimit='Mapping'] 輸入設計變數指標超過範圍之處理方式,預設'Mapping'。種類:列舉字串,'Mapping'、'Limit'、'Random'
 * @param {Number|String} [opt.saInitialTemperature=100] 輸入初始溫度,預設100。種類:有效數字
 * @param {Number|String} [opt.saAlpha=0.9] 輸入溫度衰減係數(改善時T=α*T,越小衰減越快),預設0.9。種類:有效數字
 * @param {Boolean} [opt.UseHists=true] 輸入是否收集hists陣列,預設true。種類:布林,只收true或false('true'、'n'、1等皆為無效)
 * @param {Function} [opt.funGetBetter] 輸入有更優解出現時呼叫之函數,將傳入(最佳解,迴圈序號)。種類:函數
 * @param {Function} [opt.funEndLoop] 輸入每次主迴圈結束後呼叫之函數,將傳入(現解,最佳解,迴圈序號)。種類:函數
 * @param {Function} [opt.calcFitness] 輸入計算適應度之函數,供LocalSearch模式共享呼叫次數計數,將傳入(解物件,來源字串),需回傳{ ps, fitness }。種類:函數
 * @param {Object} [opt.initSolution] 輸入初始解(LocalSearch模式),不給則隨機初始化。種類:一般物件,ps為非空陣列(元素為本套件內部結構,不逐一檢測),fitness為適應函數值(數字或數字字串,轉換後使用,另收+-Infinity作為懲罰值)
 * @param {Function} [opt.random] 輸入亂數產生函數,須回傳[0,1)之數字(同Math.random之約定,回傳值不檢測)。給了則該次呼叫之一切隨機取值皆只經它,同題同選項同序列即得同結果(含適應函數被呼叫之序列),同一函數勿同時交給多個進行中之呼叫;未給(undefined或null)則用Math.random(取整數時用wsemi之randomIntRange)。種類:函數
 * @returns {Promise} 回傳Promise,resolve為結果物件,含鍵值bestSolution,hists,stopMode,stopNl,stopExecutions;輸入無效時reject字串,格式為`invalid <名稱>: must be <種類描述>`,不含輸入值
 */
async function omlSA(dps, funFit, opt = {}) {
    //Simulated Annealing, 模擬退火
    //此版本同時支援「主演算法」與「LocalSearch helper」雙用途:
    //  - 主演算法: 不傳opt.initSolution, 內部隨機初始化
    //  - LocalSearch: 傳opt.initSolution + opt.calcFitness(共享caller之iExecute counter)

    //check, 一般參數與opt先於任何適應函數呼叫檢測, 檢測之值即使用之值
    let c = chkParams([[dps, 'dps', kDps], [funFit, 'funFit', kFun]], opt, {
        Nl: [kPint, 10000], //最大總迴圈數
        NContiguous: [kPint, 200], //最大最佳解連續未更新次數
        NCore: [kPint, 1000000], //最大核心執行次數(僅主演算法用; LocalSearch模式由caller自管)
        ModeOutLimit: [kModeOutLimit, 'Mapping'], //設計變數指標超過範圍之處理方式
        saInitialTemperature: [kNum, 100], //初始溫度
        saAlpha: [kNum, 0.9], //溫度衰減係數 (改善時 T = α*T, 越小衰減越快)
        UseHists: [kBol, true], //是否收集hists陣列(LocalSearch模式可關以省記憶體)
        funGetBetter: [kFun, undefined], //當有更優解出現時呼叫函數
        funEndLoop: [kFun, undefined], //每次主迴圈結束後呼叫函數
        calcFitness: [kFun, undefined], //可由caller傳入以共享iExecute counter
        initSolution: [kInitSolution, undefined], //可由caller傳入(LocalSearch模式)
        random: [kFun, undefined], //亂數產生函數(給了則一切隨機取值只經它)
    })
    if (c.err !== '') {
        return Promise.reject(c.err)
    }
    dps = c.vs[0]
    let { Nl, NContiguous, NCore, ModeOutLimit, saInitialTemperature, saAlpha, UseHists, funGetBetter, funEndLoop, random } = c.o

    //R, 隨機取值之統一出口(見 _random.mjs)
    let R = _makeRandom(random)

    //iExecute, 核心分析次數(若caller傳calcFitness則由caller計, 此值僅作本地參考)
    let iExecute = 0

    //calcFitness, 可由caller傳入以共享iExecute counter
    let calcFitness = c.o.calcFitness
    if (!isfun(calcFitness)) {
        calcFitness = async (_s, from) => {
            iExecute++
            let _ps = map(_s.ps, 'value')
            let f = funFit(_ps)
            if (ispm(f)) {
                f = await f
            }
            return {
                ps: _s.ps,
                fitness: f,
            }
        }
    }

    //初始solution: 可由caller傳入(LocalSearch模式), 否則隨機產生(主演算法模式)
    let initSolution = c.o.initSolution
    let s
    if (initSolution) {
        s = cloneDeep(initSolution)
    }
    else {
        let _s = _genSolution(dps, R)
        s = await calcFitness(_s, 'init')
    }

    let bestSolution = cloneDeep(s)
    let hists = []
    let stopMode = ''
    let stopNl = 0
    let stopExecutions = 0
    let iContinue = 0

    //溫度
    let rTemperature = saInitialTemperature

    if (UseHists) {
        hists.push(cloneDeep(s))
    }

    //搜尋
    let i = -1
    while (true) {
        i++

        //隨機鄰點
        let neighborResult = _randPickNeighbor(s, dps, ModeOutLimit, R)
        let neighbor
        if (neighborResult.changed) {
            //真有變動才算fitness
            neighbor = await calcFitness({ ps: neighborResult.ps }, 'neighbor')
        }
        else {
            //ind未變(_modifyParameter在limit模式或邊界可能)
            neighbor = { ps: neighborResult.ps, fitness: s.fitness }
        }

        //接受判定
        let rFitness = neighbor.fitness - s.fitness
        if (rFitness < 0) {
            //改善 → 必接受, 降溫
            s = neighbor
            rTemperature = saAlpha * rTemperature
        }
        else {
            //惡化 → 機率接受 exp(-ΔF/T)
            if (R.rand() < Math.exp(-rFitness / rTemperature)) {
                s = neighbor
            }
            //else: 拒絕, 保持原解
        }

        //更新bestSolution
        if (bestSolution.fitness > s.fitness) {
            bestSolution = cloneDeep(s)
            if (isfun(funGetBetter)) {
                funGetBetter(cloneDeep(bestSolution), i)
            }
            iContinue = 0
        }
        else {
            iContinue += 1
        }

        if (UseHists) {
            hists.push(cloneDeep(s))
        }

        //stopMode
        if (i >= Nl) {
            stopMode = `stop by Nl[${Nl}]`
        }
        else if (iContinue >= NContiguous) {
            stopMode = `stop by iContinue[${iContinue}] >= NContiguous[${NContiguous}]`
        }
        else if (iExecute >= NCore) {
            stopMode = `stop by iExecute[${iExecute}] >= NCore[${NCore}]`
        }

        if (isestr(stopMode)) {
            stopNl = i
            stopExecutions = iExecute
            break
        }

        if (isfun(funEndLoop)) {
            funEndLoop(cloneDeep(s), cloneDeep(bestSolution), i)
        }
    }

    return {
        bestSolution,
        hists,
        stopMode,
        stopNl,
        stopExecutions,
    }
}


export default omlSA