tmhglnd / total-serialism

Toolbox full of Algorithmic Composition methods
MIT License
151 stars 11 forks source link

Export and import transition table as json for Markov and DeepMarkov #39

Closed tmhglnd closed 8 months ago

tmhglnd commented 1 year ago

For the normal Markov this will be quite straight forward, for the DeepMarkov it needs some translation because that class uses the Map object. Below some code that should be implemented from https://stackoverflow.com/questions/29085197/how-do-you-json-stringify-an-es6-map:

// when exporting
JSON.stringify(markov.table, replacer);

// when importing
markov.table = JSON.parse(inputJSON, reviver);

// function for stringifying the Map output to store as json
function replacer(key, value) {
    if (value instanceof Map) {
        return {
            type: 'Map',
            value: [ ...value ],
        };
    } else {
        return value;
    }
}

// function for parsing a stringified Map output stored as json
function reviver(key, value) {
    if (typeof value === 'object' && value !== null) {
        if (value.type === 'Map') {
            return new Map(value.value);
        }
    }
    return value;
}
tmhglnd commented 1 year ago

For MarkovChain() there is now an markov.read() method to set the transition table.

tmhglnd commented 8 months ago

This is now fixed in 7211cf46a1a096b705eab5ee3e20554b2f8897fc. The methods .stringify() and .parse() have been added to the DeepMarkovChain class. See more details in the docs: https://github.com/tmhglnd/total-serialism/blob/master/docs/stochastic-methods.md#deepmarkovchain