diff --git a/.babelrc b/.babelrc deleted file mode 100644 index 4e1dc0e1..00000000 --- a/.babelrc +++ /dev/null @@ -1,15 +0,0 @@ -{ - "presets": [ - [ - "@babel/preset-env", { - "targets": { - "node": "current" - } - } - ] - ], - "plugins": [ - ["@babel/plugin-proposal-decorators", { "legacy": true }], - ["@babel/plugin-proposal-class-properties", { "loose": true }] - ] -} diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 463b650a..0e377d56 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -5,6 +5,7 @@ module.exports = { plugins: ['lodash'], rules: { 'lodash/import-scope': 2, + 'import/no-cycle': 'error', 'comma-dangle': ['error', 'always-multiline'], 'prefer-destructuring': [ 'error', diff --git a/electron.vite.config.js b/electron.vite.config.js index ae6d9f84..29a493ec 100644 --- a/electron.vite.config.js +++ b/electron.vite.config.js @@ -47,13 +47,12 @@ export default defineConfig( ( { command } ) => ( { }, }, plugins: [ - // plugin-react 5: its babel option compiles legacy MobX decorators. 6 dropped babel. - // JSX in .js is compiled here too: Vite's oxc parser does not treat .js as JSX. + // plugin-react 5: its babel option compiles JSX in .js files. 6 dropped babel. + // Vite's oxc parser does not treat .js as JSX. react( { babel: { plugins: [ - ['@babel/plugin-proposal-decorators', { legacy: true }], - ['@babel/plugin-proposal-class-properties', { loose: true }], + ['@babel/plugin-proposal-class-properties', { loose: false }], ['@babel/plugin-transform-react-jsx', { runtime: 'automatic' }], ], }, diff --git a/jest.config.js b/jest.config.js index ed3f490a..b912988c 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,6 +1,7 @@ module.exports = { testEnvironment: 'jsdom', setupFiles: [ '/jest/setup.js' ], + setupFilesAfterEnv: [ '/jest/mobxActionWarning.js' ], roots: [ '/src' ], transform: { '^.+\\.(js|jsx|mjs|ts|tsx)$': '/jest/babelTransform.js', diff --git a/jest/babelTransform.js b/jest/babelTransform.js index 3bc5092c..0802f01f 100644 --- a/jest/babelTransform.js +++ b/jest/babelTransform.js @@ -1,6 +1,6 @@ const babelJest = require( 'babel-jest' ); -// Decorator plugins match the page build. preset-env and preset-typescript +// Plugins match the page build. preset-env and preset-typescript // are what Jest needs to load the page's ESM and .tsx imports. module.exports = babelJest.default.createTransformer( { babelrc: false, @@ -10,8 +10,7 @@ module.exports = babelJest.default.createTransformer( { '@babel/preset-typescript', ], plugins: [ - [ '@babel/plugin-proposal-decorators', { legacy: true } ], - [ '@babel/plugin-proposal-class-properties', { loose: true } ], + [ '@babel/plugin-proposal-class-properties', { loose: false } ], [ '@babel/plugin-transform-react-jsx', { runtime: 'automatic' } ], ], } ); diff --git a/jest/mobxActionWarning.js b/jest/mobxActionWarning.js new file mode 100644 index 00000000..3177d9b1 --- /dev/null +++ b/jest/mobxActionWarning.js @@ -0,0 +1,26 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +// Fails a test when MobX warns that observable state was changed outside an action. +const collected = []; +let warn; + +// The warnings collected during the running test; the proof test clears them after asserting. +export const actionWarnings = () => collected; + +beforeEach( () => { + collected.length = 0; + const original = console.warn; + warn = jest.spyOn( console, 'warn' ).mockImplementation( ( ...args ) => { + if ( /\[MobX\] Since strict-mode is enabled/.test( String( args[0] ) ) ) { + collected.push( args[0] ); + } else { + original.apply( console, args ); + } + } ); +} ); + +afterEach( () => { + warn.mockRestore(); + if ( collected.length ) { + throw new Error( `MobX changed observable state outside an action:\n${collected.join( '\n' )}` ); + } +} ); diff --git a/jest/setup.js b/jest/setup.js index 2a373e2a..2d6d5929 100644 --- a/jest/setup.js +++ b/jest/setup.js @@ -42,6 +42,10 @@ function withBridgeEvents( next ) { if ( typeof next.getVersion !== 'function' ) { next.getVersion = () => Promise.resolve(); } + // The output panel checks the output name; MobX 6 re-renders it inside the render test when this rejects. + if ( typeof next.checkOutput !== 'function' ) { + next.checkOutput = () => Promise.resolve( { ok: true, resultFilenames: [] } ); + } // Config construction reads and may write dark mode. if ( typeof next.getDarkMode !== 'function' ) { next.getDarkMode = () => Promise.resolve( false ); diff --git a/jest/storeBridge.js b/jest/storeBridge.js new file mode 100644 index 00000000..613730c1 --- /dev/null +++ b/jest/storeBridge.js @@ -0,0 +1,30 @@ +// @ts-nocheck — Jest helper. checkJs has no jsdom bridge type. +import { autorun } from 'mobx'; + +import { runEvents } from '../src/app/store/StoreBase'; + +// Installs a renderer bridge whose run events record their listeners; `extra` adds or overrides methods. +// `listeners[name]` always holds the live subscribers, and `fire` calls them. +export function stubBridge( extra = {} ) { + const listeners = {}; + const bridge = { ...extra }; + for ( const name of Object.values( runEvents ) ) { + bridge[name] = ( listener ) => { + ( listeners[name] ||= [] ).push( listener ); + return () => { + listeners[name] = listeners[name].filter( ( l ) => l !== listener ); + }; + }; + } + window.rendererBridge = bridge; + const fire = ( name, payload ) => + ( listeners[name] || [] ).forEach( ( listener ) => listener( payload ) ); + return { bridge, listeners, fire }; +} + +// Records every value a reaction sees, so a test can prove it re-ran. +export function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} diff --git a/package.json b/package.json index d8bad7c8..a7b33ca4 100644 --- a/package.json +++ b/package.json @@ -50,11 +50,10 @@ "docs-serve": "cd docs && bundle exec jekyll serve --config _config.yml,_config_dev.yml", "typecheck": "tsc --noEmit", "typecheck:baseline": "node scripts/typecheck-baseline.js", - "lint": "eslint \"src/**/*.{js,jsx,ts,tsx}\" electron.vite.config.js jest.config.js \"jest/**/*.js\"", + "lint": "eslint \"src/**/*.{js,jsx,ts,tsx}\" electron.vite.config.js jest.config.js \"jest/**/*.js\" --max-warnings 0", "lint:fix": "eslint \"src/**/*.{js,jsx,ts,tsx}\" electron.vite.config.js jest.config.js \"jest/**/*.js\" --fix" }, "dependencies": { - "@babel/plugin-proposal-decorators": "^7.29.7", "@emotion/react": "^11.14.0", "@emotion/styled": "^11.14.1", "@mui/icons-material": "^7.3.11", @@ -63,16 +62,15 @@ "allotment": "^1.20.6", "classnames": "^2.3.2", "clean-stack": "3.0.1", - "computed-async-mobx": "^4.2.0", "d3-array": "^3.2.5", "electron-log": "^4.4.8", "electron-store": "^8.1.0", "electron-updater": "^5.2.4", "filenamify": "^4.3.0", "lodash": "^4.18.1", - "mobx": "^5.15.7", - "mobx-react-lite": "^2.2.2", - "mobx-utils": "^5.6.2", + "mobx": "^7.1.7", + "mobx-react-lite": "^5.1.3", + "mobx-utils": "^6.1.0", "parse-filepath": "^1.0.2", "patch-package": "^8.0.1", "postinstall-postinstall": "^2.1.0", @@ -216,6 +214,7 @@ } }, "resolutions": { + "@babel/plugin-proposal-private-property-in-object": "7.21.11", "@typescript-eslint/eslint-plugin": "^8.72.1", "@typescript-eslint/parser": "^8.72.1" } diff --git a/scripts/page-store-coverage.js b/scripts/page-store-coverage.js new file mode 100644 index 00000000..3358079d --- /dev/null +++ b/scripts/page-store-coverage.js @@ -0,0 +1,79 @@ +// Lists every @computed and @action in the page store and reports which run +// under jest. Exits 1 when any member is not run. Also lists @observable +// fields whose name appears in no test file (a pointer, not proof). +const { spawnSync } = require( 'child_process' ); +const fs = require( 'fs' ); +const os = require( 'os' ); +const path = require( 'path' ); +const parser = require( '@babel/parser' ); + +const root = path.join( __dirname, '..' ); +const storeDir = path.join( root, 'src/app/store' ); +const files = fs.readdirSync( storeDir ).filter( f => f.endsWith( '.js' ) && !f.endsWith( '.test.js' ) ); +const tests = fs.readdirSync( storeDir ).filter( f => f.endsWith( '.test.js' ) ) + .map( f => fs.readFileSync( path.join( storeDir, f ), 'utf8' ) ).join( '\n' ); + +const covDir = fs.mkdtempSync( path.join( os.tmpdir(), 'page-store-cov-' ) ); +const jest = spawnSync( 'node', [ + 'node_modules/jest/bin/jest.js', '--watchAll=false', '--coverage', '--coverageReporters=json', + `--coverageDirectory=${covDir}`, '--collectCoverageFrom=src/app/store/*.js', + '--collectCoverageFrom=!src/app/store/*.test.js', +], { cwd: root, encoding: 'utf8' } ); +if ( jest.status !== 0 ) { + console.error( jest.stdout, jest.stderr ); + process.exit( 1 ); +} +const coverage = JSON.parse( fs.readFileSync( path.join( covDir, 'coverage-final.json' ), 'utf8' ) ); + +const decoratorName = d => { + let e = d.expression; + if ( e.type === 'CallExpression' ) e = e.callee; + while ( e.type === 'MemberExpression' ) e = e.object; + return e.name; +}; + +const notRun = []; +const noObservableTest = []; +let computeds = 0; +let actions = 0; +let observables = 0; +for ( const file of files ) { + const full = path.join( storeDir, file ); + const ast = parser.parse( fs.readFileSync( full, 'utf8' ), { + sourceType: 'module', plugins: [ 'jsx', 'typescript', [ 'decorators', { decoratorsBeforeExport: true } ], 'classProperties' ], + } ); + const cov = Object.entries( coverage ).find( ( [ p ] ) => p === full )?.[ 1 ]; + const walk = node => { + if ( !node || typeof node.type !== 'string' ) return; + if ( node.type === 'ClassDeclaration' || node.type === 'ClassExpression' ) { + for ( const m of node.body.body ) { + const kind = ( m.decorators || [] ).map( decoratorName ) + .find( n => [ 'computed', 'action', 'observable' ].includes( n ) ); + if ( !kind ) continue; + const name = `${node.id?.name}.${m.key.name}`; + if ( kind === 'observable' ) { + observables += 1; + if ( !new RegExp( `\\b${m.key.name}\\b` ).test( tests ) ) noObservableTest.push( `${file} ${name}` ); + continue; + } + if ( kind === 'computed' ) computeds += 1; else actions += 1; + // The member's own function is the earliest one inside its range. + const fns = cov ? Object.entries( cov.fnMap ) + .filter( ( [ , f ] ) => f.loc.start.line >= m.loc.start.line && f.loc.end.line <= m.loc.end.line ) + .sort( ( [ , a ], [ , b ] ) => a.loc.start.line - b.loc.start.line || a.loc.start.column - b.loc.start.column ) : []; + if ( !fns.length || !cov.f[fns[0][0]] ) notRun.push( `${file}:${m.loc.start.line} ${kind} ${name}` ); + } + } + for ( const v of Object.values( node ) ) { + if ( Array.isArray( v ) ) v.forEach( walk ); else if ( v && typeof v === 'object' ) walk( v ); + } + }; + walk( ast.program ); +} + +console.log( `computeds: ${computeds}, actions: ${actions}, observables: ${observables}` ); +console.log( `members not run: ${notRun.length}` ); +notRun.forEach( l => console.log( ` ${l}` ) ); +console.log( `observables named in no test: ${noObservableTest.length}` ); +noObservableTest.forEach( l => console.log( ` ${l}` ) ); +process.exit( notRun.length ? 1 : 0 ); diff --git a/scripts/typecheck-baseline.js b/scripts/typecheck-baseline.js index 32452189..aa8ef106 100644 --- a/scripts/typecheck-baseline.js +++ b/scripts/typecheck-baseline.js @@ -43,6 +43,29 @@ function unusedLines(known, actual) { return known.filter( (line, i) => !seen.has(knownOwned[i]) ); } +/** + * Repoint baseline entries from one file path to another after a pure move. + * An entry is rewritten only when tsc reports the same code and message at the + * new path, so the rename can never shelter a new diagnostic. + */ +function renameLines(known, actual, from, to) { + const unclaimed = actual.filter( (line) => line.startsWith(`${to}(`) ); + const missing = []; + const renamed = known.map((line) => { + if (!line.startsWith(`${from}(`)) { + return line; + } + const want = fingerprint(`${to}${line.slice(from.length)}`); + const i = unclaimed.findIndex( (candidate) => fingerprint(candidate) === want ); + if (i === -1) { + missing.push(line); + return line; + } + return unclaimed.splice(i, 1)[0]; + }); + return { renamed, missing }; +} + function main() { if (!fs.existsSync(baselinePath)) { console.error('typecheck baseline is missing: ' + baselinePath); @@ -63,6 +86,25 @@ function main() { process.exit(result.status || 1); } const actual = diagnosticLines(`${result.stdout || ''}\n${result.stderr || ''}`); + const renameAt = process.argv.indexOf('--rename'); + if (renameAt !== -1) { + const [from, to] = process.argv.slice(renameAt + 1, renameAt + 3); + if (!from || !to) { + console.error('usage: typecheck-baseline.js --rename '); + process.exit(1); + } + if (!baseline.some( (line) => line.startsWith(`${from}(`) )) { + console.error('no baseline entries at ' + from); + process.exit(1); + } + const { renamed, missing } = renameLines(baseline, actual, from, to); + if (missing.length) { + console.error('no matching diagnostic at ' + to + ' for:\n' + missing.join('\n')); + process.exit(1); + } + fs.writeFileSync(baselinePath, renamed.join('\n') + '\n'); + return; + } const fresh = freshLines(actual, baseline); const unused = unusedLines(baseline, actual); if (fresh.length || unused.length) { @@ -80,4 +122,4 @@ if (require.main === module) { main(); } -module.exports = { diagnosticLines, freshLines, unusedLines, ownedFingerprints }; +module.exports = { diagnosticLines, freshLines, unusedLines, ownedFingerprints, renameLines }; diff --git a/scripts/typecheck-baseline.txt b/scripts/typecheck-baseline.txt index d3526632..ce174476 100644 --- a/scripts/typecheck-baseline.txt +++ b/scripts/typecheck-baseline.txt @@ -8,26 +8,26 @@ src/app/App.js(466,12): error TS2739: Type '{ error: any; onClose: any; }' is mi src/app/App.js(512,10): error TS2741: Property 'needReload' is missing in type '{ error: any; title: any; onClose: () => void; }' but required in type '{ error: any; onClose: any; needReload: any; title: any; }'. src/app/App.test.js(5,1): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`. src/app/App.test.js(13,3): error TS2304: Cannot find name 'expect'. -src/app/store/Alignment.js(27,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/Alignment.js(54,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/Alignment.js(138,5): error TS2554: Expected 5-6 arguments, but got 3. +src/app/store/AlignmentOptions.js(10,5): error TS2554: Expected 5-6 arguments, but got 3. +src/app/store/AlignmentOptions.js(37,5): error TS2554: Expected 5-6 arguments, but got 3. +src/app/store/AlignmentOptions.js(121,5): error TS2554: Expected 5-6 arguments, but got 3. src/app/store/index.js(5,8): error TS2551: Property 'store' does not exist on type 'Window & typeof globalThis'. Did you mean 'Storage'? src/app/store/Option.js(12,14): error TS2304: Cannot find name 'yup'. -src/app/store/Run.js(278,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(291,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(306,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(313,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(323,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(333,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(353,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(397,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(409,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(422,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(459,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/Run.js(519,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/Run.js(554,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/Run.js(585,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/Run.js(630,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(662,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(681,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/Run.js(693,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(265,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(278,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(293,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(300,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(310,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(320,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(340,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(384,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(396,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(409,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(446,5): error TS2554: Expected 5-6 arguments, but got 3. +src/app/store/RunOptions.js(506,5): error TS2554: Expected 5-6 arguments, but got 3. +src/app/store/RunOptions.js(541,5): error TS2554: Expected 5-6 arguments, but got 3. +src/app/store/RunOptions.js(572,5): error TS2554: Expected 5-6 arguments, but got 3. +src/app/store/RunOptions.js(617,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(649,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(668,5): error TS2554: Expected 5-6 arguments, but got 3. +src/app/store/RunOptions.js(680,5): error TS2554: Expected 5-6 arguments, but got 4. diff --git a/src/app/promisedComputed.js b/src/app/promisedComputed.js new file mode 100644 index 00000000..fbded5c3 --- /dev/null +++ b/src/app/promisedComputed.js @@ -0,0 +1,38 @@ +import { computed, makeObservable } from 'mobx'; +import { fromPromise } from 'mobx-utils'; + +// Replaces computed-async-mobx: its 7.0 build mixes decorators with annotations, which MobX 6 rejects. +// Like a computed that unwraps a promise: `init` until the first resolve, then the latest resolved value. +// Read it inside a reaction: outside one, every read re-runs `fetch` and returns `init`. +class PromisedComputed { + constructor( init, fetch ) { + this.fetch = fetch; + this.cached = init; + makeObservable( this, { + currentState: computed, + value: computed, + } ); + } + + // fetch must return a promise (the only caller is async) + get currentState() { + return fromPromise( this.fetch() ); + } + + get value() { + const state = this.currentState; + if ( state.state === 'rejected' ) { + throw state.value; + } + if ( state.state === 'fulfilled' ) { + this.cached = state.value; + } + return this.cached; + } + + get() { + return this.value; + } +} + +export const promisedComputed = ( init, fetch ) => new PromisedComputed( init, fetch ); diff --git a/src/app/promisedComputed.test.js b/src/app/promisedComputed.test.js new file mode 100644 index 00000000..9d010158 --- /dev/null +++ b/src/app/promisedComputed.test.js @@ -0,0 +1,36 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { observable, runInAction, reaction, when } from 'mobx'; +import { promisedComputed } from './promisedComputed'; + +it( 'keeps the last value while pending and throws a rejection', async () => { + const input = observable.box( 1 ); + const pc = promisedComputed( 0, async () => { + const n = input.get(); + if ( n === 3 ) { + throw new Error( 'boom' ); + } + return n * 10; + } ); + const seen = []; + const errors = []; + const stop = reaction( + () => { + try { + return pc.get(); + } catch ( e ) { + errors.push( e.message ); + return 'error'; + } + }, + ( v ) => seen.push( v ), + { fireImmediately: true }, + ); + await when( () => pc.value === 10, { timeout: 1000 } ).catch( () => {} ); + runInAction( () => input.set( 2 ) ); + await when( () => pc.value === 20, { timeout: 1000 } ); + runInAction( () => input.set( 3 ) ); + await new Promise( ( r ) => setTimeout( r, 20 ) ); + stop(); + expect( seen ).toEqual( [0, 10, 20, 'error'] ); + expect( errors ).toEqual( ['boom'] ); +} ); diff --git a/src/app/store/Alignment.js b/src/app/store/Alignment.js index f8a65724..8c94e42f 100644 --- a/src/app/store/Alignment.js +++ b/src/app/store/Alignment.js @@ -1,152 +1,77 @@ -import { observable, computed, action, runInAction } from 'mobx'; -import union from 'lodash/union'; -import intersection from 'lodash/intersection'; +import { observable, computed, action, runInAction, makeObservable } from 'mobx'; -import Option from './Option'; import * as raxmlSettings from '../../settings/raxml'; import * as raxmlNgSettings from '../../settings/raxmlng'; -import Partition, { FinalPartition } from './Partition'; +import Partition from './Partition'; import InputFile from './InputFile'; +import { + RaxmlNgAlignmentSubstitutionModel, + RaxmlNgModelF, + RaxmlNgModelI, + RaxmlNgModelG, + RaxmlNgModelASC, + MultistateNumber, +} from './AlignmentOptions'; import { runEvents } from './StoreBase'; import { getFinalDataType } from '../../common/typecheckAlignment'; import UserFixError from '../../common/errors'; import { host } from './host'; -import { join } from '../paths'; const raxmlMatrixOptions = raxmlSettings.matrixOptions; const raxmlNgModelOptions = raxmlNgSettings.modelOptions; -class RaxmlNgAlignmentSubstitutionModel extends Option { - constructor( alignment ) { - super( alignment.run, '', 'Substitution model' ); - this.alignment = alignment; - } - @computed get options() { - if ( !this.alignment.run.haveAlignments ) { - return []; - } - const modelSettings = raxmlNgModelOptions[this.alignment.dataType]; - if ( !modelSettings ) { - return []; - } - return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); - } - @computed get notAvailable() { - return !this.alignment.run.haveAlignments; - } - @computed get cmdValue() { - let model = this.value; - if ( this.alignment.dataType === 'multistate' ) { - model = model.replace( 'x', this.alignment.multistateNumber.value ); - } - return model; - } -} - -class RaxmlNgModelExtraParam extends Option { - constructor( alignment, label, options, { addNone = true } = {} ) { - super( alignment.run, addNone - ? '' - : options[0].value, label ); - this.alignment = alignment; - this.optionsSource = addNone - ? [{ value: '', title: 'none' }, ...options] - : options; - this.addNone = addNone; - } - @computed get options() { - if ( !this.run.haveAlignments ) { - return []; - } - return this.optionsSource; - } - @computed get notAvailable() { - return !this.run.haveAlignments || !this.run.usesRaxmlNg; - } - @computed get cmdValue() { - return this.value === '' - ? '' - : this.value; - } -} - -class RaxmlNgModelF extends RaxmlNgModelExtraParam { - constructor( alignment ) { - super( - alignment, - 'Stationary frequencies', - raxmlNgSettings.stationaryFrequenciesOptions.options.map( - ( { value, label: title } ) => ( { value, title } ), - ), - ); - } -} - -class RaxmlNgModelI extends RaxmlNgModelExtraParam { - constructor( alignment ) { - super( - alignment, - 'Proportion of invariant sites', - raxmlNgSettings.proportionOfInvariantSitesOptions.options.map( - ( { value, label: title } ) => ( { value, title } ), - ), - ); - } -} - -class RaxmlNgModelG extends RaxmlNgModelExtraParam { - constructor( alignment ) { - super( - alignment, - 'Rate heterogeneity', - raxmlNgSettings.amongsiteRateHeterogeneityModelOptions.options.map( - ( { value, label: title } ) => ( { value, title } ), - ), - ); - } -} - -class RaxmlNgModelASC extends RaxmlNgModelExtraParam { - constructor( alignment ) { - super( - alignment, - 'Ascertainment bias', - [ - { value: '', label: 'No correction' }, - ...raxmlNgSettings.ascertainmentBiasCorrectionOptions.options, - ].map( ( { value, label: title } ) => ( { value, title } ) ), - { addNone: false }, - ); - } - @computed get notAvailable() { - return ( - !this.run.haveAlignments || - !this.run.usesRaxmlNg || - this.alignment.hasInvariantSites - ); - } -} - -class MultistateNumber extends Option { - constructor( alignment ) { - super( alignment.run, '', 'Number of states' ); - this.alignment = alignment; - this.placeholder = 'Integer'; - } - @computed get notAvailable() { - return ( - this.alignment.dataType !== 'multistate' || - !this.alignment.run.usesRaxmlNg - ); - } - @computed get error() { - return !this.value || !Number.isInteger( Number( this.value ) ); - } -} - class Alignment extends InputFile { constructor( run, path ) { super( run, path ); + makeObservable( this, { + error: observable, + dataType: observable, + aaMatrixName: observable, + size: observable, + fileFormat: observable, + convertedFrom: observable, + converted: observable, + modified: observable, + modificationMessages: observable, + showModifiedSnack: observable, + showModifiedDialog: observable, + length: observable, + numSequences: observable, + sequences: observable, + hasInvariantSites: observable, + parsingComplete: observable, + typecheckingComplete: observable, + loading: observable, + checkRunComplete: observable, + checkRunData: observable, + checkRunSuccess: observable, + partitionText: observable, + modeltestLoading: observable, + taxons: computed, + showPartition: computed, + partitionType: computed, + partitionFileContent: computed, + ngSubstitutionModelCmd: computed, + numSites: computed, + status: computed, + modelExtra: computed, + modelTestCanRun: computed, + setShowPartition: action, + hidePartition: action, + setPartitionText: action, + runModelTest: action, + cancelModelTest: action, + setModelFromString: action, + onModelSelectionSuccess: action, + onModelSelectionFailure: action, + clearModified: action, + dispose: action, + remove: action, + onChangeModel: action, + onChangeAAMatrixName: action, + onRunStdout: action, + onRunStderr: action, + } ); this.substitutionModel = new RaxmlNgAlignmentSubstitutionModel( this ); this.multistateNumber = new MultistateNumber( this ); this.ngStationaryFrequencies = new RaxmlNgModelF( this ); @@ -162,64 +87,60 @@ class Alignment extends InputFile { this.listen(); } - @observable error = null; + error = null; - @observable dataType = undefined; + dataType = undefined; /** @type {string} */ - @observable aaMatrixName = + aaMatrixName = raxmlSettings.aminoAcidSubstitutionMatrixOptions.default; - @observable size = 0; - @observable fileFormat = undefined; - @observable convertedFrom = undefined; - @observable converted = false; - @observable modified = false; - @observable modificationMessages = []; - @observable showModifiedSnack = false; - @observable showModifiedDialog = false; - @observable length = 0; - @observable numSequences = 0; - @observable sequences = []; - @observable hasInvariantSites = false; - - @computed get taxons() { + size = 0; + fileFormat = undefined; + convertedFrom = undefined; + converted = false; + modified = false; + modificationMessages = []; + showModifiedSnack = false; + showModifiedDialog = false; + length = 0; + numSequences = 0; + sequences = []; + hasInvariantSites = false; + + get taxons() { return this.sequences.map( ( seq ) => seq.taxon ); } - @observable parsingComplete = false; - @observable typecheckingComplete = false; - @observable loading = true; + parsingComplete = false; + typecheckingComplete = false; + loading = true; - @observable checkRunComplete = false; - @observable checkRunData = ''; - @observable checkRunSuccess = false; - // @observable taxons = []; + checkRunComplete = false; + checkRunData = ''; + checkRunSuccess = false; // Partition stuff - @computed get showPartition() { + get showPartition() { return this.run.showPartitionFor === this; } - @action - setShowPartition = ( value = true ) => { - this.run.showPartition( value - ? this - : null ); - }; + setShowPartition = ( value = true ) => { + this.run.showPartition( value + ? this + : null ); + }; - @action - hidePartition = () => { - this.setShowPartition( false ); - }; + hidePartition = () => { + this.setShowPartition( false ); + }; - @action - setPartitionText = ( value ) => { - this.partitionText = value; - }; + setPartitionText = ( value ) => { + this.partitionText = value; + }; - @observable partitionText = ''; + partitionText = ''; - @computed get partitionType() { + get partitionType() { if ( this.run.usesRaxmlNg ) { return this.ngSubstitutionModelCmd; } @@ -238,7 +159,7 @@ class Alignment extends InputFile { } } - @computed get partitionFileContent() { + get partitionFileContent() { /* DNA, gene1 = 1-3676 BIN, morph = 3677-3851 @@ -254,16 +175,14 @@ class Alignment extends InputFile { return partitionFileText; } - @computed get ngSubstitutionModelCmd() { + get ngSubstitutionModelCmd() { return `${this.substitutionModel.cmdValue}${this.ngStationaryFrequencies.cmdValue}${this.ngInvariantSites.cmdValue}${this.ngRateHeterogeneity.cmdValue}${this.ngAscertainmentBias.cmdValue}`; } - @computed get numSites() { return this.length; } - @computed get status() { if ( this.error ) { return `Error: ${this.error}`; @@ -280,7 +199,6 @@ class Alignment extends InputFile { return 'ok'; } - @computed get modelExtra() { switch ( this.dataType ) { case 'protein': @@ -299,124 +217,121 @@ class Alignment extends InputFile { } } - @computed get modelTestCanRun() { + get modelTestCanRun() { return this.dataType === 'nucleotide' || this.dataType === 'protein'; } - @observable modeltestLoading = false; + modeltestLoading = false; - @action - runModelTest = async () => { + runModelTest = async () => { // Show an error if there are not enough sequences and dont start the run - if ( this.numSequences < 3 ) { - this.run.parent.onError( - new UserFixError( - 'ModelTest can only be run on alignments with more than two sequences.', - ), - ); - return; - } - this.modeltestLoading = true; - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.startModelSelection( { - id: this.id, - filePath: this.path, - outputDir: this.run.outputDir, - dataType: this.dataType, - numThreads: this.run.numThreads.value, - binaryName: this.run.modeltestName, - } ); - }; - - @action - cancelModelTest = () => { - if ( this.modeltestLoading ) { - this.modeltestLoading = false; - const { rendererBridge } = /** @type {any} */ ( window ); - rendererBridge.cancelModelSelection( this.id ); - } - }; - - @action - setModelFromString = ( { raxml, extraFlag, raxmlNG } ) => { + if ( this.numSequences < 3 ) { + this.run.parent.onError( + new UserFixError( + 'ModelTest can only be run on alignments with more than two sequences.', + ), + ); + return; + } + this.modeltestLoading = true; + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.startModelSelection( { + id: this.id, + filePath: this.path, + outputDir: this.run.outputDir, + dataType: this.dataType, + numThreads: this.run.numThreads.value, + binaryName: this.run.modeltestName, + } ); + }; + + cancelModelTest = () => { + if ( this.modeltestLoading ) { this.modeltestLoading = false; - // For raxml-ng - let model = raxmlNG.split( '+' )[0]; - // Two models have different names in modeltest-ng and raxml-ng - model = model.replace( 'TrN', 'TN93' ); - model = model.replace( 'TPM1', 'K81' ); - this.substitutionModel.setValue( model ); - if ( /\+F[O|E]?/.test( raxmlNG ) ) { - this.ngStationaryFrequencies.setValue( /\+F[O|E]?/.exec( raxmlNG )[0] ); - } - if ( /\+IC?/.test( raxmlNG ) ) { - this.ngInvariantSites.setValue( /\+IC?/.exec( raxmlNG )[0] ); - } - if ( /\+GA?/.test( raxmlNG ) ) { - this.ngRateHeterogeneity.setValue( /\+GA?/.exec( raxmlNG )[0] ); - } - if ( /\+ASC_LEWIS/.test( raxmlNG ) ) { - this.ngAscertainmentBias.setValue( '+ASC_LEWIS' ); - } - - model = raxml; - // For raxml - if ( /F$/.test( raxml ) ) { - this.run.baseFrequencies.setValue( 'F' ); - model = model.slice( 0, -1 ); - } else if ( /X$/.test( raxml ) ) { - this.run.estimatedFrequencies.setValue( true ); // for all but proteins - this.run.baseFrequencies.setValue( 'X' ); // for proteins - model = model.slice( 0, -1 ); - } else { - this.run.baseFrequencies.setValue( 'default' ); - } - - if ( this.dataType === 'protein' ) { - console.log( 'parsing matrix name...' ); - const { options } = raxmlSettings.aminoAcidSubstitutionMatrixOptions; - const re = new RegExp( `(${options.join( '|' )})$` ); - const matrixName = re.exec( model )[1]; - this.aaMatrixName = matrixName; - model = model.replace( re, '' ); - } - // I couldnt find information if ModelTest checks for ASC_ - this.run.substitutionAscertainment.setValue( 'none' ); - - // Check for invariant sites - if ( /I$/.test( model ) ) { - this.run.substitutionI.setValue( '+I (ML estimate)' ); - model = model.slice( 0, -1 ); - } else { - this.run.substitutionI.setValue( 'none' ); - } - // Check for substitution rates - if ( /GAMMA/.test( model ) ) { - this.run.substitutionRate.setValue( 'GAMMA' ); - model = model.replace( 'GAMMA', '' ); - } - if ( /CAT/.test( model ) ) { - this.run.substitutionRate.setValue( 'CAT' ); - model = model.replace( 'CAT', '' ); - } - // Checks for the different nucleotide substitution matrices - // Default is GTR - if ( extraFlag === '--JC69' ) { - this.run.substitutionMatrix.setValue( 'JC' ); - // We dont allow CAT model for this matrix - this.run.substitutionRate.setValue( 'GAMMA' ); - } - if ( extraFlag === '--K80' ) { - this.run.substitutionMatrix.setValue( 'K80' ); - // We dont allow CAT model for this matrix - this.run.substitutionRate.setValue( 'GAMMA' ); - } - if ( extraFlag === '--HKY85' ) { - this.run.substitutionMatrix.setValue( 'HKY' ); - // We dont allow CAT model for this matrix - this.run.substitutionRate.setValue( 'GAMMA' ); - } - }; + const { rendererBridge } = /** @type {any} */ ( window ); + rendererBridge.cancelModelSelection( this.id ); + } + }; + + setModelFromString = ( { raxml, extraFlag, raxmlNG } ) => { + this.modeltestLoading = false; + // For raxml-ng + let model = raxmlNG.split( '+' )[0]; + // Two models have different names in modeltest-ng and raxml-ng + model = model.replace( 'TrN', 'TN93' ); + model = model.replace( 'TPM1', 'K81' ); + this.substitutionModel.setValue( model ); + if ( /\+F[O|E]?/.test( raxmlNG ) ) { + this.ngStationaryFrequencies.setValue( /\+F[O|E]?/.exec( raxmlNG )[0] ); + } + if ( /\+IC?/.test( raxmlNG ) ) { + this.ngInvariantSites.setValue( /\+IC?/.exec( raxmlNG )[0] ); + } + if ( /\+GA?/.test( raxmlNG ) ) { + this.ngRateHeterogeneity.setValue( /\+GA?/.exec( raxmlNG )[0] ); + } + if ( /\+ASC_LEWIS/.test( raxmlNG ) ) { + this.ngAscertainmentBias.setValue( '+ASC_LEWIS' ); + } + + model = raxml; + // For raxml + if ( /F$/.test( raxml ) ) { + this.run.baseFrequencies.setValue( 'F' ); + model = model.slice( 0, -1 ); + } else if ( /X$/.test( raxml ) ) { + this.run.estimatedFrequencies.setValue( true ); // for all but proteins + this.run.baseFrequencies.setValue( 'X' ); // for proteins + model = model.slice( 0, -1 ); + } else { + this.run.baseFrequencies.setValue( 'default' ); + } + + if ( this.dataType === 'protein' ) { + console.log( 'parsing matrix name...' ); + const { options } = raxmlSettings.aminoAcidSubstitutionMatrixOptions; + const re = new RegExp( `(${options.join( '|' )})$` ); + const matrixName = re.exec( model )[1]; + this.aaMatrixName = matrixName; + model = model.replace( re, '' ); + } + // I couldnt find information if ModelTest checks for ASC_ + this.run.substitutionAscertainment.setValue( 'none' ); + + // Check for invariant sites + if ( /I$/.test( model ) ) { + this.run.substitutionI.setValue( '+I (ML estimate)' ); + model = model.slice( 0, -1 ); + } else { + this.run.substitutionI.setValue( 'none' ); + } + // Check for substitution rates + if ( /GAMMA/.test( model ) ) { + this.run.substitutionRate.setValue( 'GAMMA' ); + model = model.replace( 'GAMMA', '' ); + } + if ( /CAT/.test( model ) ) { + this.run.substitutionRate.setValue( 'CAT' ); + model = model.replace( 'CAT', '' ); + } + // Checks for the different nucleotide substitution matrices + // Default is GTR + if ( extraFlag === '--JC69' ) { + this.run.substitutionMatrix.setValue( 'JC' ); + // We dont allow CAT model for this matrix + this.run.substitutionRate.setValue( 'GAMMA' ); + } + if ( extraFlag === '--K80' ) { + this.run.substitutionMatrix.setValue( 'K80' ); + // We dont allow CAT model for this matrix + this.run.substitutionRate.setValue( 'GAMMA' ); + } + if ( extraFlag === '--HKY85' ) { + this.run.substitutionMatrix.setValue( 'HKY' ); + // We dont allow CAT model for this matrix + this.run.substitutionRate.setValue( 'GAMMA' ); + } + }; loadParsedAlignment = async () => { const { rendererBridge } = /** @type {any} */ ( window ); @@ -428,14 +343,14 @@ class Alignment extends InputFile { .map( ( { dataType } ) => dataType ) .concat( alignment.dataType ), ); - if ( this.run.dataType !== newDataType ) { - this.run.substitutionMatrix.value = - raxmlMatrixOptions[newDataType].default; - } - // When the alignment has finished processing take the default substitution model for this datatype - this.substitutionModel.value = - raxmlNgModelOptions[alignment.dataType]?.default; runInAction( () => { + if ( this.run.dataType !== newDataType ) { + this.run.substitutionMatrix.value = + raxmlMatrixOptions[newDataType].default; + } + // When the alignment has finished processing take the default substitution model for this datatype + this.substitutionModel.value = + raxmlNgModelOptions[alignment.dataType]?.default; this.sequences = alignment.sequences; this.fileFormat = alignment.fileFormat; this.numSequences = alignment.numSequences; @@ -470,24 +385,22 @@ class Alignment extends InputFile { } }; - @action - onModelSelectionSuccess = ( { id, result } ) => { - if ( id === this.id ) { - console.log( id, 'Modeltest result:', result ); - this.setModelFromString( result ); - this.run.afterRun(); - } - }; - - @action - onModelSelectionFailure = ( { id, error } ) => { - if ( id === this.id ) { - this.modeltestLoading = false; - console.log( id, 'Modeltest error:', error ); - this.run.error = error; - this.run.afterRun(); - } - }; + onModelSelectionSuccess = ( { id, result } ) => { + if ( id === this.id ) { + console.log( id, 'Modeltest result:', result ); + this.setModelFromString( result ); + this.run.afterRun(); + } + }; + + onModelSelectionFailure = ( { id, error } ) => { + if ( id === this.id ) { + this.modeltestLoading = false; + console.log( id, 'Modeltest error:', error ); + this.run.error = error; + this.run.afterRun(); + } + }; listen = () => { this.loadParsedAlignment(); @@ -497,258 +410,54 @@ class Alignment extends InputFile { this.subscribe( runEvents.onRunStderr, this.onRunStderr ); }; - @action clearModified = () => { + clearModified = () => { this.showModifiedSnack = false; this.showModifiedDialog = false; }; - @action - dispose = () => { - this.unlisten(); - if ( this.modeltestLoading ) { - this.cancelModelTest(); - } - }; - - @action - remove = () => { - this.dispose(); - this.run.removeAlignment( this ); - }; - - @action - onChangeModel = ( event ) => { - console.log( 'onChangeModel' ); - this.model = event.target.value; - }; - - @action - onChangeAAMatrixName = ( value ) => { - console.log( 'onChangeAAMatrixName' ); - this.aaMatrixName = value; - }; - - @action - onRunStdout = ( { id, content } ) => { - if ( id === this.id ) { - // TODO: Keep local log? - this.run.stdout += content; - } - }; - - @action - onRunStderr = ( { id, content } ) => { - if ( id === this.id ) { - this.run.stderr += content; - } - }; - - getSequenceCode = ( taxon ) => { - // TODO: Sort sequences on taxon for quicker search, intersection and union - const seq = this.sequences.find( ( seq ) => seq.taxon === taxon ); - if ( seq !== undefined ) { - return seq.code; + dispose() { + this.unlisten(); + if ( this.modeltestLoading ) { + this.cancelModelTest(); } - return '-'.repeat( this.length ); - }; -} - -class FinalAlignment { - constructor( run ) { - this.run = run; - this.partition = new FinalPartition( run ); - } - - @computed get filename() { - if ( this.numAlignments === 1 ) { - return this.run.alignments[0].filename; - } - return `RAxML_${this.run.outputNameSafe}_concat.txt`; - } - - @computed get dir() { - if ( this.numAlignments === 1 ) { - return this.run.alignments[0].dir; - } - return this.run.outputDir; - } - - @computed get path() { - if ( this.numAlignments === 1 ) { - return this.run.alignments[0].path; - } - return join( `${this.dir}`, `${this.filename}` ); - } - - @observable parsingComplete = true; - - @computed get numAlignments() { - return this.run.alignments.length; } - // By default add empty sequences to fill gaps up to the union of taxons - // else drop taxons that doesn't exist in all alignments by taking the intersection - @observable fillTaxonGapsWithEmptySeqeunces = true; - - @action setFillTaxonGapsWithEmptySeqeunces = ( checked ) => { - this.fillTaxonGapsWithEmptySeqeunces = checked; + remove = () => { + this.dispose(); + this.run.removeAlignment( this ); }; - @computed get taxons() { - const setMethod = this.fillTaxonGapsWithEmptySeqeunces - ? union - : intersection; - return setMethod.apply( - setMethod, - this.run.alignments.map( ( { taxons } ) => taxons ), - ); - } - - @computed get numSequences() { - return this.taxons.length; - } + onChangeModel = ( event ) => { + console.log( 'onChangeModel' ); + this.model = event.target.value; + }; - @computed get length() { - return this.run.alignments.reduce( - ( sumLength, alignment ) => sumLength + alignment.length, - 0, - ); - } + onChangeAAMatrixName = ( value ) => { + console.log( 'onChangeAAMatrixName' ); + this.aaMatrixName = value; + }; - @computed get hasInvariantSites() { - // If any one of the alignments has invariant sites return true - for ( const alignment of this.run.alignments ) { - if ( alignment.hasInvariantSites ) { - return true; - } + onRunStdout = ( { id, content } ) => { + if ( id === this.id ) { + // TODO: Keep local log? + this.run.stdout += content; } - return false; - } - - // @computed get dataType() { - // const numAlignments = this.numAlignments; - // if (numAlignments === 0) { - // return 'none'; - // } - // const firstType = this.run.alignments[0].dataType; - // if (numAlignments === 1) { - // return firstType; - // } - // for (let i = 1; i < numAlignments; ++i) { - // if (this.run.alignments[i].dataType !== firstType) { - // return 'mixed'; - // } - // } - // return firstType; - // } - - @computed get dataType() { - const { alignments } = this.run; - const dataTypes = alignments.map( ( { dataType } ) => dataType ); - return getFinalDataType( dataTypes ); - } + }; - @computed get modelFlagName() { - const {numAlignments} = this; - if ( numAlignments === 0 ) { - return 'none'; - } - const first = this.run.alignments[0].modelFlagName; - if ( numAlignments === 1 ) { - return first; + onRunStderr = ( { id, content } ) => { + if ( id === this.id ) { + this.run.stderr += content; } - return first; - } + }; - @computed get partitionFilePath() { - if ( this.partition.isDefault ) { - return ''; + getSequenceCode = ( taxon ) => { + // TODO: Sort sequences on taxon for quicker search, intersection and union + const seq = this.sequences.find( ( seq ) => seq.taxon === taxon ); + if ( seq !== undefined ) { + return seq.code; } - const suffix = this.numAlignments > 1 - ? '_concat' - : ''; - return join( - `${this.dir}`, - `RAxML_${this.run.outputNameSafe}${suffix}.part.txt`, - ); - } - - @computed get partitionFileContent() { - return this.partition.text; - } - - @action - openFile = async () => { - await this.writeConcatenatedAlignment(); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.openPath( this.path ); - }; - - @action - openPartition = async () => { - await this.writeConcatenatedAlignmentAndPartition(); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.openPath( this.partitionFilePath ); - }; - - @action - showFileInFolder = async () => { - await this.writeConcatenatedAlignment(); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.showItemInFolder( this.path ); - }; - - @action - openFolder = async () => { - await this.writeConcatenatedAlignmentAndPartition(); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.showItemInFolder( this.dir ); - }; - - @action - writeConcatenatedAlignmentAndPartition = async () => { - await this.writeConcatenatedAlignment(); - await this.writePartition(); - }; - - @action - writeConcatenatedAlignment = async () => { - const { taxons, numSequences } = this; - try { - console.log( - `Write concatenated alignment in FASTA format to ${this.path}..`, - ); - let text = ''; - for ( let i = 0; i < numSequences; ++i ) { - for ( let j = 0; j < this.numAlignments; ++j ) { - if ( j === 0 ) { - const prefix = i === 0 - ? '>' - : '\n>'; - text += `${prefix}${taxons[i]}\n`; - } - text += this.run.alignments[j].getSequenceCode( taxons[i] ); - } - } - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.writeFile( this.path, text ); - } catch ( err ) { - console.error( 'Error writing concatenated alignment:', err ); - throw err; - } - }; - - @action - writePartition = async () => { - try { - console.log( `Writing partition to ${this.partitionFilePath}...` ); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.writeFile( this.partitionFilePath, this.partitionFileContent ); - } catch ( err ) { - console.error( 'Error writing partition:', err ); - throw err; - } - }; + return '-'.repeat( this.length ); + }; } -export { Alignment as default, FinalAlignment }; +export default Alignment; diff --git a/src/app/store/AlignmentOptions.js b/src/app/store/AlignmentOptions.js new file mode 100644 index 00000000..6b8affae --- /dev/null +++ b/src/app/store/AlignmentOptions.js @@ -0,0 +1,160 @@ +import { computed, makeObservable, override } from 'mobx'; + +import Option from './Option'; +import * as raxmlNgSettings from '../../settings/raxmlng'; + +const raxmlNgModelOptions = raxmlNgSettings.modelOptions; + +class RaxmlNgAlignmentSubstitutionModel extends Option { + constructor( alignment ) { + super( alignment.run, '', 'Substitution model' ); + makeObservable( this, { + options: computed, + notAvailable: computed, + cmdValue: computed, + } ); + this.alignment = alignment; + } + get options() { + if ( !this.alignment.run.haveAlignments ) { + return []; + } + const modelSettings = raxmlNgModelOptions[this.alignment.dataType]; + if ( !modelSettings ) { + return []; + } + return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); + } + get notAvailable() { + return !this.alignment.run.haveAlignments; + } + get cmdValue() { + let model = this.value; + if ( this.alignment.dataType === 'multistate' ) { + model = model.replace( 'x', this.alignment.multistateNumber.value ); + } + return model; + } +} + +class RaxmlNgModelExtraParam extends Option { + constructor( alignment, label, options, { addNone = true } = {} ) { + super( alignment.run, addNone + ? '' + : options[0].value, label ); + makeObservable( this, { + options: computed, + notAvailable: computed, + cmdValue: computed, + } ); + this.alignment = alignment; + this.optionsSource = addNone + ? [{ value: '', title: 'none' }, ...options] + : options; + this.addNone = addNone; + } + get options() { + if ( !this.run.haveAlignments ) { + return []; + } + return this.optionsSource; + } + get notAvailable() { + return !this.run.haveAlignments || !this.run.usesRaxmlNg; + } + get cmdValue() { + return this.value === '' + ? '' + : this.value; + } +} + +class RaxmlNgModelF extends RaxmlNgModelExtraParam { + constructor( alignment ) { + super( + alignment, + 'Stationary frequencies', + raxmlNgSettings.stationaryFrequenciesOptions.options.map( + ( { value, label: title } ) => ( { value, title } ), + ), + ); + } +} + +class RaxmlNgModelI extends RaxmlNgModelExtraParam { + constructor( alignment ) { + super( + alignment, + 'Proportion of invariant sites', + raxmlNgSettings.proportionOfInvariantSitesOptions.options.map( + ( { value, label: title } ) => ( { value, title } ), + ), + ); + } +} + +class RaxmlNgModelG extends RaxmlNgModelExtraParam { + constructor( alignment ) { + super( + alignment, + 'Rate heterogeneity', + raxmlNgSettings.amongsiteRateHeterogeneityModelOptions.options.map( + ( { value, label: title } ) => ( { value, title } ), + ), + ); + } +} + +class RaxmlNgModelASC extends RaxmlNgModelExtraParam { + constructor( alignment ) { + super( + alignment, + 'Ascertainment bias', + [ + { value: '', label: 'No correction' }, + ...raxmlNgSettings.ascertainmentBiasCorrectionOptions.options, + ].map( ( { value, label: title } ) => ( { value, title } ) ), + { addNone: false }, + ); + makeObservable( this, { + notAvailable: override, + } ); + } + get notAvailable() { + return ( + !this.run.haveAlignments || + !this.run.usesRaxmlNg || + this.alignment.hasInvariantSites + ); + } +} + +class MultistateNumber extends Option { + constructor( alignment ) { + super( alignment.run, '', 'Number of states' ); + makeObservable( this, { + notAvailable: computed, + error: override, + } ); + this.alignment = alignment; + this.placeholder = 'Integer'; + } + get notAvailable() { + return ( + this.alignment.dataType !== 'multistate' || + !this.alignment.run.usesRaxmlNg + ); + } + get error() { + return !this.value || !Number.isInteger( Number( this.value ) ); + } +} + +export { + RaxmlNgAlignmentSubstitutionModel, + RaxmlNgModelF, + RaxmlNgModelI, + RaxmlNgModelG, + RaxmlNgModelASC, + MultistateNumber, +}; diff --git a/src/app/store/AlignmentOptions.test.js b/src/app/store/AlignmentOptions.test.js new file mode 100644 index 00000000..4d5ae669 --- /dev/null +++ b/src/app/store/AlignmentOptions.test.js @@ -0,0 +1,218 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; +import * as raxmlNgSettings from '../../settings/raxmlng'; + +beforeEach( () => { + window.rendererBridge = { parseAlignment: () => new Promise( () => {} ) }; +} ); + +function setup() { + const run = new Run( { onError() {} }, 1 ); + run.addAlignments( [{ path: '/data/a.fasta' }] ); + const alignment = run.alignments[0]; + runInAction( () => { + run.binary.value = 'raxml-ng'; + alignment.dataType = 'nucleotide'; + } ); + return { run, alignment }; +} + +function useOtherBinary( run ) { + runInAction( () => { + run.binary.value = run.binary.options.find( + ( o ) => !o.value.includes( 'raxml-ng' ), + ).value; + } ); +} + +// Records every value a computed takes while the store changes. +function watch( read ) { + const seen = []; + const stop = autorun( () => seen.push( read() ) ); + return { seen, stop }; +} + +describe( 'substitution model', () => { + it( 'lists the options of the alignment data type', () => { + const { alignment } = setup(); + const { options } = raxmlNgSettings.modelOptions.nucleotide; + expect( alignment.substitutionModel.options ).toEqual( + options.map( ( value ) => ( { value, title: value } ) ), + ); + } ); + + it( 'has no options for an unknown data type', () => { + const { alignment } = setup(); + runInAction( () => { + alignment.dataType = undefined; + } ); + expect( alignment.substitutionModel.options ).toEqual( [] ); + } ); + + it( 'has no options and is not available without alignments', () => { + const { run, alignment } = setup(); + const model = alignment.substitutionModel; + const { seen, stop } = watch( () => [model.options.length > 0, model.notAvailable] ); + run.removeAlignment( alignment ); + stop(); + expect( seen ).toEqual( [[true, false], [false, true]] ); + } ); + + it( 'updates the options when the data type changes', () => { + const { alignment } = setup(); + const { seen, stop } = watch( () => alignment.substitutionModel.options.length ); + runInAction( () => { + alignment.dataType = 'protein'; + } ); + stop(); + expect( seen ).toEqual( [ + raxmlNgSettings.modelOptions.nucleotide.options.length, + raxmlNgSettings.modelOptions.protein.options.length, + ] ); + } ); + + it( 'uses its value as the command value and follows value changes', () => { + const { alignment } = setup(); + const model = alignment.substitutionModel; + const { seen, stop } = watch( () => model.cmdValue ); + model.setValue( 'HKY' ); + stop(); + expect( seen ).toEqual( ['', 'HKY'] ); + } ); + + it( 'puts the multistate number into the command value', () => { + const { alignment } = setup(); + runInAction( () => { + alignment.dataType = 'multistate'; + } ); + alignment.substitutionModel.setValue( 'MULTIx_GTR' ); + const { seen, stop } = watch( () => alignment.substitutionModel.cmdValue ); + alignment.multistateNumber.setValue( '5' ); + stop(); + expect( seen ).toEqual( ['MULTI_GTR', 'MULTI5_GTR'] ); + } ); +} ); + +describe( 'extra model parameters', () => { + const extras = [ + ['ngStationaryFrequencies', 'Stationary frequencies', '+F'], + ['ngInvariantSites', 'Proportion of invariant sites', '+I'], + ['ngRateHeterogeneity', 'Rate heterogeneity', '+G'], + ]; + + it.each( extras )( '%s starts at none and has an empty command value', ( key, title ) => { + const { alignment } = setup(); + const option = alignment[key]; + expect( option.title ).toBe( title ); + expect( option.value ).toBe( '' ); + expect( option.cmdValue ).toBe( '' ); + expect( option.options[0] ).toEqual( { value: '', title: 'none' } ); + expect( option.options.length ).toBeGreaterThan( 1 ); + } ); + + it.each( extras )( '%s command value follows its value', ( key, _title, value ) => { + const { alignment } = setup(); + const option = alignment[key]; + const { seen, stop } = watch( () => option.cmdValue ); + option.setValue( value ); + option.setValue( '' ); + stop(); + expect( seen ).toEqual( ['', value, ''] ); + } ); + + it.each( extras )( '%s is only available with alignments and raxml-ng', ( key ) => { + const { run, alignment } = setup(); + const option = alignment[key]; + const { seen, stop } = watch( () => [option.notAvailable, option.options.length > 0] ); + useOtherBinary( run ); + runInAction( () => { + run.binary.value = 'raxml-ng'; + } ); + run.removeAlignment( alignment ); + stop(); + expect( seen ).toEqual( [ + [false, true], + [true, true], + [false, true], + [true, false], + ] ); + } ); + + it( 'ascertainment bias defaults to no correction', () => { + const { alignment } = setup(); + const asc = alignment.ngAscertainmentBias; + expect( asc.value ).toBe( '' ); + expect( asc.cmdValue ).toBe( '' ); + expect( asc.options ).toEqual( [ + { value: '', title: 'No correction' }, + { value: '+ASC_LEWIS', title: "Lewis' method" }, + ] ); + const { seen, stop } = watch( () => asc.cmdValue ); + asc.setValue( '+ASC_LEWIS' ); + stop(); + expect( seen ).toEqual( ['', '+ASC_LEWIS'] ); + } ); + + it( 'ascertainment bias is unavailable with invariant sites, without raxml-ng or without alignments', () => { + const { run, alignment } = setup(); + const asc = alignment.ngAscertainmentBias; + const { seen, stop } = watch( () => asc.notAvailable ); + runInAction( () => { + alignment.hasInvariantSites = true; + } ); + runInAction( () => { + alignment.hasInvariantSites = false; + } ); + useOtherBinary( run ); + stop(); + expect( seen ).toEqual( [false, true, false, true] ); + runInAction( () => { + run.binary.value = 'raxml-ng'; + } ); + run.removeAlignment( alignment ); + expect( asc.notAvailable ).toBe( true ); + } ); +} ); + +describe( 'multistate number', () => { + it( 'starts empty with an integer placeholder', () => { + const { alignment } = setup(); + expect( alignment.multistateNumber.value ).toBe( '' ); + expect( alignment.multistateNumber.placeholder ).toBe( 'Integer' ); + } ); + + it( 'has an error for a missing value', () => { + const { alignment } = setup(); + expect( alignment.multistateNumber.error ).toBe( true ); + } ); + + it( 'has an error for a non-integer value', () => { + const { alignment } = setup(); + alignment.multistateNumber.setValue( '2.5' ); + expect( alignment.multistateNumber.error ).toBe( true ); + alignment.multistateNumber.setValue( 'abc' ); + expect( alignment.multistateNumber.error ).toBe( true ); + } ); + + it( 'has no error for a valid value and follows value changes', () => { + const { alignment } = setup(); + const { seen, stop } = watch( () => alignment.multistateNumber.error ); + alignment.multistateNumber.setValue( '4' ); + stop(); + expect( seen ).toEqual( [true, false] ); + } ); + + it( 'is available only for multistate data with raxml-ng', () => { + const { run, alignment } = setup(); + const number = alignment.multistateNumber; + const { seen, stop } = watch( () => number.notAvailable ); + runInAction( () => { + alignment.dataType = 'multistate'; + } ); + useOtherBinary( run ); + stop(); + expect( seen ).toEqual( [true, false, true] ); + } ); +} ); diff --git a/src/app/store/AppStore.js b/src/app/store/AppStore.js index e976b17e..b5bc5aec 100644 --- a/src/app/store/AppStore.js +++ b/src/app/store/AppStore.js @@ -1,21 +1,30 @@ -import { observable, action } from 'mobx'; +import { observable, action, makeObservable } from 'mobx'; import StoreBase from './StoreBase'; import Citation from './Citation'; import Config from './Config'; class AppStore extends StoreBase { + constructor() { + super(); + makeObservable( this, { + version: observable, + showAppSnack: observable, + setAppSnack: action, + clearAppSnack: action, + } ); + } citation = new Citation(); config = new Config(); - @observable version = undefined; + version = undefined; - @observable showAppSnack = false; + showAppSnack = false; - @action setAppSnack = () => { + setAppSnack = () => { this.showAppSnack = true; }; - @action clearAppSnack = () => { + clearAppSnack = () => { this.showAppSnack = false; }; } diff --git a/src/app/store/AstralTree.js b/src/app/store/AstralTree.js index 2450c18b..e1b7f400 100644 --- a/src/app/store/AstralTree.js +++ b/src/app/store/AstralTree.js @@ -1,12 +1,15 @@ -import { action } from 'mobx'; +import { action, makeObservable } from 'mobx'; import InputFile from './InputFile'; class AstralTree extends InputFile { - @action - remove = () => { - this.run.removeAstralTree(); - }; + constructor( ...args ) { + super( ...args ); + makeObservable( this, { remove: action } ); + } + remove = () => { + this.run.removeAstralTree(); + }; } export default AstralTree; diff --git a/src/app/store/Citation.js b/src/app/store/Citation.js index 788b8ae4..731b3013 100644 --- a/src/app/store/Citation.js +++ b/src/app/store/Citation.js @@ -1,7 +1,17 @@ -import { observable, action, computed } from 'mobx'; +import { observable, action, computed, makeObservable } from 'mobx'; export default class Citation { - @observable visible = false; + constructor() { + makeObservable( this, { + visible: observable, + format: observable, + setFormat: action, + allText: computed, + show: action, + hide: action, + } ); + } + visible = false; formats = [ { value: 'txt', name: 'Plain text' }, @@ -9,8 +19,8 @@ export default class Citation { { value: 'bib', name: 'BibTeX' }, ]; - @observable format = 'txt'; - @action setFormat = ( format ) => { + format = 'txt'; + setFormat = ( format ) => { this.format = format; }; @@ -190,19 +200,16 @@ ER - `, }, ]; - @computed get allText() { return this.content.map( ( ref ) => ref[this.format] ).join( '\n' ); } - @action - show = () => { - this.visible = true; - }; - @action - hide = () => { - this.visible = false; - }; + show = () => { + this.visible = true; + }; + hide = () => { + this.visible = false; + }; copyToClipboard = async () => { const { rendererBridge } = /** @type {any} */ ( window ); diff --git a/src/app/store/Config.js b/src/app/store/Config.js index dda5676c..ba9cd58e 100644 --- a/src/app/store/Config.js +++ b/src/app/store/Config.js @@ -1,9 +1,13 @@ -import { observable, action, runInAction } from 'mobx'; +import { observable, action, runInAction, makeObservable } from 'mobx'; import StoreBase, { runEvents } from './StoreBase'; export default class Config extends StoreBase { constructor() { super(); + makeObservable( this, { + isDarkMode: observable, + setDarkMode: action, + } ); this.listen(); const { rendererBridge } = /** @type {any} */ ( window ); rendererBridge.getDarkMode().then( ( value ) => { @@ -13,15 +17,14 @@ export default class Config extends StoreBase { } ); } - @observable isDarkMode = false; + isDarkMode = false; - @action - setDarkMode = ( value ) => { - value = !!value; - this.isDarkMode = value; - const { rendererBridge } = /** @type {any} */ ( window ); - void rendererBridge.setDarkMode( value ); - }; + setDarkMode = ( value ) => { + value = !!value; + this.isDarkMode = value; + const { rendererBridge } = /** @type {any} */ ( window ); + void rendererBridge.setDarkMode( value ); + }; onLightMode = () => { this.setDarkMode( false ); diff --git a/src/app/store/FinalAlignment.js b/src/app/store/FinalAlignment.js new file mode 100644 index 00000000..3a8892ad --- /dev/null +++ b/src/app/store/FinalAlignment.js @@ -0,0 +1,224 @@ +import { observable, computed, action, makeObservable } from 'mobx'; +import union from 'lodash/union'; +import intersection from 'lodash/intersection'; + +import FinalPartition from './FinalPartition'; +import { getFinalDataType } from '../../common/typecheckAlignment'; +import { join } from '../paths'; + +class FinalAlignment { + constructor( run ) { + makeObservable( this, { + filename: computed, + dir: computed, + path: computed, + parsingComplete: observable, + numAlignments: computed, + fillTaxonGapsWithEmptySeqeunces: observable, + setFillTaxonGapsWithEmptySeqeunces: action, + taxons: computed, + numSequences: computed, + length: computed, + hasInvariantSites: computed, + dataType: computed, + modelFlagName: computed, + partitionFilePath: computed, + partitionFileContent: computed, + openFile: action, + openPartition: action, + showFileInFolder: action, + openFolder: action, + writeConcatenatedAlignmentAndPartition: action, + writeConcatenatedAlignment: action, + writePartition: action, + } ); + this.run = run; + this.partition = new FinalPartition( run ); + } + + get filename() { + if ( this.numAlignments === 1 ) { + return this.run.alignments[0].filename; + } + return `RAxML_${this.run.outputNameSafe}_concat.txt`; + } + + get dir() { + if ( this.numAlignments === 1 ) { + return this.run.alignments[0].dir; + } + return this.run.outputDir; + } + + get path() { + if ( this.numAlignments === 1 ) { + return this.run.alignments[0].path; + } + return join( `${this.dir}`, `${this.filename}` ); + } + + parsingComplete = true; + + get numAlignments() { + return this.run.alignments.length; + } + + // By default add empty sequences to fill gaps up to the union of taxons + // else drop taxons that doesn't exist in all alignments by taking the intersection + fillTaxonGapsWithEmptySeqeunces = true; + + setFillTaxonGapsWithEmptySeqeunces = ( checked ) => { + this.fillTaxonGapsWithEmptySeqeunces = checked; + }; + + get taxons() { + const setMethod = this.fillTaxonGapsWithEmptySeqeunces + ? union + : intersection; + return setMethod.apply( + setMethod, + this.run.alignments.map( ( { taxons } ) => taxons ), + ); + } + + get numSequences() { + return this.taxons.length; + } + + get length() { + return this.run.alignments.reduce( + ( sumLength, alignment ) => sumLength + alignment.length, + 0, + ); + } + + get hasInvariantSites() { + // If any one of the alignments has invariant sites return true + for ( const alignment of this.run.alignments ) { + if ( alignment.hasInvariantSites ) { + return true; + } + } + return false; + } + + // get dataType() { + // const numAlignments = this.numAlignments; + // if (numAlignments === 0) { + // return 'none'; + // } + // const firstType = this.run.alignments[0].dataType; + // if (numAlignments === 1) { + // return firstType; + // } + // for (let i = 1; i < numAlignments; ++i) { + // if (this.run.alignments[i].dataType !== firstType) { + // return 'mixed'; + // } + // } + // return firstType; + // } + + get dataType() { + const { alignments } = this.run; + const dataTypes = alignments.map( ( { dataType } ) => dataType ); + return getFinalDataType( dataTypes ); + } + + get modelFlagName() { + const {numAlignments} = this; + if ( numAlignments === 0 ) { + return 'none'; + } + const first = this.run.alignments[0].modelFlagName; + if ( numAlignments === 1 ) { + return first; + } + return first; + } + + get partitionFilePath() { + if ( this.partition.isDefault ) { + return ''; + } + const suffix = this.numAlignments > 1 + ? '_concat' + : ''; + return join( + `${this.dir}`, + `RAxML_${this.run.outputNameSafe}${suffix}.part.txt`, + ); + } + + get partitionFileContent() { + return this.partition.text; + } + + openFile = async () => { + await this.writeConcatenatedAlignment(); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.openPath( this.path ); + }; + + openPartition = async () => { + await this.writeConcatenatedAlignmentAndPartition(); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.openPath( this.partitionFilePath ); + }; + + showFileInFolder = async () => { + await this.writeConcatenatedAlignment(); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.showItemInFolder( this.path ); + }; + + openFolder = async () => { + await this.writeConcatenatedAlignmentAndPartition(); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.showItemInFolder( this.dir ); + }; + + writeConcatenatedAlignmentAndPartition = async () => { + await this.writeConcatenatedAlignment(); + await this.writePartition(); + }; + + writeConcatenatedAlignment = async () => { + const { taxons, numSequences } = this; + try { + console.log( + `Write concatenated alignment in FASTA format to ${this.path}..`, + ); + let text = ''; + for ( let i = 0; i < numSequences; ++i ) { + for ( let j = 0; j < this.numAlignments; ++j ) { + if ( j === 0 ) { + const prefix = i === 0 + ? '>' + : '\n>'; + text += `${prefix}${taxons[i]}\n`; + } + text += this.run.alignments[j].getSequenceCode( taxons[i] ); + } + } + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.writeFile( this.path, text ); + } catch ( err ) { + console.error( 'Error writing concatenated alignment:', err ); + throw err; + } + }; + + writePartition = async () => { + try { + console.log( `Writing partition to ${this.partitionFilePath}...` ); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.writeFile( this.partitionFilePath, this.partitionFileContent ); + } catch ( err ) { + console.error( 'Error writing partition:', err ); + throw err; + } + }; +} + +export default FinalAlignment; diff --git a/src/app/store/FinalPartition.js b/src/app/store/FinalPartition.js new file mode 100644 index 00000000..36bdfb68 --- /dev/null +++ b/src/app/store/FinalPartition.js @@ -0,0 +1,43 @@ +import { computed, makeObservable } from 'mobx'; + +class FinalPartition { + constructor( run ) { + makeObservable( this, { + text: computed, + isDefault: computed, + isComplete: computed, + } ); + this.run = run; + } + /* + Example: + DNA, gene1 = 1-3676 + BIN, morph = 3677-3851 + */ + get text() { + if ( !this.run.haveAlignments ) { + return ''; + } + const partitionTexts = []; + let total = 0; + this.run.alignments.forEach( ( alignment, index ) => { + partitionTexts.push( alignment.partition.transform( total, `${index}_` ) ); + total += alignment.length; + } ); + return partitionTexts.join( '\n' ); + } + get isDefault() { + return ( + this.run.alignments.length === 0 || + ( this.run.alignments.length === 1 && + this.run.alignments[0].partition.isDefault ) + ); + } + get isComplete() { + return this.run.alignments.every( + ( alignment ) => alignment.partition.isComplete, + ); + } +} + +export default FinalPartition; diff --git a/src/app/store/InputFile.js b/src/app/store/InputFile.js index 347634b0..d9f93945 100644 --- a/src/app/store/InputFile.js +++ b/src/app/store/InputFile.js @@ -1,4 +1,4 @@ -import { observable, computed, action } from 'mobx'; +import { observable, computed, action, makeObservable } from 'mobx'; import { base, dir, name } from '../paths'; import StoreBase from './StoreBase'; @@ -8,54 +8,57 @@ class InputFile extends StoreBase { constructor( run, path ) { super(); + makeObservable( this, { + path: observable, + id: computed, + name: computed, + dir: computed, + base: computed, + filename: computed, + ok: computed, + openFile: action, + showFileInFolder: action, + } ); this.run = run; this.path = path; } // Observable because it may change on correcting errors or reformating of alignments - @observable path = ''; + path = ''; - @computed get id() { return `${this.run.id}_${this.path}`; } - @computed get name() { return name( this.path ); } - @computed get dir() { return dir( this.path ); } - @computed get base() { return base( this.path ); } - @computed get filename() { return base( this.path ); } - @computed get ok() { return this.path !== ''; } - @action - openFile = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.openPath( this.path ); - }; - - @action - showFileInFolder = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.showItemInFolder( this.path ); - }; + openFile = async () => { + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.openPath( this.path ); + }; + + showFileInFolder = async () => { + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.showItemInFolder( this.path ); + }; } export default InputFile; diff --git a/src/app/store/InputFile.test.js b/src/app/store/InputFile.test.js new file mode 100644 index 00000000..570b0636 --- /dev/null +++ b/src/app/store/InputFile.test.js @@ -0,0 +1,133 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import AstralTree from './AstralTree'; +import InputFile from './InputFile'; +import StoreBase from './StoreBase'; + +let bridge; + +beforeEach( () => { + bridge = { + getVersion: jest.fn( () => Promise.resolve( '2.0.0' ) ), + openPath: jest.fn( () => Promise.resolve() ), + showItemInFolder: jest.fn( () => Promise.resolve() ), + }; + window.rendererBridge = bridge; +} ); + +// Records every value an autorun sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +const run = { id: 'run1', removeAstralTree: jest.fn() }; + +describe( 'StoreBase', () => { + it( 'initialises the version from the renderer bridge', async () => { + const store = new StoreBase(); + expect( store.version ).toBeUndefined(); + await Promise.resolve(); + expect( bridge.getVersion ).toHaveBeenCalledTimes( 1 ); + expect( store.version ).toBe( '2.0.0' ); + } ); + + it( 'subscribe registers a bridge listener and unlisten stops them all', () => { + const stopA = jest.fn(); + const stopB = jest.fn(); + bridge.onRunStdout = jest.fn( () => stopA ); + bridge.onRunStderr = jest.fn( () => stopB ); + const store = new StoreBase(); + const listener = () => {}; + store.subscribe( 'onRunStdout', listener ); + store.subscribe( 'onRunStderr', listener ); + expect( bridge.onRunStdout ).toHaveBeenCalledWith( listener ); + expect( store.eventStops ).toHaveLength( 2 ); + store.unlisten(); + expect( stopA ).toHaveBeenCalledTimes( 1 ); + expect( stopB ).toHaveBeenCalledTimes( 1 ); + expect( store.eventStops ).toHaveLength( 0 ); + } ); + + it( 'dispose stops the listeners', () => { + const stop = jest.fn(); + bridge.onRunStdout = () => stop; + const store = new StoreBase(); + store.subscribe( 'onRunStdout', () => {} ); + store.dispose(); + expect( stop ).toHaveBeenCalledTimes( 1 ); + } ); +} ); + +describe( 'InputFile', () => { + it( 'derives its parts from the path', () => { + const file = new InputFile( run, '/data/trees/astral.tre' ); + expect( file.id ).toBe( 'run1_/data/trees/astral.tre' ); + expect( file.name ).toBe( 'astral' ); + expect( file.dir ).toBe( '/data/trees' ); + expect( file.base ).toBe( 'astral.tre' ); + expect( file.filename ).toBe( 'astral.tre' ); + expect( file.ok ).toBe( true ); + } ); + + it( 'is not ok with an empty path', () => { + expect( new InputFile( run, '' ).ok ).toBe( false ); + } ); + + it( 'every computed updates when the path changes', () => { + const file = new InputFile( run, '/a/one.tre' ); + const keys = ['id', 'name', 'dir', 'base', 'filename', 'ok']; + const tracked = Object.fromEntries( keys.map( ( key ) => [key, track( () => file[key] )] ) ); + runInAction( () => { + file.path = ''; + } ); + runInAction( () => { + file.path = '/b/two.nwk'; + } ); + expect( tracked.id.seen ).toEqual( ['run1_/a/one.tre', 'run1_', 'run1_/b/two.nwk'] ); + expect( tracked.name.seen ).toEqual( ['one', '', 'two'] ); + expect( tracked.dir.seen ).toEqual( ['/a', '', '/b'] ); + expect( tracked.base.seen ).toEqual( ['one.tre', '', 'two.nwk'] ); + expect( tracked.filename.seen ).toEqual( ['one.tre', '', 'two.nwk'] ); + expect( tracked.ok.seen ).toEqual( [true, false, true] ); + keys.forEach( ( key ) => tracked[key].stop() ); + } ); + + it( 'openFile asks the bridge to open the path', async () => { + const file = new InputFile( run, '/a/one.tre' ); + await file.openFile(); + expect( bridge.openPath ).toHaveBeenCalledWith( '/a/one.tre' ); + } ); + + it( 'showFileInFolder asks the bridge to reveal the path', async () => { + const file = new InputFile( run, '/a/one.tre' ); + await file.showFileInFolder(); + expect( bridge.showItemInFolder ).toHaveBeenCalledWith( '/a/one.tre' ); + } ); + + it( 'initialises the version like any store', async () => { + const file = new InputFile( run, '/a/one.tre' ); + await Promise.resolve(); + expect( file.version ).toBe( '2.0.0' ); + } ); +} ); + +describe( 'AstralTree', () => { + it( 'remove removes the tree from its run', () => { + run.removeAstralTree.mockClear(); + new AstralTree( run, '/a/one.tre' ).remove(); + expect( run.removeAstralTree ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'inherits the input file computeds', () => { + const tree = new AstralTree( run, '/a/one.tre' ); + const { seen, stop } = track( () => tree.name ); + runInAction( () => { + tree.path = '/a/other.tre'; + } ); + expect( seen ).toEqual( ['one', 'other'] ); + stop(); + } ); +} ); diff --git a/src/app/store/Option.js b/src/app/store/Option.js index 6898fd1b..36aa7279 100644 --- a/src/app/store/Option.js +++ b/src/app/store/Option.js @@ -1,4 +1,4 @@ -import { observable, computed, action } from 'mobx'; +import { observable, computed, action, makeObservable } from 'mobx'; import { mixed } from 'yup'; class Option { @@ -19,6 +19,15 @@ class Option { hoverInfo, { schema = undefined, allowOnlyValidChange = false, helperText = '' } = {}, ) { + makeObservable( this, { + value: observable, + setValue: action, + reset: action, + isDefault: computed, + error: computed, + haveError: computed, + errorMessage: computed, + } ); this.run = run; this.defaultValue = defaultValue; this.title = title; @@ -29,23 +38,24 @@ class Option { : mixed(); this.allowOnlyValidChange = allowOnlyValidChange; this.helperText = helperText; + this.value = defaultValue; } - @observable value = this.defaultValue; - @action setValue = ( value ) => { + value; + setValue( value ) { const isValid = this.schema.isValidSync( value ); if ( !this.allowOnlyValidChange || isValid ) { this.value = isValid ? this.schema.cast( value ) : value; } - }; - @action reset() { + } + reset() { this.value = this.defaultValue; } - @computed get isDefault() { + get isDefault() { return this.value === this.defaultValue; } - @computed get error() { + get error() { try { this.schema.validateSync( this.value ); return null; @@ -53,10 +63,10 @@ class Option { return err; } } - @computed get haveError() { + get haveError() { return this.error !== null; } - @computed get errorMessage() { + get errorMessage() { return this.haveError ? this.error.message : ''; diff --git a/src/app/store/Option.test.js b/src/app/store/Option.test.js new file mode 100644 index 00000000..c1224320 --- /dev/null +++ b/src/app/store/Option.test.js @@ -0,0 +1,83 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; +import * as yup from 'yup'; + +import Option from './Option'; + +const positive = () => new Option( null, 2, 'Count', 'desc', 'hover', { + schema: yup.number().positive(), +} ); + +it( 'starts at the default value', () => { + const option = positive(); + expect( option.value ).toBe( 2 ); + expect( option.isDefault ).toBe( true ); + expect( option.error ).toBeNull(); + expect( option.haveError ).toBe( false ); + expect( option.errorMessage ).toBe( '' ); +} ); + +it( 'sets a value, casting it through the schema', () => { + const option = positive(); + option.setValue( '5' ); + expect( option.value ).toBe( 5 ); + expect( option.isDefault ).toBe( false ); +} ); + +it( 'keeps an invalid value as given and reports its error', () => { + const option = positive(); + option.setValue( -1 ); + expect( option.value ).toBe( -1 ); + expect( option.error ).toBeInstanceOf( yup.ValidationError ); + expect( option.haveError ).toBe( true ); + expect( option.errorMessage ).toBe( option.error.message ); + expect( option.errorMessage ).not.toBe( '' ); +} ); + +it( 'ignores an invalid value when only valid changes are allowed', () => { + const option = new Option( null, 'a', 'Name', 'desc', 'hover', { + schema: yup.string().max( 3 ), + allowOnlyValidChange: true, + } ); + option.setValue( 'toolong' ); + expect( option.value ).toBe( 'a' ); + option.setValue( 'abc' ); + expect( option.value ).toBe( 'abc' ); +} ); + +it( 'accepts any value without a schema', () => { + const option = new Option( null, 'x', 'Title', 'desc', 'hover' ); + option.setValue( 42 ); + expect( option.value ).toBe( 42 ); + expect( option.error ).toBeNull(); + expect( option.helperText ).toBe( '' ); +} ); + +it( 'resets to the default value', () => { + const option = positive(); + option.setValue( -1 ); + option.reset(); + expect( option.value ).toBe( 2 ); + expect( option.isDefault ).toBe( true ); + expect( option.haveError ).toBe( false ); +} ); + +it( 'updates computeds and reactions when value changes', () => { + const option = positive(); + const seen = []; + const dispose = autorun( () => { + seen.push( [option.isDefault, option.errorMessage === ''] ); + } ); + runInAction( () => { + option.value = -3; + } ); + runInAction( () => { + option.value = 2; + } ); + dispose(); + expect( seen ).toEqual( [ + [true, true], + [false, false], + [true, true], + ] ); +} ); diff --git a/src/app/store/OutGroup.test.js b/src/app/store/OutGroup.test.js new file mode 100644 index 00000000..48433b2e --- /dev/null +++ b/src/app/store/OutGroup.test.js @@ -0,0 +1,105 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import RunList from './RunList'; +import { runEvents } from './StoreBase'; + +// A run subscribes to bridge events when it is created. +beforeEach( () => { + const bridge = { cancelRun: jest.fn(), getVersion: () => Promise.resolve( '2.0.0' ) }; + for ( const name of Object.values( runEvents ) ) { + bridge[name] = () => () => {}; + } + window.rendererBridge = bridge; +} ); + +const newRun = () => new RunList().activeRun; + +const setAlignments = ( run, taxons ) => runInAction( () => { + run.alignments = [{ taxons }]; +} ); + +// Records every value an autorun sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +describe( 'OutGroup', () => { + it( 'starts at none', () => { + const { outGroup } = newRun(); + expect( outGroup.value ).toEqual( [''] ); + expect( outGroup.multiple ).toBe( true ); + expect( outGroup.cmdValue ).toBe( '' ); + } ); + + it( 'options are none followed by the taxa, and follow the alignments', () => { + const run = newRun(); + const { seen, stop } = track( () => run.outGroup.options.map( ( o ) => o.value ) ); + setAlignments( run, ['a', 'b'] ); + expect( run.outGroup.options ).toEqual( [ + { value: '', title: '' }, + { value: 'a', title: 'a' }, + { value: 'b', title: 'b' }, + ] ); + expect( seen ).toEqual( [[''], ['', 'a', 'b']] ); + stop(); + } ); + + describe( 'setValue', () => { + it( 'choosing a taxon clears none', () => { + const { outGroup } = newRun(); + outGroup.setValue( ['', 'a'] ); + expect( outGroup.value ).toEqual( ['a'] ); + } ); + + it( 'choosing none clears the taxa', () => { + const { outGroup } = newRun(); + outGroup.setValue( ['a', 'b'] ); + outGroup.setValue( ['a', 'b', ''] ); + expect( outGroup.value ).toEqual( [''] ); + } ); + + it( 'keeps several taxa', () => { + const { outGroup } = newRun(); + outGroup.setValue( ['a', 'b'] ); + expect( outGroup.value ).toEqual( ['a', 'b'] ); + } ); + } ); + + it( 'reset returns to none', () => { + const { outGroup } = newRun(); + outGroup.setValue( ['a'] ); + outGroup.reset(); + expect( outGroup.value ).toEqual( [''] ); + expect( outGroup.isDefault ).toBe( false ); // default is an array compared by identity + } ); + + it( 'cmdValue is empty for none and comma-joined for taxa, and follows value', () => { + const { outGroup } = newRun(); + const { seen, stop } = track( () => outGroup.cmdValue ); + runInAction( () => { + outGroup.value = ['a', 'b']; + } ); + runInAction( () => { + outGroup.value = ['']; + } ); + expect( seen ).toEqual( ['', 'a,b', ''] ); + stop(); + } ); + + it( 'notAvailable follows alignments and the analysis', () => { + const run = newRun(); + const { seen, stop } = track( () => run.outGroup.notAvailable ); + expect( run.outGroup.notAvailable ).toBe( true ); // no alignments + setAlignments( run, ['a'] ); + expect( run.outGroup.notAvailable ).toBe( false ); // default analysis takes an outgroup + runInAction( () => { + run.analysis.value = 'AS'; // takes no outgroup + } ); + expect( run.outGroup.notAvailable ).toBe( true ); + expect( seen ).toEqual( [true, false, true] ); + stop(); + } ); +} ); diff --git a/src/app/store/Part.test.js b/src/app/store/Part.test.js new file mode 100644 index 00000000..057e58f8 --- /dev/null +++ b/src/app/store/Part.test.js @@ -0,0 +1,527 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Alignment from './Alignment'; +import Run from './Run'; +import { + CODON_NONE, + CODON_SPECIFIC, + CODON_THIRD, + CodonModels, +} from './PartOptions'; + +// The alignment subscribes to bridge events and parses its file on creation. +beforeEach( () => { + window.rendererBridge = { + parseAlignment: () => new Promise( () => {} ), + onModelSelectionSuccess: () => () => {}, + onModelSelectionFailure: () => () => {}, + onRunStdout: () => () => {}, + onRunStderr: () => () => {}, + }; +} ); + +// The run defaults to raxml-ng, whose partition type is the model command; classic raxml uses the data type. +function makeAlignment( { dataType = 'dna', length = 100, ng = false } = {} ) { + const run = new Run( {}, 1 ); + const alignment = new Alignment( run, '/data/a.fasta' ); + runInAction( () => { + if ( !ng ) { + run.binary.value = run.binary.options + .map( ( o ) => o.value ) + .find( ( v ) => /raxml/i.test( v ) && !v.includes( 'raxml-ng' ) ); + } + alignment.dataType = dataType; + alignment.length = length; + } ); + return alignment; +} + +// Records every value an autorun sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +const part = ( alignment, values ) => { + const { partition } = alignment; + runInAction( () => { + Object.entries( values ).forEach( ( [key, value] ) => { + partition.partToAdd[key].value = value; + } ); + } ); + return partition.partToAdd; +}; + +describe( 'Part', () => { + it( 'starts from the alignment: default part covers all sites', () => { + const { partition } = makeAlignment(); + expect( partition.defaultPartition.values ).toEqual( { + type: 'DNA', + aaType: 'BLOSUM62', + name: 'part_1', + start: 1, + end: 100, + codon: CODON_NONE, + } ); + expect( partition.partToAdd.end.value ).toBe( 1 ); + } ); + + it( 'typePadded pads the final type to twelve characters', () => { + const alignment = makeAlignment(); + const { typePadded } = alignment.partition.partToAdd; + expect( typePadded ).toBe( 'DNA, ' ); + expect( typePadded ).toHaveLength( 12 ); + } ); + + it( 'a reaction sees typePadded change with the alignment data type', () => { + const alignment = makeAlignment(); + const { seen, stop } = track( () => alignment.partition.partToAdd.typePadded ); + runInAction( () => { + alignment.dataType = 'binary'; + } ); + expect( seen ).toEqual( ['DNA, ', 'BIN, '] ); + stop(); + } ); + + it( 'typePadded uses the model command under raxml-ng', () => { + const alignment = makeAlignment( { ng: true } ); + const { seen, stop } = track( () => alignment.partition.partToAdd.typePadded ); + runInAction( () => { + alignment.ngInvariantSites.value = true; + } ); + expect( seen[0] ).toBe( ', ' ); + expect( seen ).toHaveLength( 2 ); + expect( seen[1] ).toBe( `${alignment.ngSubstitutionModelCmd},`.padEnd( 12 ) ); + stop(); + } ); + + it( 'transform without codons writes one row', () => { + const p = part( makeAlignment(), { name: 'g', start: 3, end: 9 } ); + expect( p.transform() ).toBe( 'DNA, g = 3-9' ); + expect( p.transform( 10, 'x_' ) ).toBe( 'DNA, x_g = 13-19' ); + } ); + + it( 'transform with codon specific writes three rows', () => { + const p = part( makeAlignment(), { + name: 'g', + start: 1, + end: 9, + codon: CODON_SPECIFIC, + } ); + expect( p.transform() ).toBe( + [ + 'DNA, g_codon1 = 1-9\\3', + 'DNA, g_codon2 = 2-9\\3', + 'DNA, g_codon3 = 3-9\\3', + ].join( '\n' ), + ); + expect( p.transform( 100, 'p_' ).split( '\n' )[1] ).toBe( + 'DNA, p_g_codon2 = 102-109\\3', + ); + } ); + + it( 'transform with third codon writes the first two codons and the third', () => { + const p = part( makeAlignment(), { + name: 'g', + start: 1, + end: 9, + codon: CODON_THIRD, + } ); + expect( p.transform() ).toBe( + [ + 'DNA, g_codon1and2 = 1-9\\3, 2-9\\3', + 'DNA, g_codon3 = 3-9\\3', + ].join( '\n' ), + ); + } ); + + it( 'transform throws on an unknown codon model', () => { + const p = part( makeAlignment(), { codon: 'Bogus' } ); + expect( () => p.transform() ).toThrow( 'Codon type Bogus not recognized.' ); + } ); + + it( 'text is the transform and a reaction sees it change', () => { + const alignment = makeAlignment(); + const p = alignment.partition.partToAdd; + const { seen, stop } = track( () => p.text ); + expect( p.text ).toBe( p.transform() ); + runInAction( () => { + p.name.value = 'other'; + } ); + expect( seen ).toEqual( ['DNA, part_1 = 1-1', 'DNA, other = 1-1'] ); + stop(); + } ); + + it( 'parse accepts a row and returns nothing', () => { + const p = makeAlignment().partition.partToAdd; + expect( p.parse( 'DNA, g = 1-9' ) ).toBeUndefined(); + } ); + + it( 'values collects every option value and tracks changes', () => { + const p = makeAlignment().partition.partToAdd; + const { seen, stop } = track( () => p.values.start ); + runInAction( () => { + p.start.value = 4; + } ); + expect( seen ).toEqual( [1, 4] ); + expect( p.values ).toEqual( { + type: 'DNA', + aaType: 'BLOSUM62', + name: 'part_1', + start: 4, + end: 1, + codon: CODON_NONE, + } ); + stop(); + } ); + + it( 'clone copies the values into an independent part', () => { + const p = part( makeAlignment(), { name: 'g', start: 2, end: 8 } ); + const copy = p.clone(); + expect( copy ).not.toBe( p ); + expect( copy.values ).toEqual( p.values ); + expect( copy.partition ).toBe( p.partition ); + runInAction( () => { + p.name.value = 'changed'; + } ); + expect( copy.name.value ).toBe( 'g' ); + } ); +} ); + +describe( 'part options', () => { + it( 'PartType.finalValue follows the alignment partition type', () => { + const alignment = makeAlignment(); + const { type } = alignment.partition.partToAdd; + const { seen, stop } = track( () => type.finalValue ); + runInAction( () => { + alignment.dataType = 'multistate'; + } ); + expect( seen ).toEqual( ['DNA', 'MULTI'] ); + stop(); + } ); + + it( 'PartType.finalValue is the amino acid model for protein', () => { + const alignment = makeAlignment( { dataType: 'protein' } ); + const { type, aaType } = alignment.partition.partToAdd; + const { seen, stop } = track( () => type.finalValue ); + runInAction( () => { + aaType.value = 'WAG'; + } ); + expect( seen ).toEqual( ['BLOSUM62', 'WAG'] ); + stop(); + } ); + + it( 'PartType.finalValue is the own value for a mixed alignment', () => { + const alignment = makeAlignment( { dataType: 'mixed' } ); + const { type } = alignment.partition.partToAdd; + const { seen, stop } = track( () => type.finalValue ); + runInAction( () => { + type.value = 'BIN'; + } ); + expect( seen ).toEqual( [expect.anything(), 'BIN'] ); + expect( type.finalValue ).toBe( 'BIN' ); + stop(); + } ); + + it( 'PartType.finalValue is the amino acid model when the part itself is protein', () => { + const alignment = makeAlignment( { dataType: 'mixed' } ); + const { type } = alignment.partition.partToAdd; + runInAction( () => { + type.value = 'protein'; + } ); + expect( type.finalValue ).toBe( 'BLOSUM62' ); + } ); + + it( 'PartType.options and notAvailable follow the alignment data type', () => { + const alignment = makeAlignment(); + const { type } = alignment.partition.partToAdd; + const seen = track( () => [type.options.map( ( o ) => o.value ), type.notAvailable] ); + expect( seen.seen[0] ).toEqual( [['dna'], true] ); + runInAction( () => { + alignment.dataType = 'mixed'; + } ); + expect( seen.seen[1] ).toEqual( [['DNA', 'BIN', 'MULTI', 'protein'], false] ); + runInAction( () => { + alignment.dataType = ''; + } ); + expect( type.options.map( ( o ) => o.title ) ).toEqual( [ + 'DNA', + 'BIN', + 'MULTI', + 'protein', + ] ); + expect( type.notAvailable ).toBe( true ); + seen.stop(); + } ); + + it( 'PartType accepts only strings', () => { + const { type } = makeAlignment().partition.partToAdd; + type.setValue( 5 ); + expect( type.value ).toBe( '5' ); + type.setValue( {} ); + expect( type.value ).toBe( '5' ); + } ); + + it( 'PartAAType offers the amino acid matrices and is available for protein only', () => { + const alignment = makeAlignment(); + const { aaType } = alignment.partition.partToAdd; + const { seen, stop } = track( () => aaType.notAvailable ); + expect( aaType.options.length ).toBeGreaterThan( 1 ); + expect( aaType.options[0] ).toEqual( { + value: aaType.options[0].title, + title: aaType.options[0].value, + } ); + expect( aaType.options.map( ( o ) => o.value ) ).toContain( 'WAG' ); + runInAction( () => { + alignment.dataType = 'protein'; + } ); + expect( seen ).toEqual( [true, false] ); + stop(); + } ); + + it( 'PartName is always available and keeps its value as a string', () => { + const { name } = makeAlignment().partition.partToAdd; + expect( name.notAvailable ).toBe( false ); + name.setValue( 'gene' ); + expect( name.value ).toBe( 'gene' ); + } ); + + it( 'PartStart is always available, disabled and stores invalid input as given', () => { + const { start } = makeAlignment().partition.partToAdd; + expect( start.notAvailable ).toBe( false ); + expect( start.disabled ).toBe( true ); + start.setValue( '7' ); + expect( start.value ).toBe( 7 ); + start.setValue( 'abc' ); + expect( start.value ).toBe( 'abc' ); + } ); + + it( 'PartEnd.min follows the start and the codon model', () => { + const alignment = makeAlignment(); + const { start, end, codon } = alignment.partition.partToAdd; + const { seen, stop } = track( () => end.min ); + runInAction( () => { + start.value = 5; + } ); + runInAction( () => { + codon.value = CODON_SPECIFIC; + } ); + expect( seen ).toEqual( [1, 5, 7] ); + stop(); + } ); + + it( 'PartEnd.max follows the alignment length', () => { + const alignment = makeAlignment(); + const { end } = alignment.partition.partToAdd; + const { seen, stop } = track( () => end.max ); + runInAction( () => { + alignment.length = 250; + } ); + expect( seen ).toEqual( [100, 250] ); + expect( end.notAvailable ).toBe( false ); + stop(); + } ); + + it( 'PartEnd reports an error outside [min, max] and a reaction sees it', () => { + const alignment = makeAlignment(); + const { end } = alignment.partition.partToAdd; + const { seen, stop } = track( () => end.haveError ); + end.setValue( 50 ); + expect( end.haveError ).toBe( false ); + expect( end.errorMessage ).toBe( '' ); + end.setValue( 101 ); + expect( end.haveError ).toBe( true ); + expect( end.errorMessage ).toBe( 'Must be in interval [1, 100]' ); + runInAction( () => { + alignment.length = 200; + } ); + expect( end.haveError ).toBe( false ); + expect( seen ).toEqual( [false, true, false] ); + stop(); + } ); + + it( 'PartCodon offers the codon models and is available for a DNA part to add only', () => { + const alignment = makeAlignment(); + const { codon, type } = alignment.partition.partToAdd; + const { seen, stop } = track( () => codon.notAvailable ); + expect( codon.options.map( ( o ) => o.value ) ).toEqual( CodonModels ); + expect( seen ).toEqual( [false] ); + runInAction( () => { + type.value = 'BIN'; + } ); + expect( seen ).toEqual( [false, true] ); + stop(); + } ); +} ); + +describe( 'Partition', () => { + const add = ( partition, values ) => { + runInAction( () => { + Object.entries( values ).forEach( ( [key, value] ) => { + partition.partToAdd[key].value = value; + } ); + } ); + partition.addPart(); + }; + + it( 'is the default partition until a part is added', () => { + const alignment = makeAlignment(); + const { partition } = alignment; + expect( partition.isDefault ).toBe( true ); + expect( partition.isMixed ).toBe( false ); + expect( partition.maxEndValue ).toBe( 100 ); + expect( partition.currentEndValue ).toBe( 100 ); + expect( partition.isComplete ).toBe( true ); + expect( partition.nonDefaultPartitionComplete ).toBe( false ); + expect( partition.progress ).toBe( 100 ); + expect( partition.text ).toBe( 'DNA, part_1 = 1-100' ); + expect( partition.transform( 5, 'x_' ) ).toBe( 'DNA, x_part_1 = 6-105' ); + } ); + + it( 'isMixed follows the alignment data type', () => { + const alignment = makeAlignment(); + const { seen, stop } = track( () => alignment.partition.isMixed ); + runInAction( () => { + alignment.dataType = 'mixed'; + } ); + expect( seen ).toEqual( [false, true] ); + stop(); + } ); + + it( 'addPart appends a copy and moves partToAdd past it', () => { + const { partition } = makeAlignment(); + const { seen, stop } = track( () => [partition.isDefault, partition.currentEndValue] ); + add( partition, { end: 40, codon: CODON_SPECIFIC } ); + expect( partition.parts ).toHaveLength( 1 ); + expect( partition.parts[0].values ).toMatchObject( { + name: 'part_1', + start: 1, + end: 40, + codon: CODON_SPECIFIC, + } ); + expect( partition.isDefault ).toBe( false ); + expect( partition.currentEndValue ).toBe( 40 ); + expect( partition.progress ).toBe( 40 ); + expect( partition.isComplete ).toBe( false ); + expect( partition.nonDefaultPartitionComplete ).toBe( false ); + expect( partition.partToAdd.codon.value ).toBe( CODON_NONE ); + expect( partition.partToAdd.start.value ).toBe( 41 ); + expect( partition.partToAdd.end.value ).toBe( 41 ); + expect( partition.partToAdd.name.value ).toBe( 'part_2' ); + expect( seen ).toEqual( [[true, 100], [false, 40]] ); + stop(); + } ); + + it( 'addPart appends _1 to a name without a trailing number', () => { + const { partition } = makeAlignment(); + add( partition, { name: 'gene', end: 10 } ); + expect( partition.partToAdd.name.value ).toBe( 'gene_1' ); + } ); + + it( 'addPart completing the alignment leaves partToAdd and disables adding', () => { + const { partition } = makeAlignment(); + const { seen, stop } = track( () => partition.addPartDisabled ); + add( partition, { end: 60 } ); + add( partition, { end: 100 } ); + expect( partition.isComplete ).toBe( true ); + expect( partition.nonDefaultPartitionComplete ).toBe( true ); + expect( partition.progress ).toBe( 100 ); + expect( partition.addPartDisabled ).toBe( true ); + expect( partition.partToAdd.name.value ).toBe( 'part_2' ); + expect( partition.partToAdd.start.value ).toBe( 61 ); + expect( seen ).toEqual( [false, true] ); + stop(); + } ); + + it( 'text and transform join the rows of all parts', () => { + const { partition } = makeAlignment(); + add( partition, { end: 40 } ); + add( partition, { end: 100 } ); + const expected = 'DNA, part_1 = 1-40\nDNA, part_2 = 41-100'; + expect( partition.text ).toBe( expected ); + expect( partition.transform() ).toBe( expected ); + expect( partition.transform( 10, 'a_' ) ).toBe( + 'DNA, a_part_1 = 11-50\nDNA, a_part_2 = 51-110', + ); + } ); + + it( 'haveError and errorMessage report the end position of the part to add', () => { + const { partition } = makeAlignment(); + const { seen, stop } = track( () => partition.errorMessage ); + partition.partToAdd.end.setValue( 500 ); + expect( partition.haveError ).toBe( true ); + expect( partition.addPartDisabled ).toBe( true ); + expect( partition.errorMessage ).toBe( + 'End position error: Must be in interval [1, 100]', + ); + partition.partToAdd.end.setValue( 20 ); + expect( partition.haveError ).toBe( false ); + expect( seen ).toEqual( [ + '', + 'End position error: Must be in interval [1, 100]', + '', + ] ); + stop(); + } ); + + it( 'reset drops the parts and restores partToAdd', () => { + const { partition } = makeAlignment(); + add( partition, { end: 40 } ); + partition.reset(); + expect( partition.parts ).toHaveLength( 0 ); + expect( partition.isDefault ).toBe( true ); + expect( partition.partToAdd.name.value ).toBe( 'part_1' ); + expect( partition.partToAdd.start.value ).toBe( 1 ); + expect( partition.partToAdd.end.value ).toBe( 1 ); + } ); + + it( 'reset without parts changes nothing', () => { + const { partition } = makeAlignment(); + runInAction( () => { + partition.partToAdd.name.value = 'keep'; + } ); + partition.reset(); + expect( partition.partToAdd.name.value ).toBe( 'keep' ); + } ); + + it( 'the default part end follows the alignment length once', () => { + const alignment = makeAlignment( { length: 0 } ); + const { partition } = alignment; + runInAction( () => { + alignment.length = 80; + } ); + expect( partition.defaultPartition.end.value ).toBe( 80 ); + runInAction( () => { + alignment.length = 90; + } ); + expect( partition.defaultPartition.end.value ).toBe( 80 ); + } ); + + it( 'the default part end stays put for a mixed alignment', () => { + const alignment = makeAlignment( { dataType: 'mixed', length: 0 } ); + runInAction( () => { + alignment.length = 80; + } ); + expect( alignment.partition.defaultPartition.end.value ).toBe( 0 ); + } ); + + it( 'the part types follow the alignment data type and matrix', () => { + const alignment = makeAlignment(); + const { partition } = alignment; + runInAction( () => { + alignment.dataType = 'binary'; + } ); + expect( partition.partToAdd.type.value ).toBe( 'BIN' ); + expect( partition.defaultPartition.type.value ).toBe( 'BIN' ); + runInAction( () => { + alignment.dataType = 'protein'; + alignment.aaMatrixName = 'WAG'; + } ); + expect( partition.partToAdd.type.value ).toBe( 'protein' ); + expect( partition.defaultPartition.type.value ).toBe( 'protein' ); + expect( partition.defaultPartition.aaType.value ).toBe( 'WAG' ); + expect( partition.partToAdd.aaType.value ).toBe( 'WAG' ); + } ); +} ); diff --git a/src/app/store/PartOptions.js b/src/app/store/PartOptions.js new file mode 100644 index 00000000..6a6166a9 --- /dev/null +++ b/src/app/store/PartOptions.js @@ -0,0 +1,179 @@ +import { computed, makeObservable } from 'mobx'; +import Option from './Option'; +import * as raxmlSettings from '../../settings/raxml'; +import * as yup from 'yup'; + +export const CODON_NONE = 'None'; +export const CODON_SPECIFIC = 'Codon specific'; +export const CODON_THIRD = 'Third codon'; +export const CodonModels = [CODON_NONE, CODON_SPECIFIC, CODON_THIRD]; + +class PartBase extends Option { + constructor( + part, + defaultValue, + title, + description, + hoverInfo, + { schema = undefined, allowOnlyValidChange = false, helperText = '' } = {}, + ) { + super( + part.partition.alignment.run, + defaultValue, + title, + description, + hoverInfo, + { + schema, + allowOnlyValidChange, + helperText, + }, + ); + makeObservable( this, { + alignment: computed, + } ); + this.part = part; + } + get alignment() { + return this.part.partition.alignment; + } +} + +class PartType extends PartBase { + constructor( part, value = 'DNA' ) { + super( part, value, 'Data type', 'Data type of the part', '', { + schema: yup.string(), + allowOnlyValidChange: true, + } ); + makeObservable( this, { + finalValue: computed, + options: computed, + notAvailable: computed, + } ); + } + get finalValue() { + const { dataType, partitionType } = this.alignment; + if ( dataType === 'protein' || this.value === 'protein' ) { + return this.part.aaType.value; + } + if ( dataType === 'mixed' ) { + return this.value; + } + return partitionType; + } + get options() { + const { dataType } = this.alignment; + let opts = [dataType]; + if ( dataType === '' || dataType === 'mixed' ) { + opts = ['DNA', 'BIN', 'MULTI', 'protein']; + } + return opts.map( ( value ) => ( { value, title: value } ) ); + } + get notAvailable() { + return this.alignment.dataType !== 'mixed'; + } +} +class PartAAType extends PartBase { + constructor( part, value = 'BLOSUM62' ) { + super( part, value, 'Model', 'Substitution model for the part', '', { + schema: yup.string(), + allowOnlyValidChange: true, + } ); + makeObservable( this, { + notAvailable: computed, + } ); + } + options = raxmlSettings.aminoAcidSubstitutionMatrixOptions.options.map( + ( value ) => ( { value, title: value } ), + ); + get notAvailable() { + return this.alignment.dataType !== 'protein'; + } +} +class PartName extends PartBase { + constructor( part, value = 'part1' ) { + super( part, value, 'Name', 'Name of part', '', { + schema: yup.string(), // TODO: Check that it is unique within partition + allowOnlyValidChange: true, + } ); + makeObservable( this, { + notAvailable: computed, + } ); + } + get notAvailable() { + return false; + } +} +class PartStart extends PartBase { + constructor( part, value = 1 ) { + super( part, value, 'from', 'Start position for this part', '', { + schema: yup.number(), + allowOnlyValidChange: false, + } ); + makeObservable( this, { + notAvailable: computed, + } ); + this.disabled = true; + } + get notAvailable() { + return false; + } +} + +class PartEnd extends PartBase { + constructor( part, value = 1 ) { + super( + part, + value, + 'to', + 'Ending position (inclusive) for this part', + 'Ending position (inclusive) for this part', + { + schema: yup.number().test( { + name: 'part-end', + message: () => `Must be in interval [${this.min}, ${this.max}]`, + test: ( value ) => { + return value >= this.min && value <= this.max; + }, + } ), + allowOnlyValidChange: false, + }, + ); + makeObservable( this, { + min: computed, + max: computed, + notAvailable: computed, + } ); + } + get min() { + return ( + this.part.start.value + ( this.part.codon.value === CODON_NONE + ? 0 + : 2 ) + ); + } + get max() { + return this.alignment.length; + } + get notAvailable() { + return false; + } +} + +class PartCodon extends PartBase { + constructor( part, value = 'None' ) { + super( part, value, 'Codon model', '', '', { + schema: yup.string(), + allowOnlyValidChange: true, + } ); + makeObservable( this, { + notAvailable: computed, + } ); + } + options = CodonModels.map( ( value ) => ( { value, title: value } ) ); + get notAvailable() { + return this.alignment.partition.partToAdd.type.value !== 'DNA'; + } +} + +export { PartType, PartAAType, PartName, PartStart, PartEnd, PartCodon }; diff --git a/src/app/store/Partition.js b/src/app/store/Partition.js index dbd31fec..a55f5e42 100644 --- a/src/app/store/Partition.js +++ b/src/app/store/Partition.js @@ -1,12 +1,15 @@ -import { observable, computed, action, reaction } from 'mobx'; -import Option from './Option'; -import * as raxmlSettings from '../../settings/raxml'; -import * as yup from 'yup'; - -const CODON_NONE = 'None'; -const CODON_SPECIFIC = 'Codon specific'; -const CODON_THIRD = 'Third codon'; -export const CodonModels = [CODON_NONE, CODON_SPECIFIC, CODON_THIRD]; +import { observable, computed, action, reaction, makeObservable } from 'mobx'; +import { + CODON_NONE, + CODON_SPECIFIC, + CODON_THIRD, + PartType, + PartAAType, + PartName, + PartStart, + PartEnd, + PartCodon, +} from './PartOptions'; const getPartitionType = ( dataType, aaMatrixName = 'BLOSUM62' ) => { // for old raxml @@ -25,151 +28,13 @@ const getPartitionType = ( dataType, aaMatrixName = 'BLOSUM62' ) => { } }; -class PartBase extends Option { - constructor( - part, - defaultValue, - title, - description, - hoverInfo, - { schema = undefined, allowOnlyValidChange = false, helperText = '' } = {}, - ) { - super( - part.partition.alignment.run, - defaultValue, - title, - description, - hoverInfo, - { - schema, - allowOnlyValidChange, - helperText, - }, - ); - this.part = part; - } - @computed get alignment() { - return this.part.partition.alignment; - } -} - -class PartType extends PartBase { - constructor( part, value = 'DNA' ) { - super( part, value, 'Data type', 'Data type of the part', '', { - schema: yup.string(), - allowOnlyValidChange: true, - } ); - } - @computed get finalValue() { - const { dataType, partitionType } = this.alignment; - if ( dataType === 'protein' || this.value === 'protein' ) { - return this.part.aaType.value; - } - if ( dataType === 'mixed' ) { - return this.value; - } - return partitionType; - } - @computed get options() { - const { dataType } = this.alignment; - let opts = [dataType]; - if ( dataType === '' || dataType === 'mixed' ) { - opts = ['DNA', 'BIN', 'MULTI', 'protein']; - } - return opts.map( ( value ) => ( { value, title: value } ) ); - } - @computed get notAvailable() { - return this.alignment.dataType !== 'mixed'; - } -} -class PartAAType extends PartBase { - constructor( part, value = 'BLOSUM62' ) { - super( part, value, 'Model', 'Substitution model for the part', '', { - schema: yup.string(), - allowOnlyValidChange: true, - } ); - } - options = raxmlSettings.aminoAcidSubstitutionMatrixOptions.options.map( - ( value ) => ( { value, title: value } ), - ); - @computed get notAvailable() { - return this.alignment.dataType !== 'protein'; - } -} -class PartName extends PartBase { - constructor( part, value = 'part1' ) { - super( part, value, 'Name', 'Name of part', '', { - schema: yup.string(), // TODO: Check that it is unique within partition - allowOnlyValidChange: true, - } ); - } - @computed get notAvailable() { - return false; - } -} -class PartStart extends PartBase { - constructor( part, value = 1 ) { - super( part, value, 'from', 'Start position for this part', '', { - schema: yup.number(), - allowOnlyValidChange: false, - } ); - this.disabled = true; - } - @computed get notAvailable() { - return false; - } -} - -class PartEnd extends PartBase { - constructor( part, value = 1 ) { - super( - part, - value, - 'to', - 'Ending position (inclusive) for this part', - 'Ending position (inclusive) for this part', - { - schema: yup.number().test( { - name: 'part-end', - message: () => `Must be in interval [${this.min}, ${this.max}]`, - test: ( value ) => { - return value >= this.min && value <= this.max; - }, - } ), - allowOnlyValidChange: false, - }, - ); - } - @computed get min() { - return ( - this.part.start.value + ( this.part.codon.value === CODON_NONE - ? 0 - : 2 ) - ); - } - @computed get max() { - return this.alignment.length; - } - @computed get notAvailable() { - return false; - } -} - -class PartCodon extends PartBase { - constructor( part, value = 'None' ) { - super( part, value, 'Codon model', '', '', { - schema: yup.string(), - allowOnlyValidChange: true, - } ); - } - options = CodonModels.map( ( value ) => ( { value, title: value } ) ); - @computed get notAvailable() { - return this.alignment.partition.partToAdd.type.value !== 'DNA'; - } -} - class Part { constructor( partition, { type, aaType, name, start, end, codon } ) { + makeObservable( this, { + typePadded: computed, + text: computed, + values: computed, + } ); this.partition = partition; this.type = new PartType( this, type ); this.aaType = new PartAAType( this, aaType ); @@ -179,7 +44,7 @@ class Part { this.codon = new PartCodon( this, codon ); } - @computed get typePadded() { + get typePadded() { return `${this.type.finalValue},`.padEnd( 12 ); } @@ -224,14 +89,14 @@ class Part { } }; - @computed get text() { + get text() { // return `${this.typePadded}${this.name.value} = ${this.start.value}-${this.end.value}`; return this.transform(); } parse = ( row ) => {}; - @computed get values() { + get values() { return { type: this.type.value, aaType: this.aaType.value, @@ -248,6 +113,22 @@ class Part { } class Partition { constructor( alignment ) { + makeObservable( this, { + parts: observable, + addPart: action, + isMixed: computed, + isDefault: computed, + maxEndValue: computed, + currentEndValue: computed, + isComplete: computed, + nonDefaultPartitionComplete: computed, + progress: computed, + haveError: computed, + errorMessage: computed, + addPartDisabled: computed, + text: computed, + reset: action, + } ); this.alignment = alignment; this.defaultPartition = new Part( this, { type: alignment.partitionType, @@ -267,7 +148,7 @@ class Partition { } ); reaction( () => alignment.length, - ( length, reaction ) => { + ( length, _previous, reaction ) => { reaction.dispose(); // Make default alignment complete except for mixed type if ( this.alignment.dataType !== 'mixed' ) { @@ -293,7 +174,7 @@ class Partition { { name: 'React to default partition type change' }, ); } - @observable parts = []; + parts = []; // Add current part values addPart = () => { this.parts.push( this.partToAdd.clone() ); @@ -315,44 +196,44 @@ class Partition { this.partToAdd.name.value = newName; } }; - @computed get isMixed() { + get isMixed() { return this.alignment.dataType === 'mixed'; } - @computed get isDefault() { + get isDefault() { return this.parts.length === 0; } - @computed get maxEndValue() { + get maxEndValue() { return this.alignment.length; } - @computed get currentEndValue() { + get currentEndValue() { return this.isDefault ? this.defaultPartition.end.value : this.parts[this.parts.length - 1].end.value; } - @computed get isComplete() { + get isComplete() { return this.currentEndValue === this.maxEndValue; } - @computed get nonDefaultPartitionComplete() { + get nonDefaultPartitionComplete() { return !this.isDefault && this.isComplete; } - @computed get progress() { + get progress() { return this.isDefault ? 100 : ( this.currentEndValue * 100.0 ) / this.alignment.length; } - @computed get haveError() { + get haveError() { return this.partToAdd.end.haveError; } - @computed get errorMessage() { + get errorMessage() { return this.haveError ? `End position error: ${this.partToAdd.end.errorMessage}` : ''; } - @computed get addPartDisabled() { + get addPartDisabled() { return this.nonDefaultPartitionComplete || this.haveError; } - @computed get text() { + get text() { if ( this.isDefault ) { // return this.alignment.partitionFileContent; return this.defaultPartition.text; @@ -366,7 +247,7 @@ class Partition { return this.parts.map( ( part ) => part.transform( offset, prefix ) ).join( '\n' ); }; - @action reset = () => { + reset = () => { if ( this.parts.length > 0 ) { this.parts.splice( 0 ); this.partToAdd.name.value = 'part_1'; @@ -376,39 +257,4 @@ class Partition { }; } -class FinalPartition { - constructor( run ) { - this.run = run; - } - /* - Example: - DNA, gene1 = 1-3676 - BIN, morph = 3677-3851 - */ - @computed get text() { - if ( !this.run.haveAlignments ) { - return ''; - } - const partitionTexts = []; - let total = 0; - this.run.alignments.forEach( ( alignment, index ) => { - partitionTexts.push( alignment.partition.transform( total, `${index}_` ) ); - total += alignment.length; - } ); - return partitionTexts.join( '\n' ); - } - @computed get isDefault() { - return ( - this.run.alignments.length === 0 || - ( this.run.alignments.length === 1 && - this.run.alignments[0].partition.isDefault ) - ); - } - @computed get isComplete() { - return this.run.alignments.every( - ( alignment ) => alignment.partition.isComplete, - ); - } -} - -export { Partition as default, FinalPartition }; +export default Partition; diff --git a/src/app/store/Partition.test.js b/src/app/store/Partition.test.js new file mode 100644 index 00000000..8f69329a --- /dev/null +++ b/src/app/store/Partition.test.js @@ -0,0 +1,334 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Alignment from './Alignment'; +import RunList from './RunList'; +import { runEvents } from './StoreBase'; + +// The run and alignment subscribe to bridge events; a no-op bridge is enough here. +function stubBridge() { + const bridge = { cancelRun: jest.fn(), getVersion: () => Promise.resolve( '2.0.0' ) }; + for ( const name of Object.values( runEvents ) ) { + bridge[name] = () => () => {}; + } + window.rendererBridge = bridge; +} + +// Records every value an autorun sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +let run; + +// Adds an alignment to the run the way loading a file would, minus the file. +function addAlignment( { dataType = 'nucleotide', length = 100 } = {} ) { + const alignment = new Alignment( run, `/data/aln${run.alignments.length}.fasta` ); + runInAction( () => { + alignment.dataType = dataType; + alignment.length = length; + run.alignments.push( alignment ); + } ); + return alignment; +} + +// Sets the end of the part to add, then adds it. +function addPartEndingAt( partition, end ) { + runInAction( () => { + partition.partToAdd.end.value = end; + } ); + partition.addPart(); +} + +beforeEach( () => { + stubBridge(); + run = new RunList().activeRun; + runInAction( () => { + run.binary.value = 'raxmlHPC'; + } ); +} ); + +describe( 'Partition', () => { + it( 'starts as the default partition covering the alignment', () => { + const { partition } = addAlignment( { length: 100 } ); + expect( partition.parts ).toEqual( [] ); + expect( partition.isDefault ).toBe( true ); + expect( partition.isMixed ).toBe( false ); + expect( partition.maxEndValue ).toBe( 100 ); + expect( partition.currentEndValue ).toBe( 100 ); + expect( partition.isComplete ).toBe( true ); + expect( partition.nonDefaultPartitionComplete ).toBe( false ); + expect( partition.progress ).toBe( 100 ); + expect( partition.text ).toBe( 'DNA, part_1 = 1-100' ); + } ); + + it( 'the default partition follows the alignment length and data type', () => { + const alignment = new Alignment( run, '/data/a.fasta' ); + const { partition } = alignment; + const { seen, stop } = track( () => partition.text ); + runInAction( () => { + alignment.dataType = 'nucleotide'; + alignment.length = 250; + } ); + expect( partition.defaultPartition.end.value ).toBe( 250 ); + expect( partition.defaultPartition.type.value ).toBe( 'DNA' ); + expect( partition.partToAdd.type.value ).toBe( 'DNA' ); + expect( partition.text ).toBe( 'DNA, part_1 = 1-250' ); + runInAction( () => { + alignment.dataType = 'binary'; + } ); + expect( partition.defaultPartition.type.value ).toBe( 'BIN' ); + expect( partition.partToAdd.type.value ).toBe( 'BIN' ); + expect( seen[seen.length - 1] ).toBe( 'BIN, part_1 = 1-250' ); + stop(); + } ); + + it( 'a protein alignment takes the amino acid matrix as the model', () => { + const alignment = new Alignment( run, '/data/a.fasta' ); + const { partition } = alignment; + runInAction( () => { + alignment.dataType = 'protein'; + alignment.aaMatrixName = 'WAG'; + alignment.length = 30; + } ); + expect( partition.defaultPartition.type.value ).toBe( 'protein' ); + expect( partition.defaultPartition.aaType.value ).toBe( 'WAG' ); + expect( partition.partToAdd.aaType.value ).toBe( 'WAG' ); + expect( partition.text ).toBe( 'WAG, part_1 = 1-30' ); + } ); + + it( 'a mixed alignment keeps the default partition end', () => { + const alignment = new Alignment( run, '/data/a.fasta' ); + const before = alignment.partition.defaultPartition.end.value; + runInAction( () => { + alignment.dataType = 'mixed'; + alignment.length = 80; + } ); + expect( alignment.partition.isMixed ).toBe( true ); + expect( alignment.partition.defaultPartition.end.value ).toBe( before ); + } ); + + it( 'adding a part appends it and prepares the next start and a fresh name', () => { + const { partition } = addAlignment( { length: 100 } ); + const { seen, stop } = track( () => partition.parts.length ); + addPartEndingAt( partition, 40 ); + expect( partition.parts.map( ( p ) => p.values ) ).toEqual( [ + { type: 'DNA', aaType: 'BLOSUM62', name: 'part_1', start: 1, end: 40, codon: 'None' }, + ] ); + expect( partition.partToAdd.start.value ).toBe( 41 ); + expect( partition.partToAdd.end.value ).toBe( 41 ); + expect( partition.partToAdd.name.value ).toBe( 'part_2' ); + expect( partition.partToAdd.codon.value ).toBe( 'None' ); + expect( seen ).toEqual( [0, 1] ); + stop(); + } ); + + it( 'adding a part to a name without digits appends _1', () => { + const { partition } = addAlignment( { length: 100 } ); + runInAction( () => { + partition.partToAdd.name.value = 'gene'; + } ); + addPartEndingAt( partition, 10 ); + expect( partition.partToAdd.name.value ).toBe( 'gene_1' ); + } ); + + it( 'adding the last part completes the partition', () => { + const { partition } = addAlignment( { length: 100 } ); + addPartEndingAt( partition, 60 ); + const { seen, stop } = track( () => partition.addPartDisabled ); + addPartEndingAt( partition, 100 ); + expect( partition.isDefault ).toBe( false ); + expect( partition.currentEndValue ).toBe( 100 ); + expect( partition.isComplete ).toBe( true ); + expect( partition.nonDefaultPartitionComplete ).toBe( true ); + expect( partition.progress ).toBe( 100 ); + expect( partition.addPartDisabled ).toBe( true ); + expect( seen ).toEqual( [false, true] ); + stop(); + } ); + + it( 'progress, currentEndValue and text follow the parts', () => { + const { partition } = addAlignment( { length: 100 } ); + const { seen, stop } = track( () => [ + partition.currentEndValue, + partition.progress, + partition.isDefault, + ] ); + addPartEndingAt( partition, 25 ); + expect( partition.isComplete ).toBe( false ); + expect( partition.nonDefaultPartitionComplete ).toBe( false ); + expect( partition.text ).toBe( 'DNA, part_1 = 1-25' ); + expect( seen ).toEqual( [ + [100, 100, true], + [25, 25, false], + ] ); + addPartEndingAt( partition, 100 ); + expect( partition.text ).toBe( + 'DNA, part_1 = 1-25\nDNA, part_2 = 26-100', + ); + stop(); + } ); + + it( 'a codon specific part expands to one row per codon', () => { + const { partition } = addAlignment( { length: 99 } ); + runInAction( () => { + partition.partToAdd.codon.value = 'Codon specific'; + } ); + addPartEndingAt( partition, 99 ); + expect( partition.text ).toBe( + [ + 'DNA, part_1_codon1 = 1-99\\3', + 'DNA, part_1_codon2 = 2-99\\3', + 'DNA, part_1_codon3 = 3-99\\3', + ].join( '\n' ), + ); + expect( partition.partToAdd.codon.value ).toBe( 'None' ); + } ); + + it( 'transform applies the offset and prefix to the default and added parts', () => { + const { partition } = addAlignment( { length: 100 } ); + expect( partition.transform( 10, 'x_' ) ).toBe( 'DNA, x_part_1 = 11-110' ); + addPartEndingAt( partition, 30 ); + expect( partition.transform( 10, 'x_' ) ).toBe( 'DNA, x_part_1 = 11-40' ); + expect( partition.transform() ).toBe( 'DNA, part_1 = 1-30' ); + } ); + + it( 'haveError, errorMessage and addPartDisabled follow the end of the part to add', () => { + const { partition } = addAlignment( { length: 100 } ); + const { seen, stop } = track( () => [ + partition.haveError, + partition.errorMessage, + partition.addPartDisabled, + ] ); + expect( seen[0] ).toEqual( [false, '', false] ); + runInAction( () => { + partition.partToAdd.end.value = 500; + } ); + expect( partition.haveError ).toBe( true ); + expect( partition.errorMessage ).toBe( + 'End position error: Must be in interval [1, 100]', + ); + expect( partition.addPartDisabled ).toBe( true ); + runInAction( () => { + partition.partToAdd.end.value = 50; + } ); + expect( seen[seen.length - 1] ).toEqual( [false, '', false] ); + stop(); + } ); + + it( 'a reaction sees parts set directly', () => { + const { partition } = addAlignment( { length: 100 } ); + const { seen, stop } = track( () => [partition.isDefault, partition.text] ); + runInAction( () => { + partition.parts.push( partition.partToAdd.clone() ); + } ); + expect( seen.map( ( s ) => s[0] ) ).toEqual( [true, false] ); + expect( seen[1][1] ).toBe( 'DNA, part_1 = 1-1' ); + stop(); + } ); + + it( 'maxEndValue and isComplete follow the alignment length', () => { + const alignment = addAlignment( { length: 100 } ); + const { partition } = alignment; + addPartEndingAt( partition, 100 ); + const { seen, stop } = track( () => [partition.maxEndValue, partition.isComplete] ); + runInAction( () => { + alignment.length = 120; + } ); + expect( seen ).toEqual( [ + [100, true], + [120, false], + ] ); + stop(); + } ); + + it( 'reset removes the parts and restores the part to add', () => { + const { partition } = addAlignment( { length: 100 } ); + addPartEndingAt( partition, 30 ); + const { seen, stop } = track( () => partition.isDefault ); + partition.reset(); + expect( partition.parts ).toEqual( [] ); + expect( partition.partToAdd.name.value ).toBe( 'part_1' ); + expect( partition.partToAdd.start.value ).toBe( 1 ); + expect( partition.partToAdd.end.value ).toBe( 1 ); + expect( seen ).toEqual( [false, true] ); + stop(); + } ); + + it( 'reset leaves the part to add alone when there are no parts', () => { + const { partition } = addAlignment( { length: 100 } ); + runInAction( () => { + partition.partToAdd.name.value = 'keep'; + } ); + partition.reset(); + expect( partition.partToAdd.name.value ).toBe( 'keep' ); + } ); +} ); + +describe( 'FinalPartition', () => { + it( 'is empty, default and complete without alignments', () => { + const finalPartition = run.finalAlignment.partition; + expect( finalPartition.text ).toBe( '' ); + expect( finalPartition.isDefault ).toBe( true ); + expect( finalPartition.isComplete ).toBe( true ); + } ); + + it( 'text offsets and prefixes each alignment partition', () => { + const finalPartition = run.finalAlignment.partition; + const { seen, stop } = track( () => finalPartition.text ); + addAlignment( { dataType: 'nucleotide', length: 100 } ); + addAlignment( { dataType: 'binary', length: 50 } ); + expect( finalPartition.text ).toBe( + 'DNA, 0_part_1 = 1-100\nBIN, 1_part_1 = 101-150', + ); + expect( seen[0] ).toBe( '' ); + expect( seen[seen.length - 1] ).toBe( finalPartition.text ); + stop(); + } ); + + it( 'text follows the added parts of an alignment', () => { + const finalPartition = run.finalAlignment.partition; + const first = addAlignment( { length: 100 } ); + addAlignment( { length: 50 } ); + addPartEndingAt( first.partition, 40 ); + addPartEndingAt( first.partition, 100 ); + expect( finalPartition.text ).toBe( + [ + 'DNA, 0_part_1 = 1-40', + 'DNA, 0_part_2 = 41-100', + 'DNA, 1_part_1 = 101-150', + ].join( '\n' ), + ); + } ); + + it( 'isDefault is true for one default alignment and false otherwise', () => { + const finalPartition = run.finalAlignment.partition; + const { seen, stop } = track( () => finalPartition.isDefault ); + const first = addAlignment( { length: 100 } ); + expect( finalPartition.isDefault ).toBe( true ); + addPartEndingAt( first.partition, 40 ); + expect( finalPartition.isDefault ).toBe( false ); + first.partition.reset(); + expect( finalPartition.isDefault ).toBe( true ); + addAlignment( { length: 10 } ); + expect( finalPartition.isDefault ).toBe( false ); + expect( seen ).toEqual( [true, false, true, false] ); + stop(); + } ); + + it( 'isComplete requires every alignment partition to be complete', () => { + const finalPartition = run.finalAlignment.partition; + const first = addAlignment( { length: 100 } ); + const second = addAlignment( { length: 100 } ); + const { seen, stop } = track( () => finalPartition.isComplete ); + addPartEndingAt( second.partition, 40 ); + expect( finalPartition.isComplete ).toBe( false ); + addPartEndingAt( second.partition, 100 ); + expect( finalPartition.isComplete ).toBe( true ); + expect( first.partition.isComplete ).toBe( true ); + expect( seen ).toEqual( [true, false, true] ); + stop(); + } ); +} ); diff --git a/src/app/store/Run.computeds.test.js b/src/app/store/Run.computeds.test.js new file mode 100644 index 00000000..5768779a --- /dev/null +++ b/src/app/store/Run.computeds.test.js @@ -0,0 +1,396 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; +import { analysisOptions, binaries } from './RunOptions'; +import { runEvents } from './StoreBase'; + +const modeltestName = binaries.find( ( b ) => b.type === 'modeltest' ).name; + +let checkOutput; +let stops = []; + +// The run subscribes to bridge events in its constructor; the stub accepts and ignores them. +beforeEach( () => { + stops = []; + checkOutput = jest.fn( async ( { outputName } ) => ( { + ok: true, + outputNameUnused: outputName, + resultFilenames: [], + } ) ); + const bridge = { checkOutput, getVersion: () => Promise.resolve( '2.0.0' ) }; + for ( const name of Object.values( runEvents ) ) { + bridge[name] = () => () => {}; + } + window.rendererBridge = bridge; +} ); + +afterEach( () => stops.forEach( ( stop ) => stop() ) ); + +const nucleotide = ( over = {} ) => ( { + name: 'a.fasta', + path: '/in/a.fasta', + filename: 'a.fasta', + dir: '/in', + taxons: ['t1', 't2', 't3'], + length: 10, + dataType: 'nucleotide', + modified: false, + converted: false, + showModifiedSnack: false, + showModifiedDialog: false, + modeltestLoading: false, + modificationMessages: [], + ngSubstitutionModelCmd: 'GTR+G', + partition: { isDefault: true, isComplete: true }, + ...over, +} ); + +function makeRun( { alignments = [nucleotide()], binary = 'raxmlHPC', outputDir = '/out' } = {} ) { + const run = new Run( null, 1 ); + runInAction( () => { + run.binary.value = binary; + run.outputDir = outputDir; + run.alignments = alignments; + } ); + // analysis is a computed that builds its option; keep it observed so a set value sticks. + stops.push( autorun( () => run.analysis ) ); + return run; +} + +// outputNameAvailable only settles inside a reaction, so reads that touch it go through here. +function read( fn ) { + let value; + autorun( () => { + value = fn(); + } )(); + return value; +} + +// outputNameAvailable is async and only computes while observed. +async function observeOutput( run ) { + stops.push( autorun( () => run.outputNameAvailable.get() ) ); + await new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); +} + +describe( 'Run binary computeds', () => { + it( 'maps the binary to its flags', () => { + const run = makeRun( { binary: 'raxml-ng' } ); + expect( [run.usesRaxmlNg, run.usesRaxml, run.usesModeltest, run.usesAstral] ) + .toEqual( [true, true, false, false] ); + expect( [run.inputIsAlignment, run.inputIsTree] ).toEqual( [true, false] ); + runInAction( () => { + run.binary.value = 'raxmlHPC'; + } ); + expect( [run.usesRaxmlNg, run.usesRaxml] ).toEqual( [false, true] ); + runInAction( () => { + run.binary.value = modeltestName; + } ); + expect( [run.usesModeltestNg, run.usesModeltest, run.usesRaxml] ) + .toEqual( [true, true, false] ); + expect( run.inputIsAlignment ).toBe( true ); + } ); + + it( 'analysis and analysisOption follow the binary family', () => { + const run = makeRun( { binary: 'raxmlHPC' } ); + run.analysis.setValue( 'FT' ); + expect( run.analysisOption.title ).toBe( 'Fast tree search' ); + runInAction( () => { + run.binary.value = 'raxml-ng'; + } ); + expect( run.analysisOption.value ).toBe( run.analysis.value ); + expect( run.analysisOption.title ).not.toBe( 'Fast tree search' ); + } ); + + it( 'haveRandomSeed is true only for analyses that take a seed', () => { + const run = makeRun( { binary: 'raxmlHPC' } ); + run.analysis.setValue( 'FT' ); + expect( run.haveRandomSeed ).toBe( true ); + run.analysis.setValue( 'SC' ); + expect( run.haveRandomSeed ).toBe( false ); + } ); + + it( 'the three seeds mirror randomSeed', () => { + const run = makeRun(); + run.setRandomSeed( 42 ); + expect( [run.seedParsimony, run.seedRapidBootstrap, run.seedBootstrap] ) + .toEqual( [42, 42, 42] ); + } ); +} ); + +describe( 'Run alignment computeds', () => { + it( 'haveAlignments, taxons and numSites follow the alignments', () => { + const run = makeRun( { alignments: [] } ); + expect( run.haveAlignments ).toBe( false ); + expect( run.taxons ).toEqual( [] ); + runInAction( () => { + run.alignments = [nucleotide()]; + } ); + expect( run.haveAlignments ).toBe( true ); + expect( run.taxons ).toEqual( ['t1', 't2', 't3'] ); + expect( run.dataType ).toBe( 'nucleotide' ); + } ); + + it( 'hasAstralTree and canLoadAstralTree follow the tree', () => { + const run = makeRun(); + expect( run.hasAstralTree ).toBe( false ); + expect( run.canLoadAstralTree ).toBe( false ); + runInAction( () => { + run.astralTree = { path: '/in/t.tre' }; + } ); + expect( run.hasAstralTree ).toBe( true ); + } ); + + it( 'canLoadAlignment is false once a partition file is loaded', () => { + const run = makeRun(); + expect( run.canLoadAlignment ).toBe( true ); + runInAction( () => { + run.partitionFile = '/in/parts.txt'; + } ); + expect( run.havePartitionFile ).toBe( true ); + expect( run.partitionFileName ).toBe( 'parts.txt' ); + expect( run.canLoadAlignment ).toBe( false ); + expect( run.canLoadPartitionFile ).toBe( false ); + } ); + + it( 'canLoadPartitionFile needs exactly one alignment', () => { + const one = makeRun(); + expect( one.canLoadPartitionFile ).toBe( true ); + const two = makeRun( { alignments: [nucleotide(), nucleotide()] } ); + expect( two.canLoadPartitionFile ).toBe( false ); + } ); + + it( 'modified flags are true when any alignment is flagged', () => { + const run = makeRun( { + alignments: [ + nucleotide(), + nucleotide( { + name: 'b.fasta', + modified: true, + converted: true, + convertedFrom: 'phylip', + showModifiedSnack: true, + showModifiedDialog: true, + modificationMessages: ['fixed names'], + } ), + ], + } ); + expect( run.modified ).toBe( true ); + expect( run.converted ).toBe( true ); + expect( run.convertedAlignmentFrom ).toBe( 'phylip' ); + expect( run.showModifiedSnack ).toBe( true ); + expect( run.showModifiedDialog ).toBe( true ); + expect( run.modificationMessages ).toEqual( [ + 'a.fasta:\n', 'b.fasta:\n', 'fixed names\n', + ] ); + } ); + + it( 'modified flags are false without alignments', () => { + const run = makeRun( { alignments: [] } ); + expect( [run.modified, run.converted, run.showModifiedSnack, run.showModifiedDialog] ) + .toEqual( [false, false, false, false] ); + expect( run.convertedAlignmentFrom ).toBe( null ); + expect( run.ngSubstitutionModelCmd ).toBe( '' ); + } ); + + it( 'modelTestIsRunningOnAlignment and modelTestCanRun', () => { + const run = makeRun( { alignments: [nucleotide( { modeltestLoading: true } )] } ); + expect( run.modelTestIsRunningOnAlignment ).toBe( true ); + expect( run.modelTestCanRun ).toBe( true ); + runInAction( () => { + run.alignments[0].dataType = 'multistate'; + run.alignments[0].modeltestLoading = false; + } ); + expect( run.modelTestIsRunningOnAlignment ).toBe( false ); + expect( run.modelTestCanRun ).toBe( false ); + } ); + + it( 'ngSubstitutionModelCmd comes from the first alignment', () => { + expect( makeRun().ngSubstitutionModelCmd ).toBe( 'GTR+G' ); + } ); + + it( 'numSites is 0 without alignments', () => { + expect( makeRun( { alignments: [] } ).numSites ).toBe( 0 ); + } ); + + it( 'needAlignment is always true', () => { + expect( makeRun().needAlignment ).toBe( true ); + } ); +} ); + +describe( 'Run state computeds', () => { + it( 'missing asks for a tree only for an analysis that needs one', () => { + const run = makeRun( { binary: 'raxmlHPC' } ); + const needsTree = analysisOptions.find( ( o ) => o.params.includes( 'tree' ) ); + run.analysis.setValue( 'FT' ); + expect( run.missing ).toBe( '' ); + run.analysis.setValue( needsTree.value ); + expect( run.missing ).toBe( 'Missing tree, please load one.' ); + expect( run.ok ).toBe( false ); + expect( run.startDisabled ).toBe( true ); + } ); + + it( 'ok is false while an error is set', () => { + const run = makeRun(); + const { missing } = run; + expect( run.ok ).toBe( !missing ); + runInAction( () => { + run.error = 'boom'; + } ); + expect( run.ok ).toBe( false ); + } ); + + it( 'startDisabled is true without alignments or tree', () => { + expect( makeRun( { alignments: [] } ).startDisabled ).toBe( true ); + } ); + + it( 'startDisabled is true while running or in error', () => { + const run = makeRun(); + runInAction( () => { + run.error = 'boom'; + } ); + expect( run.startDisabled ).toBe( true ); + runInAction( () => { + run.error = null; + run.running = true; + } ); + expect( run.startDisabled ).toBe( true ); + } ); + + it( 'startDisabled is true while an alignment runs model test', () => { + const run = makeRun( { alignments: [nucleotide( { modeltestLoading: true } )] } ); + expect( run.startDisabled ).toBe( true ); + } ); + + it( 'startDisabled is true when the partition is incomplete', () => { + const run = makeRun( { + alignments: [nucleotide( { partition: { isDefault: false, isComplete: false } } )], + } ); + expect( run.startDisabled ).toBe( true ); + } ); + + it( 'modeltest-ng cannot start on several alignments', () => { + const run = makeRun( { + binary: modeltestName, + alignments: [nucleotide(), nucleotide()], + } ); + expect( run.startDisabled ).toBe( true ); + } ); +} ); + +describe( 'Run output computeds', () => { + it( 'output name falls back to the placeholder and reports no notice', async () => { + const run = makeRun(); + await observeOutput( run ); + expect( read( () => run.outputNameOk ) ).toBe( true ); + expect( read( () => run.outputNameSafe ) ).toBe( 'output' ); + expect( read( () => run.outputFilenameSafe ) ).toBe( 'output.tre' ); + expect( read( () => run.outputNameNotice ) ).toBe( '' ); + expect( checkOutput ).toHaveBeenCalledWith( { outputDir: '/out', outputName: 'output' } ); + } ); + + it( 'a taken output name shows the notice with the unused name', async () => { + checkOutput.mockResolvedValue( { + ok: false, + outputNameUnused: 'output_2', + resultFilenames: ['a.tre'], + } ); + const run = makeRun(); + await observeOutput( run ); + expect( read( () => run.outputNameOk ) ).toBe( false ); + expect( read( () => run.outputNameSafe ) ).toBe( 'output_2' ); + expect( read( () => run.outputFilenameSafe ) ).toBe( 'output_2.tre' ); + expect( read( () => run.outputNameNotice ) ) + .toBe( "Output with that id already exists. New run will use output id 'output_2'" ); + expect( read( () => run.resultFilenames ) ).toEqual( ['a.tre'] ); + } ); + + it( 'haveResult needs result files from the current output directory', async () => { + checkOutput.mockResolvedValue( { ok: false, outputNameUnused: 'x', resultFilenames: ['a.tre'] } ); + const run = makeRun(); + await observeOutput( run ); + runInAction( () => { + run.resultDir = '/other'; + } ); + expect( read( () => run.haveResult ) ).toBe( false ); + runInAction( () => { + run.resultDir = '/out'; + } ); + expect( read( () => run.haveResult ) ).toBe( true ); + } ); + + it( 'the settings file path and content use the output name and args', async () => { + const run = makeRun( { binary: 'raxmlHPC' } ); + run.analysis.setValue( 'FT' ); + await observeOutput( run ); + expect( read( () => run.settingsFilePath ) ).toBe( '/out/RAxML_GUI_Settings_output.txt' ); + const content = read( () => run.settingsFileContent ); + expect( content ).toContain( 'Analysis: Fast tree search' ); + expect( content ).toContain( 'Binary: raxmlHPC version 8.2.12' ); + expect( content ).toContain( 'Results saved to: /out' ); + expect( content ).toContain( `1.) ${read( () => run.args )[0].join( ' ' )}` ); + } ); +} ); + +describe( 'Run command', () => { + it( 'starts with the binary and carries the paths and output name', async () => { + const run = makeRun( { binary: 'raxmlHPC' } ); + run.analysis.setValue( 'FT' ); + await observeOutput( run ); + const command = read( () => run.command ); + expect( command.startsWith( 'raxmlHPC ' ) ).toBe( true ); + expect( command ).toContain( '-f E' ); + expect( command ).toContain( '-n output.tre' ); + expect( command ).toContain( '-s /in/a.fasta' ); + expect( command ).toContain( '-w /out' ); + } ); + + it( 'changing an option updates the command preview', async () => { + const run = makeRun( { binary: 'raxmlHPC' } ); + run.analysis.setValue( 'FT' ); + await observeOutput( run ); + const seen = []; + stops.push( autorun( () => seen.push( run.command ) ) ); + run.analysis.setValue( 'ML' ); + expect( seen[seen.length - 1] ).toContain( '-f d' ); + expect( seen[seen.length - 1] ).not.toBe( seen[0] ); + run.setRandomSeed( 7 ); + expect( seen[seen.length - 1] ).toContain( '-p 7' ); + runInAction( () => { + run.outputDir = '/elsewhere'; + } ); + expect( seen[seen.length - 1] ).toContain( '-w /elsewhere' ); + } ); + + it( 'multiple commands are joined with &&', async () => { + const run = makeRun( { binary: 'raxmlHPC' } ); + run.analysis.setValue( 'FT' ); + run.branchLength.setValue( true ); + await observeOutput( run ); + const args = read( () => run.args ); + expect( args.length ).toBeGreaterThan( 1 ); + expect( read( () => run.command ).split( ' &&\\\n' ) ).toHaveLength( args.length ); + } ); + + it( 'raxml-ng and modeltest-ng build their own command', async () => { + const run = makeRun( { binary: 'raxml-ng' } ); + await observeOutput( run ); + expect( read( () => run.command ).startsWith( 'raxml-ng ' ) ).toBe( true ); + runInAction( () => { + run.binary.value = modeltestName; + } ); + const command = read( () => run.command ); + expect( command.startsWith( `${modeltestName} ` ) ).toBe( true ); + expect( command ).toContain( '-d nt' ); + expect( command ).toContain( '-i /in/a.fasta' ); + } ); + + it( 'raxmlSubstitutionModelCmd adds X for estimated frequencies', () => { + const run = makeRun(); + const before = run.raxmlSubstitutionModelCmd; + runInAction( () => { + run.estimatedFrequencies.value = true; + } ); + expect( run.raxmlSubstitutionModelCmd ).toBe( `${before}X` ); + } ); +} ); diff --git a/src/app/store/Run.js b/src/app/store/Run.js index 40ff8f46..35e8ae68 100644 --- a/src/app/store/Run.js +++ b/src/app/store/Run.js @@ -1,783 +1,161 @@ -import { observable, computed, action, createAtom } from 'mobx'; -import { range } from 'd3-array'; -import { promisedComputed } from 'computed-async-mobx'; +import { observable, observableRef, computed, action, runInAction, createAtom, makeObservable } from 'mobx'; +import { promisedComputed } from '../promisedComputed'; import filenamify from 'filenamify'; -import Alignment, { FinalAlignment } from './Alignment'; +import Alignment from './Alignment'; +import FinalAlignment from './FinalAlignment'; import AstralTree from './AstralTree'; -import Option from './Option'; import StoreBase, { runEvents } from './StoreBase'; import { host } from './host'; -import { basename, dir, join, name, quote } from '../paths'; -import * as raxmlSettings from '../../settings/raxml'; +import { + binaries, + analysisOptions, + raxmlNgAnalysisOptions, + Binary, + NumThreads, + Analysis, + RaxmlNgAnalysis, + NumRuns, + NumRepetitions, + NumRepetitionsNg, + BranchLength, + SHlike, + CombinedOutput, + StartingTree, + OutGroup, + SubstitutionMatrix, + SubstitutionRate, + SubstitutionI, + SubstitutionAscertainment, + AAMatrixName, + EstimatedFrequencies, + BaseFrequencies, + MultistateModel, + Tree, + BackboneConstraintTree, + MultifurcatingConstraintTree, +} from './RunOptions'; +import { basename, join, quote } from '../paths'; import remove from 'lodash/remove'; import UserFixError from '../../common/errors'; -const raxmlMatrixOptions = raxmlSettings.matrixOptions; -const raxmlRateOptions = raxmlSettings.rateOptions; -const raxmlIOptions = raxmlSettings.iOptions; -const raxmlAscertainmentOptions = raxmlSettings.ascertainmentOptions; - const { windows } = host; -export const MAX_NUM_CPUS = navigator.hardwareConcurrency || 1; - -// On Windows 7 (= 6.1) use older versions of RAxML -const [majorVersion, minorVersion] = host.release.split( '.' ); -const winBinaries = - majorVersion === '6' && minorVersion === '1' - ? [ - // TODO: add raxml ng windows exe - // TODO: Crashes on Win7, disabled for now - // { name: 'modeltest-ng.exe', version: '0.1.7' }, - { - name: 'raxmlHPC_Win7.exe', - multithreaded: false, - version: '8.2.10', - type: 'raxml', - }, - { - name: 'raxmlHPC-SSE3_Win7.exe', - multithreaded: false, - version: '8.2.10', - type: 'raxml', - }, - // TODO: Crashes on Win7, disabled for now - // { - // name: 'raxmlHPC-PTHREADS-AVX_Win7.exe', - // multithreaded: true, - // version: '8.2.10', - // }, - { - name: 'raxmlHPC-PTHREADS-SSE3_Win7.exe', - multithreaded: true, - version: '8.2.10', - initial: true, - type: 'raxml', - }, - // TODO: put back in Astral - // { - // name: 'astral.5.7.8.jar', - // multithreaded: false, - // version: '5.7.8', - // type: 'astral', - // }, - ] - : [ - // TODO: add raxml ng windows exe - { name: 'modeltest-ng.exe', version: '0.1.7', type: 'modeltest' }, - { - name: 'raxmlHPC.exe', - multithreaded: false, - version: '8.2.12', - type: 'raxml', - }, - { - name: 'raxmlHPC-SSE3.exe', - multithreaded: false, - version: '8.2.12', - type: 'raxml', - }, - { - name: 'raxmlHPC-PTHREADS-AVX.exe', - multithreaded: true, - version: '8.2.12', - type: 'raxml', - }, - { - name: 'raxmlHPC-PTHREADS-SSE3.exe', - multithreaded: true, - version: '8.2.12', - initial: true, - type: 'raxml', - }, - // TODO: put back in Astral - // { - // name: 'astral.5.7.8.jar', - // multithreaded: false, - // version: '5.7.8', - // type: 'astral', - // }, - ]; - -const likelyARM = - host.arch.includes( 'arm64' ) || host.cpuModel.includes( 'Apple' ); -const armBinaries = [ - { - name: 'modeltest-ng-ARM64', - multithreaded: true, - version: '0.1.7', - type: 'modeltest', - }, -]; -const x64Binaries = [ - { - name: 'modeltest-ng', - multithreaded: true, - version: '0.1.7', - type: 'modeltest', - }, -]; - -const allBinaries = host.windows - ? winBinaries - : [ - ...( !likelyARM - ? x64Binaries - : armBinaries ), - { - name: 'raxml-ng', - multithreaded: true, - version: '1.2.2', - initial: true, - type: 'raxml', - }, - { - name: 'raxmlHPC', - multithreaded: false, - version: '8.2.12', - type: 'raxml', - }, - { - name: 'raxmlHPC-SSE3', - multithreaded: false, - version: '8.2.12', - type: 'raxml', - }, - { - name: 'raxmlHPC-PTHREADS-AVX', - multithreaded: true, - version: '8.2.12', - type: 'raxml', - }, - { - name: 'raxmlHPC-PTHREADS-SSE3', - multithreaded: true, - version: '8.2.12', - type: 'raxml', - }, - // TODO: put back in Astral - // { - // name: 'astral.5.7.8.jar', - // multithreaded: false, - // version: '5.7.8', - // type: 'astral', - // }, - ]; - -const binaries = allBinaries.filter( ( { multithreaded } ) => - MAX_NUM_CPUS === 1 - ? !multithreaded - : true, -); - -const initialBinaryName = binaries.filter( ( { initial } ) => initial )[0].name; - -// Available parameters for different analysis -const params = { - brL: 'brL', - SHlike: 'SHlike', - combinedOutput: 'combinedOutput', - reps: 'reps', - repsNg: 'repsNg', - runs: 'runs', - tree: 'tree', - startingTree: 'startingTree', - outGroup: 'outGroup', -}; - -const analysisOptions = [ - { - title: 'Fast tree search', - value: 'FT', - params: [params.brL, params.SHlike, params.outGroup], - }, - { - title: 'ML search', - value: 'ML', - params: [ - params.runs, - params.SHlike, - params.combinedOutput, - params.outGroup, - ], - }, - { - title: 'ML + rapid bootstrap', - value: 'ML+rBS', - params: [params.reps, params.brL, params.outGroup], - }, // default - { - title: 'ML + thorough bootstrap', - value: 'ML+tBS', - params: [params.runs, params.reps, params.brL, params.outGroup], - }, - { - title: 'Bootstrap + consensus', - value: 'BS+con', - params: [params.reps, params.brL, params.outGroup], - }, - { - title: 'Ancestral states', - value: 'AS', - needTree: true, - params: [params.tree], - }, - { - title: 'Pairwise distances', - value: 'PD', - params: [params.startingTree], - }, - { - title: 'RELL bootstraps', - value: 'RBS', - params: [], - }, -]; - -const raxmlNgAnalysisOptions = [ - { - title: 'Sanity check', - value: 'SC', - params: [], - }, - { - title: 'Compression and conversion to binary format', - value: 'CC', - params: [], - }, - { - title: 'ML tree inference', - value: 'TI', - params: [params.runs, params.outGroup], - }, - { - title: 'ML + thorough bootstrap + consensus', - value: 'ML+tBS+con', - params: [params.runs, params.repsNg, params.outGroup], - }, - { - title: 'ML + transfer bootstrap expectation + consensus', - value: 'ML+TBE+con', - params: [params.runs, params.repsNg, params.outGroup], - }, - { - title: 'Ancestral state reconstruction', - value: 'AS', - needTree: true, - params: [params.tree], - }, -]; - -class Binary extends Option { - constructor( run ) { - super( run, initialBinaryName, 'Binary', 'Name of binary' ); - } - options = binaries.map( ( { name } ) => ( { value: name, title: name } ) ); - @computed get version() { - return binaries.filter( ( b ) => b.name === this.value )[0].version; - } - @computed get type() { - return binaries.filter( ( b ) => b.name === this.value )[0].type; - } -} - -class NumThreads extends Option { - constructor( run ) { - super( run, 2, 'Threads', 'Number of cpu threads' ); - } - options = range( 1, MAX_NUM_CPUS + 1 ).map( ( value ) => ( { - value, - title: value, - } ) ); - @computed get notAvailable() { - return !( - /PTHREADS/.test( this.run.binary.value ) || this.run.usesModeltestNg - ); - } -} - -class Analysis extends Option { - constructor( run ) { - super( run, 'ML+rBS', 'Analysis', 'Type of analysis' ); - } - options = analysisOptions.map( ( { value, title } ) => ( { value, title } ) ); -} - -class RaxmlNgAnalysis extends Option { - constructor( run ) { - super( run, 'ML+TBE+con', 'Analysis', 'Type of analysis' ); - } - options = raxmlNgAnalysisOptions.map( ( { value, title } ) => ( { - value, - title, - } ) ); -} - -class NumRuns extends Option { - constructor( run ) { - super( run, 1, 'Runs', 'Number of runs' ); - } - options = [1, 10, 20, 50, 100, 500].map( ( value ) => ( { value, title: value } ) ); - @computed get notAvailable() { - return !this.run.analysisOption.params.includes( params.runs ); - } -} - -class NumRepetitions extends Option { - constructor( run ) { - super( run, 100, 'Reps.', 'Number of repetitions' ); - } - options = [ - 100, - 200, - 500, - 1000, - 10000, - 'autoMR', - 'autoMRE', - 'autoMRE_IGN', - 'autoFC', - ].map( ( value ) => ( { value, title: value } ) ); - @computed get notAvailable() { - return !this.run.analysisOption.params.includes( params.reps ); - } -} - -class NumRepetitionsNg extends Option { - constructor( run ) { - super( run, 100, 'Reps.', 'Number of repetitions' ); - } - options = [100, 200, 500, 1000, 10000, 'autoMRE'].map( ( value ) => ( { - value, - title: value, - } ) ); - @computed get notAvailable() { - return !this.run.analysisOption.params.includes( params.repsNg ); - } -} - -//TODO: Another branch lengths option for FT? ('compute brL' vs 'BS brL' for the rest) -class BranchLength extends Option { - constructor( run ) { - super( - run, - false, - 'BS brL', - 'Compute branch lengths', - 'Optimize model parameters and branch lengths for the given input tree', - ); - } - @computed get notAvailable() { - return !this.run.analysisOption.params.includes( params.brL ); - } -} - -class SHlike extends Option { - constructor( run ) { - super( - run, - false, - 'SH-like', - 'Compute log-likelihood test', - 'Shimodaira-Hasegawa-like procedure', - ); - } - @computed get notAvailable() { - return !this.run.analysisOption.params.includes( params.SHlike ); - } -} - -class CombinedOutput extends Option { - constructor( run ) { - super( run, false, 'Combined output', 'Concatenate output trees' ); - } - @computed get notAvailable() { - return !this.run.analysisOption.params.includes( params.combinedOutput ); - } - @computed get isUsed() { - return this.value && !this.notAvailable; - } -} - -class StartingTree extends Option { - constructor( run ) { - super( run, 'Maximum parsimony', 'Starting tree', '' ); - } - options = ['Maximum parsimony', 'User defined'].map( ( value ) => ( { - value, - title: value, - } ) ); - @computed get notAvailable() { - return !this.run.analysisOption.params.includes( params.startingTree ); - } -} - -class OutGroup extends Option { - constructor( run ) { - super( run, [''], 'Outgroup', '' ); - this.multiple = true; - } - @computed get options() { - return ['', ...this.run.taxons].map( ( value ) => ( { - value, - title: value, - } ) ); - } - - @action setValue = ( value ) => { - if ( this.value.includes( '' ) ) { - this.value = value.filter( ( v ) => v !== '' ); - return; - } - if ( !this.value.includes( '' ) && value.includes( '' ) ) { - this.value = value.filter( ( v ) => v === '' ); - return; - } - this.value = value; - }; - - @computed get notAvailable() { - return ( - !this.run.haveAlignments || - !this.run.analysisOption.params.includes( params.outGroup ) - ); - } - @computed get cmdValue() { - return this.value.includes( '' ) - ? '' - : this.value.join( ',' ); - } -} - -class SubstitutionMatrix extends Option { - constructor( run ) { - super( run, 'GTR', 'Substitution matrix' ); - } - @computed get options() { - if ( !this.run.haveAlignments ) { - return []; - } - const modelSettings = raxmlMatrixOptions[this.run.dataType]; - if ( !modelSettings ) { - return []; - } - return modelSettings.options.map( ( value ) => ( { - value, - title: value === 'GTR' - ? value - : `${value} + GAMMA`, - } ) ); - } - @computed get notAvailable() { - return ( - !this.run.haveAlignments || - this.run.dataType === 'binary' || - this.run.dataType === 'protein' || - this.run.dataType === 'multistate' || - this.run.usesRaxmlNg - ); - } - @computed get cmdValue() { - if ( this.run.dataType === 'binary' ) { - return 'BIN'; - } - if ( this.run.dataType === 'protein' ) { - return 'PROT'; - } - if ( this.run.dataType === 'multistate' ) { - return 'MULTI'; - } - if ( this.value === 'JC' || this.value === 'K80' || this.value === 'HKY' ) { - return 'GTR'; - } - return this.value; - } - @computed get extraCmdValue() { - switch ( this.value ) { - case 'JC': - return '--JC69'; - case 'K80': - return '--K80'; - case 'HKY': - return '--HKY85'; - default: - return ''; - } - } - @computed get notGTR() { - return this.value !== 'GTR'; - } -} - -class SubstitutionRate extends Option { - constructor( run ) { - super( run, 'GAMMA', 'Substitution rates' ); - } - @computed get options() { - if ( !this.run.haveAlignments ) { - return []; - } - const modelSettings = raxmlRateOptions; - if ( !modelSettings ) { - return []; - } - return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); - } - @computed get notAvailable() { - return ( - !this.run.haveAlignments || - ( ( this.run.dataType === 'dna' || - this.run.dataType === 'rna' || - this.run.dataType === 'nucleotide' ) && - this.run.substitutionMatrix.notGTR ) || - this.run.usesRaxmlNg - ); - } - @computed get cmdValue() { - if ( this.run.substitutionMatrix.notGTR ) { - return 'GAMMA'; - } - return this.value; - } - @computed get isCAT() { - return this.value === 'CAT'; - } -} - -class SubstitutionI extends Option { - constructor( run ) { - super( run, 'none', 'Proportion of invariant sites' ); - } - @computed get options() { - if ( !this.run.haveAlignments ) { - return []; - } - const modelSettings = raxmlIOptions; - if ( !modelSettings ) { - return []; - } - return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); - } - @computed get notAvailable() { - return ( - this.run.substitutionAscertainment.isSet || - !this.run.haveAlignments || - this.run.usesRaxmlNg - ); - } - @computed get cmdValue() { - return this.value === 'none' - ? '' - : 'I'; - } - @computed get isSet() { - return this.value !== 'none'; - } -} - -class SubstitutionAscertainment extends Option { - constructor( run ) { - super( run, 'none', 'Ascertainment bias correction' ); - } - @computed get options() { - if ( !this.run.haveAlignments ) { - return []; - } - const modelSettings = raxmlAscertainmentOptions; - if ( !modelSettings ) { - return []; - } - return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); - } - @computed get notAvailable() { - return ( - !this.run.haveAlignments || - this.run.usesRaxmlNg || - this.run.dataType === 'mixed' || - this.run.finalAlignment.hasInvariantSites || - this.run.substitutionI.isSet - ); - } - @computed get cmdValue() { - return this.value === 'none' - ? '' - : 'ASC_'; - } - @computed get extraCmdValue() { - switch ( this.value ) { - case "Lewis' method": - return '--asc-corr=lewis'; - case "Felsenstein's method": - return '--asc-corr=felsenstein'; - case "Stamatakis' method": - return '--asc-corr=stamatakis'; - default: - return ''; - } - } - @computed get isSet() { - return this.value !== 'none'; - } -} - -class AAMatrixName extends Option { - constructor( run ) { - super( - run, - 'BLOSUM62', - 'Matrix name', - 'Amino Acid Substitution Matrix name', - ); - } - options = raxmlSettings.aminoAcidSubstitutionMatrixOptions.options.map( - ( value ) => ( { value, title: value } ), - ); - @computed get notAvailable() { - return this.run.dataType !== 'protein'; - } -} - -class EstimatedFrequencies extends Option { - constructor( run ) { - super( - run, - false, - 'ML Freq.', - 'Estimated base frequencies', - 'Use estimated base frequencies instead of empirical.', - ); - } - @computed get notAvailable() { - return this.run.dataType === 'protein' || this.run.usesRaxmlNg; - } -} - -class BaseFrequencies extends Option { - constructor( run ) { - super( - run, - 'default', - 'Base frequencies', - 'Empirical, ML estimated or model based base frequencies', - ); - } - options = [ - { title: 'From model', value: 'default' }, - { title: 'Empirical', value: 'F' }, - { title: 'Estimated (ML)', value: 'X' }, - ]; - @computed get notAvailable() { - return this.run.dataType !== 'protein' || this.run.usesRaxmlNg; - } -} - -class MultistateModel extends Option { - constructor( run ) { - super( run, 'GTR', 'Multistate model' ); - } - options = raxmlSettings.kMultistateSubstitutionModelOptions.options.map( - ( value ) => ( { value, title: value } ), - ); - @computed get notAvailable() { - return this.run.dataType !== 'multistate' || this.run.usesRaxmlNg; - } -} - -class TreeFile extends Option { - constructor( run ) { - super( run, '', 'Tree', '' ); - } - @observable filePath = ''; - @computed get haveFile() { - return !!this.filePath; - } - @computed get filename() { - return basename( this.filePath ); - } - @computed get name() { - return name( this.filePath ); - } - @computed get dir() { - return dir( this.filePath ); - } - @action setFilePath = ( filePath ) => { - this.filePath = filePath; - }; - @action openFolder = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.showItemInFolder( this.filePath ); - }; - @action openFile = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.openPath( this.filePath ); - }; - @action remove = () => { - this.setFilePath( '' ); - }; -} - -class Tree extends TreeFile { - @computed get notAvailable() { - return !( - this.run.analysisOption.params.includes( params.tree ) || - ( !this.run.startingTree.notAvailable && - this.run.startingTree.value === 'User defined' ) - ); - } -} - -class BackboneConstraintTree extends TreeFile { - @computed get isSet() { - return this.run.useBackboneConstraint && this.haveFile; - } - @computed get canConstraint() { - const analysisWithConstraint = [ - 'ML', - 'ML+rBS', - 'ML+tBS', - 'BS+con', - 'RBS', - 'SC', - 'CC', - 'TI', - 'ML+tBS+con', - 'ML+TBE+con', - ]; - return analysisWithConstraint.includes( this.run.analysis.value ); - } - @computed get notAvailable() { - return !this.run.useBackboneConstraint || !this.canConstraint; - } -} - -class MultifurcatingConstraintTree extends TreeFile { - @computed get isSet() { - return this.run.useMultifurcatingConstraint && this.haveFile; - } - @computed get canConstraint() { - const analysisWithConstraint = [ - 'ML', - 'ML+rBS', - 'ML+tBS', - 'BS+con', - 'RBS', - 'SC', - 'CC', - 'TI', - 'ML+tBS+con', - 'ML+TBE+con', - ]; - return analysisWithConstraint.includes( this.run.analysis.value ); - } - @computed get notAvailable() { - return !this.run.useMultifurcatingConstraint || !this.canConstraint; - } -} - class Run extends StoreBase { constructor( parent, id ) { super(); + makeObservable( this, { + analysis: computed, + analysisOption: computed, + loadTreeFile: action, + loadBackboneConstraintFile: action, + loadMultifurcatingConstraintFile: action, + disableCheckUndeterminedSequence: observable, + outputName: observable, + setOutputName: action, + outputNameOk: computed, + outputNameSafe: computed, + outputNameNotice: computed, + outputFilenameSafe: computed, + outputDir: observable, + setOutputDir: action, + selectOutputDir: action, + openOutputDir: action, + showPartitionFor: observableRef, + showPartition: action, + hidePartition: action, + resultDir: observable, + resultFilenames: computed, + haveResult: computed, + openFile: action, + haveAlignments: computed, + hasAstralTree: computed, + taxons: computed, + dataType: computed, + error: observable, + missing: computed, + running: observable, + finished: observable, + exitCode: observable, + clearFinished: action, + ok: computed, + startDisabled: computed, + randomSeed: observable, + seedParsimony: computed, + seedRapidBootstrap: computed, + seedBootstrap: computed, + setRandomSeed: action, + haveRandomSeed: computed, + usesRaxmlNg: computed, + usesModeltestNg: computed, + inputIsAlignment: computed, + inputIsTree: computed, + usesModeltest: computed, + usesRaxml: computed, + usesAstral: computed, + modelTestCanRun: computed, + modelTestIsRunningOnAlignment: computed, + cancelModeltestOnAlignment: action, + args: computed, + ngSubstitutionModelCmd: computed, + showModifiedSnack: computed, + showModifiedDialog: computed, + modificationMessages: computed, + converted: computed, + modified: computed, + convertedAlignmentFrom: computed, + clearShowModified: action, + raxmlSubstitutionModelCmd: computed, + command: computed, + settingsFileContent: computed, + settingsFilePath: computed, + writeSettings: action, + startAstral: action, + start: action, + cancel: action, + afterRun: action, + alignments: observable, + astralTree: observable, + code: observable, + data: observable, + path: observable, + stdout: observable, + stderr: observable, + useBackboneConstraint: observable, + useMultifurcatingConstraint: observable, + numSites: computed, + needAlignment: computed, + removeRun: action, + loadAlignmentFiles: action, + loadAstralTree: action, + addAlignments: action, + addAstralFiles: action, + removeAlignment: action, + removeAstralTree: action, + canLoadAlignment: computed, + canLoadAstralTree: computed, + partitionFile: observable, + partitionFileContent: observable, + partitionFileName: computed, + havePartitionFile: computed, + canLoadPartitionFile: computed, + loadPartitionFile: action, + addPartitionFiles: action, + addTreeFiles: action, + removePartitionFile: action, + clearStdout: action, + clearStderr: action, + clearConsole: action, + clearError: action, + reset: action, + onRunStdout: action, + onRunStderr: action, + onAstralSuccess: action, + onRunFinished: action, + onRunError: action, + onBackboneConstraint: action, + onMultifurcatingConstraint: action, + } ); this.parent = parent; this.id = id; this.finalAlignment = new FinalAlignment( this ); @@ -802,12 +180,10 @@ class Run extends StoreBase { return raxmlParam; }; - @computed get analysis() { return this.raxmlNgSwitch( new RaxmlNgAnalysis( this ), new Analysis( this ) ); } - @computed get analysisOption() { return this.raxmlNgSwitch( raxmlNgAnalysisOptions.find( ( opt ) => opt.value === this.analysis.value ), @@ -846,19 +222,16 @@ class Run extends StoreBase { this.addTreeFiles( chosen.type, [{ path: chosen.filePath }] ); }; - @action - loadTreeFile = () => this.chooseTree( 'tree' ); + loadTreeFile = () => this.chooseTree( 'tree' ); - @action - loadBackboneConstraintFile = () => this.chooseTree( 'backboneConstraint' ); + loadBackboneConstraintFile = () => this.chooseTree( 'backboneConstraint' ); - @action - loadMultifurcatingConstraintFile = () => this.chooseTree( 'multifurcatingConstraint' ); + loadMultifurcatingConstraintFile = () => this.chooseTree( 'multifurcatingConstraint' ); - @observable disableCheckUndeterminedSequence = true; + disableCheckUndeterminedSequence = true; - @observable outputName = 'output'; - @action setOutputName = ( value ) => { + outputName = 'output'; + setOutputName = ( value ) => { this.outputName = filenamify( value.replace( /\s+/g, '_' ).trim() ); }; @@ -891,113 +264,109 @@ class Run extends StoreBase { }, ); - @computed get outputNameOk() { + get outputNameOk() { return this.outputNameAvailable.get().ok; } - @computed get outputNameSafe() { + get outputNameSafe() { return ( this.outputNameAvailable.get().outputNameUnused || this.outputNamePlaceholder ); } - @computed get outputNameNotice() { + get outputNameNotice() { return this.outputNameOk ? '' : `Output with that id already exists. New run will use output id '${this.outputNameSafe}'`; } - @computed get outputFilenameSafe() { + get outputFilenameSafe() { return `${this.outputNameSafe}.tre`; } - @observable outputDir = ''; - @action - setOutputDir = ( dir ) => { - this.outputDir = dir; - }; - @action - selectOutputDir = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); - const outputDir = await rendererBridge.selectOutputDir( this.id ); - if ( !outputDir ) { - return; - } - this.setOutputDir( outputDir ); - }; + outputDir = ''; + setOutputDir = ( dir ) => { + this.outputDir = dir; + }; + selectOutputDir = async () => { + const { rendererBridge } = /** @type {any} */ ( window ); + const outputDir = await rendererBridge.selectOutputDir( this.id ); + if ( !outputDir ) { + return; + } + this.setOutputDir( outputDir ); + }; - @action openOutputDir = async () => { + openOutputDir = async () => { const { rendererBridge } = /** @type {any} */ ( window ); await rendererBridge.openPath( this.outputDir ); }; - @observable.ref showPartitionFor = null; - @action - showPartition = ( alignment ) => { - this.showPartitionFor = alignment; - }; - @action - hidePartition = () => { - this.showPartition( null ); - }; + showPartitionFor = null; + showPartition = ( alignment ) => { + this.showPartitionFor = alignment; + }; + hidePartition = () => { + this.showPartition( null ); + }; // Result - @observable resultDir = ''; - @computed get resultFilenames() { + resultDir = ''; + get resultFilenames() { return this.outputNameAvailable.get().resultFilenames || []; } - @computed get haveResult() { + get haveResult() { return this.resultFilenames.length > 0 && this.resultDir === this.outputDir; } - @action openFile = async ( filePath ) => { + openFile = async ( filePath ) => { const { rendererBridge } = /** @type {any} */ ( window ); await rendererBridge.openPath( filePath ); }; - @computed get haveAlignments() { + get haveAlignments() { return this.alignments.length > 0; } - @computed get hasAstralTree() { + get hasAstralTree() { return !!this.astralTree; } - @computed get taxons() { + get taxons() { return this.haveAlignments ? this.alignments[0].taxons : []; } - @computed get dataType() { + get dataType() { return this.finalAlignment.dataType; } - @observable error = null; + error = null; - @computed get missing() { + get missing() { if ( !this.tree.notAvailable && !this.tree.filePath ) { return 'Missing tree, please load one.'; } return ''; } - @observable running = false; - @observable finished = false; - @observable exitCode = 0; - @action clearFinished = () => { + running = false; + finished = false; + exitCode = 0; + clearFinished = () => { this.finished = false; this.exitCode = 0; }; atomFinished; - @computed get ok() { + get ok() { return !this.error && !this.missing; } - @computed get startDisabled() { + get startDisabled() { return ( ( this.alignments.length === 0 && !this.hasAstralTree ) || !this.ok || @@ -1009,25 +378,25 @@ class Run extends StoreBase { ); } - @observable randomSeed = Math.floor( 1000000 * Math.random() ); - @computed get seedParsimony() { + randomSeed = Math.floor( 1000000 * Math.random() ); + get seedParsimony() { return this.randomSeed; } - @computed get seedRapidBootstrap() { + get seedRapidBootstrap() { return this.randomSeed; } - @computed get seedBootstrap() { + get seedBootstrap() { return this.randomSeed; } - @action setRandomSeed = ( value ) => { + setRandomSeed = ( value ) => { const v = Number( value ); if ( !Number.isNaN( v ) && v !== 0 && v < 1e6 ) { this.randomSeed = v; } }; - @computed get haveRandomSeed() { + get haveRandomSeed() { const analysisWithSeed = [ 'FT', 'ML', @@ -1043,50 +412,50 @@ class Run extends StoreBase { return analysisWithSeed.includes( this.analysis.value ); } - @computed get usesRaxmlNg() { + get usesRaxmlNg() { return this.binary.value.includes( 'raxml-ng' ); } - @computed get usesModeltestNg() { + get usesModeltestNg() { return this.binary.value.includes( 'modeltest-ng' ); } - @computed get inputIsAlignment() { + get inputIsAlignment() { return this.usesModeltest || this.usesRaxml; } - @computed get inputIsTree() { + get inputIsTree() { return this.usesAstral; } - @computed get usesModeltest() { + get usesModeltest() { return this.binary.type === 'modeltest'; } - @computed get usesRaxml() { + get usesRaxml() { return this.binary.type === 'raxml'; } - @computed get usesAstral() { + get usesAstral() { return this.binary.type === 'astral'; } - @computed get modelTestCanRun() { + get modelTestCanRun() { return this.dataType === 'nucleotide' || this.dataType === 'protein'; } - @computed get modelTestIsRunningOnAlignment() { + get modelTestIsRunningOnAlignment() { const running = this.alignments.some( ( alignment ) => alignment.modeltestLoading, ); return running; } - @action cancelModeltestOnAlignment = () => { + cancelModeltestOnAlignment = () => { this.alignments.forEach( ( alignment ) => alignment.cancelModelTest() ); }; - @computed get args() { + get args() { if ( this.usesAstral ) { return this.astralArgs(); } @@ -1099,27 +468,27 @@ class Run extends StoreBase { return this.raxmlArgs(); } - @computed get ngSubstitutionModelCmd() { + get ngSubstitutionModelCmd() { return this.haveAlignments ? this.alignments[0].ngSubstitutionModelCmd : ''; } - @computed get showModifiedSnack() { + get showModifiedSnack() { const shouldShow = this.alignments .map( ( a ) => a.showModifiedSnack ) .some( ( e ) => e ); return this.haveAlignments && shouldShow; } - @computed get showModifiedDialog() { + get showModifiedDialog() { const shouldShow = this.alignments .map( ( a ) => a.showModifiedDialog ) .some( ( e ) => e ); return this.haveAlignments && shouldShow; } - @computed get modificationMessages() { + get modificationMessages() { const messages = []; this.alignments.forEach( ( a ) => { messages.push( `${a.name}:\n` ); @@ -1130,17 +499,17 @@ class Run extends StoreBase { return messages; } - @computed get converted() { + get converted() { const converted = this.alignments.map( ( a ) => a.converted ).some( ( e ) => e ); return this.haveAlignments && converted; } - @computed get modified() { + get modified() { const modified = this.alignments.map( ( a ) => a.modified ).some( ( e ) => e ); return this.haveAlignments && modified; } - @computed get convertedAlignmentFrom() { + get convertedAlignmentFrom() { if ( !this.haveAlignments ) { return null; } @@ -1148,13 +517,13 @@ class Run extends StoreBase { return convertedAlignments[0].convertedFrom; } - @action clearShowModified = () => { + clearShowModified = () => { for ( let i = 0; i < this.alignments.length; i++ ) { this.alignments[i].clearModified(); } }; - @computed get raxmlSubstitutionModelCmd() { + get raxmlSubstitutionModelCmd() { let model = this.substitutionAscertainment.cmdValue + this.substitutionMatrix.cmdValue + @@ -1902,7 +1271,7 @@ class Run extends StoreBase { return cmdArgs.filter( ( args ) => args.length > 0 ); }; - @computed get command() { + get command() { if ( this.usesAstral ) { return this.args .map( ( cmdArgs ) => `java -jar ${this.binary.value} ${cmdArgs.join( ' ' )}` ) @@ -1913,7 +1282,7 @@ class Run extends StoreBase { .join( ' &&\\\n' ); } - @computed get settingsFileContent() { + get settingsFileContent() { let text = `The analysis was run using raxmlGUI 2.0 (version ${this.version}) as follows: Analysis: ${this.analysisOption.title} Binary: ${this.binary.value} version ${this.binary.version} @@ -1931,24 +1300,23 @@ Results saved to: ${this.outputDir} return text; } - @computed get settingsFilePath() { + get settingsFilePath() { return join( `${this.outputDir}`, `RAxML_GUI_Settings_${this.outputNameSafe}.txt`, ); } - @action - writeSettings = async () => { - try { - console.log( `Writing settings to ${this.settingsFilePath}...` ); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.writeFile( this.settingsFilePath, this.settingsFileContent ); - } catch ( err ) { - console.error( 'Error writing settings:', err ); - throw err; - } - }; + writeSettings = async () => { + try { + console.log( `Writing settings to ${this.settingsFilePath}...` ); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.writeFile( this.settingsFilePath, this.settingsFileContent ); + } catch ( err ) { + console.error( 'Error writing settings:', err ); + throw err; + } + }; startAstral = async () => { const { id, binary, args } = this; @@ -1962,209 +1330,197 @@ Results saved to: ${this.outputDir} } ); }; - @action - start = async () => { - const { - id, - args, - binary, - outputDir, - outputFilenameSafe: outputFilename, - outputNameSafe: outputName, - combinedOutput, - usesRaxmlNg, - usesModeltestNg, - finalAlignment, - } = this; - - // If binary is astral use start in seperate function - if ( this.usesAstral ) { - return this.startAstral(); - } + start = async () => { + const { + id, + args, + binary, + outputDir, + outputFilenameSafe: outputFilename, + outputNameSafe: outputName, + combinedOutput, + usesRaxmlNg, + usesModeltestNg, + finalAlignment, + } = this; + + // If binary is astral use start in seperate function + if ( this.usesAstral ) { + return this.startAstral(); + } - // Less than 4 sequences and RAxML would error out - if ( this.finalAlignment.numSequences <= 3 ) { - this.parent.onError( - new UserFixError( - 'To start a run with RAxML the final alignment needs to have at least four sequences.', - ), - ); - return; - } + // Less than 4 sequences and RAxML would error out + if ( this.finalAlignment.numSequences <= 3 ) { + this.parent.onError( + new UserFixError( + 'To start a run with RAxML the final alignment needs to have at least four sequences.', + ), + ); + return; + } - this.running = true; - const startToken = {}; - this.startToken = startToken; - if ( this.outputName !== this.outputNameSafe ) { - this.outputName = this.outputNameSafe; - } + this.running = true; + const startToken = {}; + this.startToken = startToken; + if ( this.outputName !== this.outputNameSafe ) { + this.outputName = this.outputNameSafe; + } - if ( this.finalAlignment.numAlignments > 1 ) { - await this.finalAlignment.writeConcatenatedAlignmentAndPartition(); - } else if ( !this.finalAlignment.partition.isDefault ) { - await this.finalAlignment.writePartition(); - } - await this.writeSettings(); - if ( this.startToken !== startToken ) { - return; - } - console.log( `Start run ${id} with args ${args}` ); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.startRun( { - id, - args, - binaryName: binary.value, - outputDir, - outputFilename, - outputName, - combinedOutput: combinedOutput.isUsed, - usesRaxmlNg, - usesModeltestNg, - inputPath: finalAlignment.path, - } ); - }; + if ( this.finalAlignment.numAlignments > 1 ) { + await this.finalAlignment.writeConcatenatedAlignmentAndPartition(); + } else if ( !this.finalAlignment.partition.isDefault ) { + await this.finalAlignment.writePartition(); + } + await this.writeSettings(); + if ( this.startToken !== startToken ) { + return; + } + console.log( `Start run ${id} with args ${args}` ); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.startRun( { + id, + args, + binaryName: binary.value, + outputDir, + outputFilename, + outputName, + combinedOutput: combinedOutput.isUsed, + usesRaxmlNg, + usesModeltestNg, + inputPath: finalAlignment.path, + } ); + }; - @action - cancel = () => { - this.startToken = null; - const { rendererBridge } = /** @type {any} */ ( window ); - rendererBridge.cancelRun( this.id ); - this.afterRun(); - }; + cancel = () => { + this.startToken = null; + const { rendererBridge } = /** @type {any} */ ( window ); + rendererBridge.cancelRun( this.id ); + this.afterRun(); + }; - @action - afterRun = () => { - this.running = false; - this.atomAfterRun.reportChanged(); - }; + afterRun = () => { + this.running = false; + this.atomAfterRun.reportChanged(); + }; - @observable alignments = []; - @observable astralTree = undefined; - @observable code = undefined; - @observable data = ''; - @observable path = undefined; - @observable stdout = ''; - @observable stderr = ''; + alignments = []; + astralTree = undefined; + code = undefined; + data = ''; + path = undefined; + stdout = ''; + stderr = ''; - @observable useBackboneConstraint = false; - @observable useMultifurcatingConstraint = false; + useBackboneConstraint = false; + useMultifurcatingConstraint = false; - @computed get numSites() { return this.alignments.reduce( ( sum, n ) => sum + n, 0 ); } - @computed get needAlignment() { return true; } - @action - removeRun = () => { - this.parent.deleteRun( this ); - }; + removeRun = () => { + this.parent.deleteRun( this ); + }; - @action - loadAlignmentFiles = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); - const alignments = await rendererBridge.selectAlignment( this.id ); - if ( !alignments ) { - return; - } - this.addAlignments( alignments ); - }; + loadAlignmentFiles = async () => { + const { rendererBridge } = /** @type {any} */ ( window ); + const alignments = await rendererBridge.selectAlignment( this.id ); + if ( !alignments ) { + return; + } + this.addAlignments( alignments ); + }; - @action - loadAstralTree = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); - const file = await rendererBridge.selectAstralFile( this.id ); - if ( !file ) { - return; - } - this.addAstralFiles( file ); - }; + loadAstralTree = async () => { + const { rendererBridge } = /** @type {any} */ ( window ); + const file = await rendererBridge.selectAstralFile( this.id ); + if ( !file ) { + return; + } + this.addAstralFiles( file ); + }; haveAlignment = ( id ) => { // TODO: Input.js queries without id, doe it work as expected? Later queries with path instead of id return this.alignments.findIndex( ( alignment ) => alignment.id === id ) >= 0; }; - @action - addAlignments = ( alignments ) => { - alignments.forEach( ( { path } ) => { - if ( !this.haveAlignment( path ) ) { - this.alignments.push( new Alignment( this, path ) ); - if ( this.alignments.length === 1 ) { - this.setOutputName( this.alignments[0].name ); - if ( !this.outputDir ) { - this.setOutputDir( this.alignments[0].dir ); - } + addAlignments = ( alignments ) => { + alignments.forEach( ( { path } ) => { + if ( !this.haveAlignment( path ) ) { + this.alignments.push( new Alignment( this, path ) ); + if ( this.alignments.length === 1 ) { + this.setOutputName( this.alignments[0].name ); + if ( !this.outputDir ) { + this.setOutputDir( this.alignments[0].dir ); } } - } ); - }; - - @action - addAstralFiles = ( { path } ) => { - if ( !this.hasAstralTree ) { - this.astralTree = new AstralTree( this, path ); - this.setOutputName( this.astralTree.name ); - if ( !this.outputDir ) { - this.setOutputDir( this.astralTree.dir ); - } } - }; + } ); + }; - @action - removeAlignment = ( alignment ) => { - const oldDataType = this.dataType; - const index = this.alignments.indexOf( alignment ); - if ( index >= 0 ) { - this.alignments.splice( index, 1 ); + addAstralFiles = ( { path } ) => { + if ( !this.hasAstralTree ) { + this.astralTree = new AstralTree( this, path ); + this.setOutputName( this.astralTree.name ); + if ( !this.outputDir ) { + this.setOutputDir( this.astralTree.dir ); } - if ( this.haveAlignments ) { + } + }; + + removeAlignment = ( alignment ) => { + const oldDataType = this.dataType; + const index = this.alignments.indexOf( alignment ); + if ( index >= 0 ) { + this.alignments.splice( index, 1 ); + } + if ( this.haveAlignments ) { // this.dataType is computed automatically with the reduced set, reset to default if changed (from mixed or multistate) - if ( this.dataType !== oldDataType ) { + if ( this.dataType !== oldDataType ) { // This parameter is deleted, but there seems to be no need for updating other params // this.substitutionModel.value = raxmlModelOptions[this.dataType].default; - } - } else { - this.reset(); } - }; + } else { + this.reset(); + } + }; - @action - removeAstralTree = () => { - this.astralTree = null; - }; + removeAstralTree = () => { + this.astralTree = null; + }; - @computed get canLoadAlignment() { + get canLoadAlignment() { return ( ( this.binary.type === 'raxml' || this.binary.type === 'modeltest' ) && !this.havePartitionFile ); } - @computed get canLoadAstralTree() { + get canLoadAstralTree() { return this.usesAstral && !this.hasAstralTree; } - @observable partitionFile = ''; - @observable partitionFileContent = ''; + partitionFile = ''; + partitionFileContent = ''; - @computed get partitionFileName() { + get partitionFileName() { return basename( this.partitionFile ); } - @computed get havePartitionFile() { + get havePartitionFile() { return this.partitionFile !== ''; } - @computed get canLoadPartitionFile() { + get canLoadPartitionFile() { return this.alignments.length === 1 && !this.havePartitionFile; } - @action loadPartitionFile = async () => { + loadPartitionFile = async () => { const { rendererBridge } = /** @type {any} */ ( window ); const filePath = await rendererBridge.selectPartitionFile( this.id ); if ( !filePath ) { @@ -2173,70 +1529,65 @@ Results saved to: ${this.outputDir} await this.addPartitionFiles( [{ path: filePath }] ); }; - @action - addPartitionFiles = async ( files ) => { - if ( !files.length ) { - return; - } - const { path } = files[0]; - const { rendererBridge } = /** @type {any} */ ( window ); - const content = await rendererBridge.readFile( path ); + addPartitionFiles = async ( files ) => { + if ( !files.length ) { + return; + } + const { path } = files[0]; + const { rendererBridge } = /** @type {any} */ ( window ); + const content = await rendererBridge.readFile( path ); + runInAction( () => { this.partitionFile = path; this.partitionFileContent = content; - }; + } ); + }; - @action - addTreeFiles = ( type, files ) => { - if ( !files.length ) { - return; - } - const { path } = files[0]; - switch ( type ) { - case 'tree': - this.tree.setFilePath( path ); - break; - case 'backboneConstraint': - this.backboneConstraint.setFilePath( path ); - break; - case 'multifurcatingConstraint': - this.multifurcatingConstraint.setFilePath( path ); - break; - default: - break; - } - }; + addTreeFiles = ( type, files ) => { + if ( !files.length ) { + return; + } + const { path } = files[0]; + switch ( type ) { + case 'tree': + this.tree.setFilePath( path ); + break; + case 'backboneConstraint': + this.backboneConstraint.setFilePath( path ); + break; + case 'multifurcatingConstraint': + this.multifurcatingConstraint.setFilePath( path ); + break; + default: + break; + } + }; - @action removePartitionFile = () => { + removePartitionFile = () => { this.partitionFile = ''; this.partitionFileContent = ''; }; - @action - clearStdout = () => { - this.stdout = ''; - }; + clearStdout = () => { + this.stdout = ''; + }; - @action - clearStderr = () => { - this.stderr = ''; - }; + clearStderr = () => { + this.stderr = ''; + }; - @action - clearConsole = () => { - this.clearStdout(); - this.clearStderr(); - }; + clearConsole = () => { + this.clearStdout(); + this.clearStderr(); + }; - @action - clearError = () => { - this.error = null; - }; + clearError = () => { + this.error = null; + }; - @action - reset = () => { - this.outGroup.reset(); - this.removePartitionFile(); - }; + reset = () => { + this.outGroup.reset(); + this.removePartitionFile(); + }; dispose = () => { this.cancel(); @@ -2255,64 +1606,57 @@ Results saved to: ${this.outputDir} // Listeners // ----------------------------------------------------------- - @action - onRunStdout = ( { id, content } ) => { - if ( id === this.id ) { - this.stdout += content; - } - }; + onRunStdout = ( { id, content } ) => { + if ( id === this.id ) { + this.stdout += content; + } + }; - @action - onRunStderr = ( { id, content } ) => { - if ( id === this.id ) { - this.stderr += content; - } - }; + onRunStderr = ( { id, content } ) => { + if ( id === this.id ) { + this.stderr += content; + } + }; - @action - onAstralSuccess = ( { id, exitCode } ) => { - if ( id === this.id ) { - console.log( `Process ${id} finished with exitCode '${exitCode}'` ); - this.resultDir = this.outputDir; - this.atomFinished.reportChanged(); - this.finished = true; - this.exitCode = exitCode; - this.afterRun(); - } - }; + onAstralSuccess = ( { id, exitCode } ) => { + if ( id === this.id ) { + console.log( `Process ${id} finished with exitCode '${exitCode}'` ); + this.resultDir = this.outputDir; + this.atomFinished.reportChanged(); + this.finished = true; + this.exitCode = exitCode; + this.afterRun(); + } + }; - @action - onRunFinished = ( { id, resultDir, resultFilenames, exitCode } ) => { - if ( id === this.id ) { - console.log( - `Process ${id} finished with exitCode '${exitCode}' and result filenames ${resultFilenames} in dir ${resultDir}.`, - ); - this.resultDir = resultDir; - this.atomFinished.reportChanged(); - this.finished = true; - this.exitCode = exitCode; - this.afterRun(); - } - }; + onRunFinished = ( { id, resultDir, resultFilenames, exitCode } ) => { + if ( id === this.id ) { + console.log( + `Process ${id} finished with exitCode '${exitCode}' and result filenames ${resultFilenames} in dir ${resultDir}.`, + ); + this.resultDir = resultDir; + this.atomFinished.reportChanged(); + this.finished = true; + this.exitCode = exitCode; + this.afterRun(); + } + }; - @action - onRunError = ( { id, error } ) => { - if ( id === this.id ) { - console.log( `Process ${id} finished with error:`, error ); - this.error = error; - this.afterRun(); - } - }; + onRunError = ( { id, error } ) => { + if ( id === this.id ) { + console.log( `Process ${id} finished with error:`, error ); + this.error = error; + this.afterRun(); + } + }; - @action - onBackboneConstraint = ( event, params ) => { - this.useBackboneConstraint = !this.useBackboneConstraint; - }; + onBackboneConstraint = ( event, params ) => { + this.useBackboneConstraint = !this.useBackboneConstraint; + }; - @action - onMultifurcatingConstraint = ( event, params ) => { - this.useMultifurcatingConstraint = !this.useMultifurcatingConstraint; - }; + onMultifurcatingConstraint = ( event, params ) => { + this.useMultifurcatingConstraint = !this.useMultifurcatingConstraint; + }; generateReport = ( { maxStdoutLength = 1000 } = {} ) => { const { command, stdout } = this; diff --git a/src/app/store/RunList.js b/src/app/store/RunList.js index 10156ecd..a5630c9a 100644 --- a/src/app/store/RunList.js +++ b/src/app/store/RunList.js @@ -1,84 +1,90 @@ -import { observable, computed, action } from 'mobx'; +import { observable, computed, action, makeObservable } from 'mobx'; import Run from './Run'; import AppStore from './AppStore'; import { runEvents } from './StoreBase'; class RunList extends AppStore { - @observable runs = []; - @observable activeIndex = 0; + runs = []; + activeIndex = 0; constructor() { super(); + makeObservable( this, { + runs: observable, + activeIndex: observable, + error: observable, + errorTitle: observable, + clearError: action, + activeRun: computed, + addRun: action, + deleteRun: action, + setActive: action, + deleteActive: action, + onError: action, + onUnhandledError: action, + onBackboneConstraint: action, + onMultifurcatingConstraint: action, + } ); this.addRun(); this.listen(); } - @observable error = null; - @observable errorTitle = null; - @action - clearError = () => { - this.error = null; - this.errorTitle = null; - }; + error = null; + errorTitle = null; + clearError = () => { + this.error = null; + this.errorTitle = null; + }; - @computed get activeRun() { return this.runs[this.activeIndex]; } - @action - addRun = () => { - let maxId = 0; - this.runs.forEach( ( run ) => ( maxId = Math.max( run.id, maxId ) ) ); - this.runs.push( new Run( this, maxId + 1 ) ); - this.activeIndex = this.runs.length - 1; - }; + addRun = () => { + let maxId = 0; + this.runs.forEach( ( run ) => ( maxId = Math.max( run.id, maxId ) ) ); + this.runs.push( new Run( this, maxId + 1 ) ); + this.activeIndex = this.runs.length - 1; + }; - @action - deleteRun = ( run ) => { - run.dispose(); - const runIndex = this.runs.findIndex( ( m ) => m.id === run.id ); - this.runs.splice( runIndex, 1 ); - if ( this.runs.length === 0 ) { - this.runs.push( new Run( this, 1 ) ); - } - this.activeIndex = Math.min( this.runs.length - 1, this.activeIndex ); - }; + deleteRun = ( run ) => { + run.dispose(); + const runIndex = this.runs.findIndex( ( m ) => m.id === run.id ); + this.runs.splice( runIndex, 1 ); + if ( this.runs.length === 0 ) { + this.runs.push( new Run( this, 1 ) ); + } + this.activeIndex = Math.min( this.runs.length - 1, this.activeIndex ); + }; - @action - setActive = ( index ) => { - this.activeIndex = index; - }; + setActive = ( index ) => { + this.activeIndex = index; + }; - @action - deleteActive = () => { - this.deleteRun( this.activeRun ); - }; + deleteActive = () => { + this.deleteRun( this.activeRun ); + }; - @action - onError = ( error ) => { - this.errorTitle = null; - this.error = error; - }; + onError = ( error ) => { + this.errorTitle = null; + this.error = error; + }; - @action - onUnhandledError = ( { title, error } ) => { - console.log( `Unhandled error:`, error ); - this.errorTitle = title; - this.error = error; - }; + onUnhandledError = ( { title, error } ) => { + console.log( `Unhandled error:`, error ); + this.errorTitle = title; + this.error = error; + }; - @action - onBackboneConstraint = ( event, params ) => { - this.activeRun.useBackboneConstraint = + onBackboneConstraint = ( event, params ) => { + this.activeRun.useBackboneConstraint = !this.activeRun.useBackboneConstraint; - }; + }; - @action - onMultifurcatingConstraint = ( event, params ) => { - this.activeRun.useMultifurcatingConstraint = + onMultifurcatingConstraint = ( event, params ) => { + this.activeRun.useMultifurcatingConstraint = !this.activeRun.useMultifurcatingConstraint; - }; + }; listen = () => { this.subscribe( runEvents.onUnhandledError, this.onUnhandledError ); diff --git a/src/app/store/RunList.test.js b/src/app/store/RunList.test.js new file mode 100644 index 00000000..bbb68d4e --- /dev/null +++ b/src/app/store/RunList.test.js @@ -0,0 +1,278 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import AppStore from './AppStore'; +import RunList from './RunList'; +import { runEvents } from './StoreBase'; + +let listeners; +let cancelRun; + +// The run list subscribes to bridge events; keep each listener so a test can fire it. +function stubBridge() { + const byName = {}; + listeners = byName; + cancelRun = jest.fn(); + const bridge = { cancelRun, getVersion: () => Promise.resolve( '2.0.0' ) }; + for ( const name of Object.values( runEvents ) ) { + bridge[name] = ( listener ) => { + ( byName[name] ||= [] ).push( listener ); + return () => { + byName[name] = byName[name].filter( ( l ) => l !== listener ); + }; + }; + } + window.rendererBridge = bridge; +} + +function fire( name, ...args ) { + ( listeners[name] || [] ).forEach( ( listener ) => listener( ...args ) ); +} + +// Records every value an autorun sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +beforeEach( () => stubBridge() ); + +describe( 'AppStore', () => { + it( 'loads the version from the renderer bridge', async () => { + const store = new AppStore(); + const { seen, stop } = track( () => store.version ); + await Promise.resolve(); + expect( store.version ).toBe( '2.0.0' ); + expect( seen ).toEqual( [undefined, '2.0.0'] ); + stop(); + } ); + + it( 'a reaction sees a version set directly', () => { + const store = new AppStore(); + const { seen, stop } = track( () => store.version ); + runInAction( () => { + store.version = '9.9.9'; + } ); + expect( seen ).toEqual( [undefined, '9.9.9'] ); + stop(); + } ); + + it( 'setAppSnack and clearAppSnack toggle the snack', () => { + const store = new AppStore(); + const { seen, stop } = track( () => store.showAppSnack ); + store.setAppSnack(); + expect( store.showAppSnack ).toBe( true ); + store.clearAppSnack(); + expect( store.showAppSnack ).toBe( false ); + expect( seen ).toEqual( [false, true, false] ); + stop(); + } ); + + it( 'has a citation and a config', () => { + const store = new AppStore(); + expect( store.citation.format ).toBe( 'txt' ); + expect( store.config.isDarkMode ).toBe( false ); + } ); +} ); + +describe( 'RunList', () => { + it( 'starts with one active run', () => { + const list = new RunList(); + expect( list.runs ).toHaveLength( 1 ); + expect( list.activeIndex ).toBe( 0 ); + expect( list.activeRun ).toBe( list.runs[0] ); + expect( list.activeRun.id ).toBe( 1 ); + } ); + + it( 'adding a run appends it with the next id and makes it active', () => { + const list = new RunList(); + const { seen, stop } = track( () => list.activeRun.id ); + list.addRun(); + list.addRun(); + expect( list.runs.map( ( r ) => r.id ) ).toEqual( [1, 2, 3] ); + expect( list.activeIndex ).toBe( 2 ); + expect( seen ).toEqual( [1, 2, 3] ); + stop(); + } ); + + it( 'adding a run after a delete uses one more than the highest id', () => { + const list = new RunList(); + list.addRun(); + list.addRun(); + list.deleteRun( list.runs[1] ); + list.addRun(); + expect( list.runs.map( ( r ) => r.id ) ).toEqual( [1, 3, 4] ); + } ); + + it( 'switching the active run changes activeRun', () => { + const list = new RunList(); + list.addRun(); + const { seen, stop } = track( () => list.activeRun.id ); + list.setActive( 0 ); + expect( list.activeIndex ).toBe( 0 ); + expect( list.activeRun ).toBe( list.runs[0] ); + list.setActive( 1 ); + expect( seen ).toEqual( [2, 1, 2] ); + stop(); + } ); + + it( 'activeRun follows activeIndex and runs set directly', () => { + const list = new RunList(); + list.addRun(); + const { seen, stop } = track( () => list.activeRun?.id ); + runInAction( () => { + list.activeIndex = 0; + } ); + runInAction( () => { + list.runs = list.runs.slice().reverse(); + } ); + expect( seen ).toEqual( [2, 1, 2] ); + stop(); + } ); + + it( 'removing a run disposes it and clamps the active index', () => { + const list = new RunList(); + list.addRun(); + list.addRun(); + const last = list.runs[2]; + list.deleteRun( last ); + expect( cancelRun ).toHaveBeenCalledWith( 3 ); + expect( list.runs.map( ( r ) => r.id ) ).toEqual( [1, 2] ); + expect( list.activeIndex ).toBe( 1 ); + expect( list.activeRun.id ).toBe( 2 ); + } ); + + it( 'removing a run before the active one keeps the index', () => { + const list = new RunList(); + list.addRun(); + list.addRun(); + list.setActive( 1 ); + list.deleteRun( list.runs[0] ); + expect( list.activeIndex ).toBe( 1 ); + expect( list.activeRun.id ).toBe( 3 ); + } ); + + it( 'removing the only run replaces it with a fresh run 1', () => { + const list = new RunList(); + list.addRun(); + list.deleteRun( list.runs[0] ); + const remaining = list.runs[0]; + list.deleteRun( remaining ); + expect( list.runs ).toHaveLength( 1 ); + expect( list.runs[0] ).not.toBe( remaining ); + expect( list.activeRun.id ).toBe( 1 ); + expect( list.activeIndex ).toBe( 0 ); + } ); + + it( 'deleteActive removes the active run', () => { + const list = new RunList(); + list.addRun(); + list.setActive( 0 ); + list.deleteActive(); + expect( list.runs.map( ( r ) => r.id ) ).toEqual( [2] ); + expect( list.activeRun.id ).toBe( 2 ); + } ); + + it( 'a removed run stops listening to bridge events', () => { + const list = new RunList(); + list.addRun(); + const removed = list.runs[1]; + list.deleteRun( removed ); + fire( runEvents.onRunStdout, { id: 2, content: 'late' } ); + expect( removed.stdout ).toBe( '' ); + } ); + + it( 'two runs keep independent state', () => { + const list = new RunList(); + list.addRun(); + const [first, second] = list.runs; + runInAction( () => { + first.useBackboneConstraint = true; + } ); + fire( runEvents.onRunStdout, { id: 2, content: 'second only' } ); + expect( first.useBackboneConstraint ).toBe( true ); + expect( second.useBackboneConstraint ).toBe( false ); + expect( first.stdout ).toBe( '' ); + expect( second.stdout ).toBe( 'second only' ); + expect( first.outputNamePlaceholder ).toBe( '1' ); + expect( second.outputNamePlaceholder ).toBe( '2' ); + } ); + + it( 'onError sets the error and clears the title; clearError resets both', () => { + const list = new RunList(); + const { seen, stop } = track( () => [list.errorTitle, list.error] ); + runInAction( () => { + list.errorTitle = 'Old'; + } ); + const error = new Error( 'boom' ); + list.onError( error ); + expect( list.error ).toBe( error ); + expect( list.errorTitle ).toBeNull(); + list.clearError(); + expect( list.error ).toBeNull(); + expect( list.errorTitle ).toBeNull(); + expect( seen ).toEqual( [ + [null, null], + ['Old', null], + [null, error], + [null, null], + ] ); + stop(); + } ); + + it( 'onUnhandledError sets the title and error', () => { + jest.spyOn( console, 'log' ).mockImplementation( () => {} ); + const list = new RunList(); + const error = new Error( 'crash' ); + list.onUnhandledError( { title: 'Oops', error } ); + expect( list.errorTitle ).toBe( 'Oops' ); + expect( list.error ).toBe( error ); + console.log.mockRestore(); + } ); + + it( 'the constraint toggles flip the active run only', () => { + const list = new RunList(); + list.addRun(); + const [first, second] = list.runs; + list.onBackboneConstraint(); + list.onMultifurcatingConstraint(); + expect( second.useBackboneConstraint ).toBe( true ); + expect( second.useMultifurcatingConstraint ).toBe( true ); + expect( first.useBackboneConstraint ).toBe( false ); + expect( first.useMultifurcatingConstraint ).toBe( false ); + list.onBackboneConstraint(); + list.onMultifurcatingConstraint(); + expect( second.useBackboneConstraint ).toBe( false ); + expect( second.useMultifurcatingConstraint ).toBe( false ); + } ); + + it( 'routes bridge events to its actions', () => { + jest.spyOn( console, 'log' ).mockImplementation( () => {} ); + const list = new RunList(); + fire( runEvents.onAddRun ); + expect( list.runs ).toHaveLength( 2 ); + fire( runEvents.onToggleBackboneConstraint ); + fire( runEvents.onToggleMultifurcatingConstraint ); + expect( list.activeRun.useBackboneConstraint ).toBe( true ); + expect( list.activeRun.useMultifurcatingConstraint ).toBe( true ); + fire( runEvents.onRemoveRun ); + expect( list.runs.map( ( r ) => r.id ) ).toEqual( [1] ); + const error = new Error( 'main' ); + fire( runEvents.onUnhandledError, { title: 'Main', error } ); + expect( list.errorTitle ).toBe( 'Main' ); + expect( list.error ).toBe( error ); + console.log.mockRestore(); + } ); + + it( 'generateReport reports the active run with truncated stdout', () => { + const list = new RunList(); + runInAction( () => { + list.activeRun.stdout = 'abcdef'; + } ); + const report = list.generateReport( { maxStdoutLength: 3 } ); + expect( report.stdout ).toBe( '[3 more characters]...def' ); + expect( report.command ).toBe( list.activeRun.command ); + expect( list.generateReport().stdout ).toBe( 'abcdef' ); + } ); +} ); diff --git a/src/app/store/RunOptions.js b/src/app/store/RunOptions.js new file mode 100644 index 00000000..bb7ca28f --- /dev/null +++ b/src/app/store/RunOptions.js @@ -0,0 +1,873 @@ +import { observable, computed, action, makeObservable, override } from 'mobx'; +import { range } from 'd3-array'; + +import Option from './Option'; +import { host } from './host'; +import { basename, dir, name } from '../paths'; +import * as raxmlSettings from '../../settings/raxml'; + +const raxmlMatrixOptions = raxmlSettings.matrixOptions; +const raxmlRateOptions = raxmlSettings.rateOptions; +const raxmlIOptions = raxmlSettings.iOptions; +const raxmlAscertainmentOptions = raxmlSettings.ascertainmentOptions; + +export const MAX_NUM_CPUS = navigator.hardwareConcurrency || 1; + +// On Windows 7 (= 6.1) use older versions of RAxML +const [majorVersion, minorVersion] = host.release.split( '.' ); +const winBinaries = + majorVersion === '6' && minorVersion === '1' + ? [ + // TODO: add raxml ng windows exe + // TODO: Crashes on Win7, disabled for now + // { name: 'modeltest-ng.exe', version: '0.1.7' }, + { + name: 'raxmlHPC_Win7.exe', + multithreaded: false, + version: '8.2.10', + type: 'raxml', + }, + { + name: 'raxmlHPC-SSE3_Win7.exe', + multithreaded: false, + version: '8.2.10', + type: 'raxml', + }, + // TODO: Crashes on Win7, disabled for now + // { + // name: 'raxmlHPC-PTHREADS-AVX_Win7.exe', + // multithreaded: true, + // version: '8.2.10', + // }, + { + name: 'raxmlHPC-PTHREADS-SSE3_Win7.exe', + multithreaded: true, + version: '8.2.10', + initial: true, + type: 'raxml', + }, + // TODO: put back in Astral + // { + // name: 'astral.5.7.8.jar', + // multithreaded: false, + // version: '5.7.8', + // type: 'astral', + // }, + ] + : [ + // TODO: add raxml ng windows exe + { name: 'modeltest-ng.exe', version: '0.1.7', type: 'modeltest' }, + { + name: 'raxmlHPC.exe', + multithreaded: false, + version: '8.2.12', + type: 'raxml', + }, + { + name: 'raxmlHPC-SSE3.exe', + multithreaded: false, + version: '8.2.12', + type: 'raxml', + }, + { + name: 'raxmlHPC-PTHREADS-AVX.exe', + multithreaded: true, + version: '8.2.12', + type: 'raxml', + }, + { + name: 'raxmlHPC-PTHREADS-SSE3.exe', + multithreaded: true, + version: '8.2.12', + initial: true, + type: 'raxml', + }, + // TODO: put back in Astral + // { + // name: 'astral.5.7.8.jar', + // multithreaded: false, + // version: '5.7.8', + // type: 'astral', + // }, + ]; + +const likelyARM = + host.arch.includes( 'arm64' ) || host.cpuModel.includes( 'Apple' ); +const armBinaries = [ + { + name: 'modeltest-ng-ARM64', + multithreaded: true, + version: '0.1.7', + type: 'modeltest', + }, +]; +const x64Binaries = [ + { + name: 'modeltest-ng', + multithreaded: true, + version: '0.1.7', + type: 'modeltest', + }, +]; + +const allBinaries = host.windows + ? winBinaries + : [ + ...( !likelyARM + ? x64Binaries + : armBinaries ), + { + name: 'raxml-ng', + multithreaded: true, + version: '1.2.2', + initial: true, + type: 'raxml', + }, + { + name: 'raxmlHPC', + multithreaded: false, + version: '8.2.12', + type: 'raxml', + }, + { + name: 'raxmlHPC-SSE3', + multithreaded: false, + version: '8.2.12', + type: 'raxml', + }, + { + name: 'raxmlHPC-PTHREADS-AVX', + multithreaded: true, + version: '8.2.12', + type: 'raxml', + }, + { + name: 'raxmlHPC-PTHREADS-SSE3', + multithreaded: true, + version: '8.2.12', + type: 'raxml', + }, + // TODO: put back in Astral + // { + // name: 'astral.5.7.8.jar', + // multithreaded: false, + // version: '5.7.8', + // type: 'astral', + // }, + ]; + +export const binaries = allBinaries.filter( ( { multithreaded } ) => + MAX_NUM_CPUS === 1 + ? !multithreaded + : true, +); + +const initialBinaryName = binaries.filter( ( { initial } ) => initial )[0].name; + +// Available parameters for different analysis +const params = { + brL: 'brL', + SHlike: 'SHlike', + combinedOutput: 'combinedOutput', + reps: 'reps', + repsNg: 'repsNg', + runs: 'runs', + tree: 'tree', + startingTree: 'startingTree', + outGroup: 'outGroup', +}; + +export const analysisOptions = [ + { + title: 'Fast tree search', + value: 'FT', + params: [params.brL, params.SHlike, params.outGroup], + }, + { + title: 'ML search', + value: 'ML', + params: [ + params.runs, + params.SHlike, + params.combinedOutput, + params.outGroup, + ], + }, + { + title: 'ML + rapid bootstrap', + value: 'ML+rBS', + params: [params.reps, params.brL, params.outGroup], + }, // default + { + title: 'ML + thorough bootstrap', + value: 'ML+tBS', + params: [params.runs, params.reps, params.brL, params.outGroup], + }, + { + title: 'Bootstrap + consensus', + value: 'BS+con', + params: [params.reps, params.brL, params.outGroup], + }, + { + title: 'Ancestral states', + value: 'AS', + needTree: true, + params: [params.tree], + }, + { + title: 'Pairwise distances', + value: 'PD', + params: [params.startingTree], + }, + { + title: 'RELL bootstraps', + value: 'RBS', + params: [], + }, +]; + +export const raxmlNgAnalysisOptions = [ + { + title: 'Sanity check', + value: 'SC', + params: [], + }, + { + title: 'Compression and conversion to binary format', + value: 'CC', + params: [], + }, + { + title: 'ML tree inference', + value: 'TI', + params: [params.runs, params.outGroup], + }, + { + title: 'ML + thorough bootstrap + consensus', + value: 'ML+tBS+con', + params: [params.runs, params.repsNg, params.outGroup], + }, + { + title: 'ML + transfer bootstrap expectation + consensus', + value: 'ML+TBE+con', + params: [params.runs, params.repsNg, params.outGroup], + }, + { + title: 'Ancestral state reconstruction', + value: 'AS', + needTree: true, + params: [params.tree], + }, +]; + +export class Binary extends Option { + constructor( run ) { + super( run, initialBinaryName, 'Binary', 'Name of binary' ); + makeObservable( this, { + version: computed, + type: computed, + } ); + } + options = binaries.map( ( { name } ) => ( { value: name, title: name } ) ); + get version() { + return binaries.filter( ( b ) => b.name === this.value )[0].version; + } + get type() { + return binaries.filter( ( b ) => b.name === this.value )[0].type; + } +} + +export class NumThreads extends Option { + constructor( run ) { + super( run, 2, 'Threads', 'Number of cpu threads' ); + makeObservable( this, { + notAvailable: computed, + } ); + } + options = range( 1, MAX_NUM_CPUS + 1 ).map( ( value ) => ( { + value, + title: value, + } ) ); + get notAvailable() { + return !( + /PTHREADS/.test( this.run.binary.value ) || this.run.usesModeltestNg + ); + } +} + +export class Analysis extends Option { + constructor( run ) { + super( run, 'ML+rBS', 'Analysis', 'Type of analysis' ); + } + options = analysisOptions.map( ( { value, title } ) => ( { value, title } ) ); +} + +export class RaxmlNgAnalysis extends Option { + constructor( run ) { + super( run, 'ML+TBE+con', 'Analysis', 'Type of analysis' ); + } + options = raxmlNgAnalysisOptions.map( ( { value, title } ) => ( { + value, + title, + } ) ); +} + +export class NumRuns extends Option { + constructor( run ) { + super( run, 1, 'Runs', 'Number of runs' ); + makeObservable( this, { + notAvailable: computed, + } ); + } + options = [1, 10, 20, 50, 100, 500].map( ( value ) => ( { value, title: value } ) ); + get notAvailable() { + return !this.run.analysisOption.params.includes( params.runs ); + } +} + +export class NumRepetitions extends Option { + constructor( run ) { + super( run, 100, 'Reps.', 'Number of repetitions' ); + makeObservable( this, { + notAvailable: computed, + } ); + } + options = [ + 100, + 200, + 500, + 1000, + 10000, + 'autoMR', + 'autoMRE', + 'autoMRE_IGN', + 'autoFC', + ].map( ( value ) => ( { value, title: value } ) ); + get notAvailable() { + return !this.run.analysisOption.params.includes( params.reps ); + } +} + +export class NumRepetitionsNg extends Option { + constructor( run ) { + super( run, 100, 'Reps.', 'Number of repetitions' ); + makeObservable( this, { + notAvailable: computed, + } ); + } + options = [100, 200, 500, 1000, 10000, 'autoMRE'].map( ( value ) => ( { + value, + title: value, + } ) ); + get notAvailable() { + return !this.run.analysisOption.params.includes( params.repsNg ); + } +} + +//TODO: Another branch lengths option for FT? ('compute brL' vs 'BS brL' for the rest) +export class BranchLength extends Option { + constructor( run ) { + super( + run, + false, + 'BS brL', + 'Compute branch lengths', + 'Optimize model parameters and branch lengths for the given input tree', + ); + makeObservable( this, { + notAvailable: computed, + } ); + } + get notAvailable() { + return !this.run.analysisOption.params.includes( params.brL ); + } +} + +export class SHlike extends Option { + constructor( run ) { + super( + run, + false, + 'SH-like', + 'Compute log-likelihood test', + 'Shimodaira-Hasegawa-like procedure', + ); + makeObservable( this, { + notAvailable: computed, + } ); + } + get notAvailable() { + return !this.run.analysisOption.params.includes( params.SHlike ); + } +} + +export class CombinedOutput extends Option { + constructor( run ) { + super( run, false, 'Combined output', 'Concatenate output trees' ); + makeObservable( this, { + notAvailable: computed, + isUsed: computed, + } ); + } + get notAvailable() { + return !this.run.analysisOption.params.includes( params.combinedOutput ); + } + get isUsed() { + return this.value && !this.notAvailable; + } +} + +export class StartingTree extends Option { + constructor( run ) { + super( run, 'Maximum parsimony', 'Starting tree', '' ); + makeObservable( this, { + notAvailable: computed, + } ); + } + options = ['Maximum parsimony', 'User defined'].map( ( value ) => ( { + value, + title: value, + } ) ); + get notAvailable() { + return !this.run.analysisOption.params.includes( params.startingTree ); + } +} + +export class OutGroup extends Option { + constructor( run ) { + super( run, [''], 'Outgroup', '' ); + makeObservable( this, { + options: computed, + setValue: override, + notAvailable: computed, + cmdValue: computed, + } ); + this.multiple = true; + } + get options() { + return ['', ...this.run.taxons].map( ( value ) => ( { + value, + title: value, + } ) ); + } + + setValue( value ) { + if ( this.value.includes( '' ) ) { + this.value = value.filter( ( v ) => v !== '' ); + return; + } + if ( !this.value.includes( '' ) && value.includes( '' ) ) { + this.value = value.filter( ( v ) => v === '' ); + return; + } + this.value = value; + } + + get notAvailable() { + return ( + !this.run.haveAlignments || + !this.run.analysisOption.params.includes( params.outGroup ) + ); + } + get cmdValue() { + return this.value.includes( '' ) + ? '' + : this.value.join( ',' ); + } +} + +export class SubstitutionMatrix extends Option { + constructor( run ) { + super( run, 'GTR', 'Substitution matrix' ); + makeObservable( this, { + options: computed, + notAvailable: computed, + cmdValue: computed, + extraCmdValue: computed, + notGTR: computed, + } ); + } + get options() { + if ( !this.run.haveAlignments ) { + return []; + } + const modelSettings = raxmlMatrixOptions[this.run.dataType]; + if ( !modelSettings ) { + return []; + } + return modelSettings.options.map( ( value ) => ( { + value, + title: value === 'GTR' + ? value + : `${value} + GAMMA`, + } ) ); + } + get notAvailable() { + return ( + !this.run.haveAlignments || + this.run.dataType === 'binary' || + this.run.dataType === 'protein' || + this.run.dataType === 'multistate' || + this.run.usesRaxmlNg + ); + } + get cmdValue() { + if ( this.run.dataType === 'binary' ) { + return 'BIN'; + } + if ( this.run.dataType === 'protein' ) { + return 'PROT'; + } + if ( this.run.dataType === 'multistate' ) { + return 'MULTI'; + } + if ( this.value === 'JC' || this.value === 'K80' || this.value === 'HKY' ) { + return 'GTR'; + } + return this.value; + } + get extraCmdValue() { + switch ( this.value ) { + case 'JC': + return '--JC69'; + case 'K80': + return '--K80'; + case 'HKY': + return '--HKY85'; + default: + return ''; + } + } + get notGTR() { + return this.value !== 'GTR'; + } +} + +export class SubstitutionRate extends Option { + constructor( run ) { + super( run, 'GAMMA', 'Substitution rates' ); + makeObservable( this, { + options: computed, + notAvailable: computed, + cmdValue: computed, + isCAT: computed, + } ); + } + get options() { + if ( !this.run.haveAlignments ) { + return []; + } + const modelSettings = raxmlRateOptions; + if ( !modelSettings ) { + return []; + } + return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); + } + get notAvailable() { + return ( + !this.run.haveAlignments || + ( ( this.run.dataType === 'dna' || + this.run.dataType === 'rna' || + this.run.dataType === 'nucleotide' ) && + this.run.substitutionMatrix.notGTR ) || + this.run.usesRaxmlNg + ); + } + get cmdValue() { + if ( this.run.substitutionMatrix.notGTR ) { + return 'GAMMA'; + } + return this.value; + } + get isCAT() { + return this.value === 'CAT'; + } +} + +export class SubstitutionI extends Option { + constructor( run ) { + super( run, 'none', 'Proportion of invariant sites' ); + makeObservable( this, { + options: computed, + notAvailable: computed, + cmdValue: computed, + isSet: computed, + } ); + } + get options() { + if ( !this.run.haveAlignments ) { + return []; + } + const modelSettings = raxmlIOptions; + if ( !modelSettings ) { + return []; + } + return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); + } + get notAvailable() { + return ( + this.run.substitutionAscertainment.isSet || + !this.run.haveAlignments || + this.run.usesRaxmlNg + ); + } + get cmdValue() { + return this.value === 'none' + ? '' + : 'I'; + } + get isSet() { + return this.value !== 'none'; + } +} + +export class SubstitutionAscertainment extends Option { + constructor( run ) { + super( run, 'none', 'Ascertainment bias correction' ); + makeObservable( this, { + options: computed, + notAvailable: computed, + cmdValue: computed, + extraCmdValue: computed, + isSet: computed, + } ); + } + get options() { + if ( !this.run.haveAlignments ) { + return []; + } + const modelSettings = raxmlAscertainmentOptions; + if ( !modelSettings ) { + return []; + } + return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); + } + get notAvailable() { + return ( + !this.run.haveAlignments || + this.run.usesRaxmlNg || + this.run.dataType === 'mixed' || + this.run.finalAlignment.hasInvariantSites || + this.run.substitutionI.isSet + ); + } + get cmdValue() { + return this.value === 'none' + ? '' + : 'ASC_'; + } + get extraCmdValue() { + switch ( this.value ) { + case "Lewis' method": + return '--asc-corr=lewis'; + case "Felsenstein's method": + return '--asc-corr=felsenstein'; + case "Stamatakis' method": + return '--asc-corr=stamatakis'; + default: + return ''; + } + } + get isSet() { + return this.value !== 'none'; + } +} + +export class AAMatrixName extends Option { + constructor( run ) { + super( + run, + 'BLOSUM62', + 'Matrix name', + 'Amino Acid Substitution Matrix name', + ); + makeObservable( this, { + notAvailable: computed, + } ); + } + options = raxmlSettings.aminoAcidSubstitutionMatrixOptions.options.map( + ( value ) => ( { value, title: value } ), + ); + get notAvailable() { + return this.run.dataType !== 'protein'; + } +} + +export class EstimatedFrequencies extends Option { + constructor( run ) { + super( + run, + false, + 'ML Freq.', + 'Estimated base frequencies', + 'Use estimated base frequencies instead of empirical.', + ); + makeObservable( this, { + notAvailable: computed, + } ); + } + get notAvailable() { + return this.run.dataType === 'protein' || this.run.usesRaxmlNg; + } +} + +export class BaseFrequencies extends Option { + constructor( run ) { + super( + run, + 'default', + 'Base frequencies', + 'Empirical, ML estimated or model based base frequencies', + ); + makeObservable( this, { + notAvailable: computed, + } ); + } + options = [ + { title: 'From model', value: 'default' }, + { title: 'Empirical', value: 'F' }, + { title: 'Estimated (ML)', value: 'X' }, + ]; + get notAvailable() { + return this.run.dataType !== 'protein' || this.run.usesRaxmlNg; + } +} + +export class MultistateModel extends Option { + constructor( run ) { + super( run, 'GTR', 'Multistate model' ); + makeObservable( this, { + notAvailable: computed, + } ); + } + options = raxmlSettings.kMultistateSubstitutionModelOptions.options.map( + ( value ) => ( { value, title: value } ), + ); + get notAvailable() { + return this.run.dataType !== 'multistate' || this.run.usesRaxmlNg; + } +} + +class TreeFile extends Option { + constructor( run ) { + super( run, '', 'Tree', '' ); + makeObservable( this, { + filePath: observable, + haveFile: computed, + filename: computed, + name: computed, + dir: computed, + setFilePath: action, + openFolder: action, + openFile: action, + remove: action, + } ); + } + filePath = ''; + get haveFile() { + return !!this.filePath; + } + get filename() { + return basename( this.filePath ); + } + get name() { + return name( this.filePath ); + } + get dir() { + return dir( this.filePath ); + } + setFilePath = ( filePath ) => { + this.filePath = filePath; + }; + openFolder = async () => { + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.showItemInFolder( this.filePath ); + }; + openFile = async () => { + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.openPath( this.filePath ); + }; + remove = () => { + this.setFilePath( '' ); + }; +} + +export class Tree extends TreeFile { + constructor( ...args ) { + super( ...args ); + makeObservable( this, { + notAvailable: computed, + } ); + } + get notAvailable() { + return !( + this.run.analysisOption.params.includes( params.tree ) || + ( !this.run.startingTree.notAvailable && + this.run.startingTree.value === 'User defined' ) + ); + } +} + +export class BackboneConstraintTree extends TreeFile { + constructor( ...args ) { + super( ...args ); + makeObservable( this, { + isSet: computed, + canConstraint: computed, + notAvailable: computed, + } ); + } + get isSet() { + return this.run.useBackboneConstraint && this.haveFile; + } + get canConstraint() { + const analysisWithConstraint = [ + 'ML', + 'ML+rBS', + 'ML+tBS', + 'BS+con', + 'RBS', + 'SC', + 'CC', + 'TI', + 'ML+tBS+con', + 'ML+TBE+con', + ]; + return analysisWithConstraint.includes( this.run.analysis.value ); + } + get notAvailable() { + return !this.run.useBackboneConstraint || !this.canConstraint; + } +} + +export class MultifurcatingConstraintTree extends TreeFile { + constructor( ...args ) { + super( ...args ); + makeObservable( this, { + isSet: computed, + canConstraint: computed, + notAvailable: computed, + } ); + } + get isSet() { + return this.run.useMultifurcatingConstraint && this.haveFile; + } + get canConstraint() { + const analysisWithConstraint = [ + 'ML', + 'ML+rBS', + 'ML+tBS', + 'BS+con', + 'RBS', + 'SC', + 'CC', + 'TI', + 'ML+tBS+con', + 'ML+TBE+con', + ]; + return analysisWithConstraint.includes( this.run.analysis.value ); + } + get notAvailable() { + return !this.run.useMultifurcatingConstraint || !this.canConstraint; + } +} diff --git a/src/app/store/RunSimpleOptions.test.js b/src/app/store/RunSimpleOptions.test.js new file mode 100644 index 00000000..8841e026 --- /dev/null +++ b/src/app/store/RunSimpleOptions.test.js @@ -0,0 +1,362 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; +import { binaries, MAX_NUM_CPUS } from './RunOptions'; + +const threaded = binaries.find( ( b ) => /PTHREADS/.test( b.name ) ); +const plain = binaries.find( ( b ) => b.type === 'raxml' && !/PTHREADS|-ng/.test( b.name ) ); + +// Run.analysis is a computed that builds a new option on each evaluation, so an +// unobserved run forgets a set analysis value. A kept-alive reaction models the page. +const stops = []; +afterEach( () => stops.splice( 0 ).forEach( ( stop ) => stop() ) ); + +// The initial binary is raxml-ng on some hosts; most tests start from classic RAxML. +const newRun = () => { + const run = new Run( null, 1 ); + stops.push( autorun( () => run.analysis ) ); + runInAction( () => { + run.binary.value = plain.name; + } ); + return run; +}; + +// Records every value an autorun sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +const set = ( option, value ) => runInAction( () => { + option.value = value; +} ); + +const setAnalysis = ( run, value ) => set( run.analysis, value ); + +const addAlignment = ( run, dataType ) => runInAction( () => { + run.alignments.push( { dataType, taxons: ['a', 'b'], partition: { isDefault: true } } ); +} ); + +describe( 'Binary', () => { + it( 'defaults to the initial binary and offers every binary', () => { + const run = new Run( null, 1 ); + expect( run.binary.value ).toBe( binaries.find( ( b ) => b.initial ).name ); + expect( run.binary.options.map( ( o ) => o.value ) ).toEqual( + binaries.map( ( b ) => b.name ), + ); + } ); + + it( 'derives version and type from the chosen binary and updates reactions', () => { + const run = newRun(); + const modeltest = binaries.find( ( b ) => b.type === 'modeltest' ); + const { seen, stop } = track( () => [run.binary.version, run.binary.type] ); + set( run.binary, modeltest.name ); + stop(); + expect( seen ).toEqual( [ + [plain.version, plain.type], + [modeltest.version, modeltest.type], + ] ); + } ); + + it( 'a reaction on the run command updates when the binary changes', () => { + const run = newRun(); + set( run.binary, plain.name ); + const { seen, stop } = track( () => run.command ); + set( run.binary, threaded.name ); + stop(); + expect( seen[0].startsWith( plain.name ) ).toBe( true ); + expect( seen[1].startsWith( threaded.name ) ).toBe( true ); + } ); +} ); + +describe( 'NumThreads', () => { + it( 'offers one to the number of cpus', () => { + const run = newRun(); + expect( run.numThreads.options.map( ( o ) => o.value ) ).toEqual( + Array.from( { length: MAX_NUM_CPUS }, ( _, i ) => i + 1 ), + ); + } ); + + it( 'is available with a PTHREADS binary and not otherwise', () => { + const run = newRun(); + const { seen, stop } = track( () => run.numThreads.notAvailable ); + set( run.binary, threaded.name ); + set( run.binary, plain.name ); + stop(); + expect( seen ).toEqual( [...seen.slice( 0, 1 ), false, true] ); + } ); + + it( 'is available with modeltest-ng', () => { + const run = newRun(); + set( run.binary, 'modeltest-ng' ); + expect( run.numThreads.notAvailable ).toBe( false ); + } ); + + it( 'a reaction on the run command updates when the thread count changes', () => { + const run = newRun(); + set( run.binary, threaded.name ); + setAnalysis( run, 'FT' ); + const { seen, stop } = track( () => run.command ); + set( run.numThreads, 4 ); + stop(); + expect( seen[0] ).toContain( '-T 2 ' ); + expect( seen[1] ).toContain( '-T 4 ' ); + } ); +} ); + +describe( 'Analysis and RaxmlNgAnalysis', () => { + it( 'uses the RAxML analysis list by default', () => { + const run = newRun(); + expect( run.usesRaxmlNg ).toBe( false ); + expect( run.analysis.value ).toBe( 'ML+rBS' ); + expect( run.analysis.options.map( ( o ) => o.value ) ).toEqual( + ['FT', 'ML', 'ML+rBS', 'ML+tBS', 'BS+con', 'AS', 'PD', 'RBS'], + ); + expect( run.analysisOption.title ).toBe( 'ML + rapid bootstrap' ); + } ); + + it( 'uses the RAxML-NG analysis list with a raxml-ng binary', () => { + const run = newRun(); + set( run.binary, 'raxml-ng' ); + expect( run.analysis.value ).toBe( 'ML+TBE+con' ); + expect( run.analysis.options.map( ( o ) => o.value ) ).toEqual( + ['SC', 'CC', 'TI', 'ML+tBS+con', 'ML+TBE+con', 'AS'], + ); + expect( run.analysisOption.title ).toBe( + 'ML + transfer bootstrap expectation + consensus', + ); + } ); + + it( 'a reaction on analysisOption updates when the analysis value changes', () => { + const run = newRun(); + const { seen, stop } = track( () => run.analysisOption.title ); + setAnalysis( run, 'FT' ); + stop(); + expect( seen ).toEqual( ['ML + rapid bootstrap', 'Fast tree search'] ); + } ); + + it( 'a reaction on analysisOption updates when the RAxML-NG analysis value changes', () => { + const run = newRun(); + set( run.binary, 'raxml-ng' ); + const { seen, stop } = track( () => run.analysisOption.title ); + setAnalysis( run, 'TI' ); + stop(); + expect( seen ).toEqual( [ + 'ML + transfer bootstrap expectation + consensus', + 'ML tree inference', + ] ); + } ); +} ); + +describe( 'analysis dependent availability', () => { + const cases = [ + // [option name, analyses that use it, analyses that do not] + ['numRuns', ['ML', 'ML+tBS'], ['FT', 'ML+rBS', 'RBS']], + ['numRepetitions', ['ML+rBS', 'ML+tBS', 'BS+con'], ['FT', 'ML', 'PD']], + ['branchLength', ['FT', 'ML+rBS', 'ML+tBS', 'BS+con'], ['ML', 'PD', 'AS']], + ['sHlike', ['FT', 'ML'], ['ML+rBS', 'RBS']], + ['combinedOutput', ['ML'], ['FT', 'ML+rBS']], + ['startingTree', ['PD'], ['FT', 'ML']], + ]; + + it.each( cases )( '%s is available only for its analyses', ( name, used, unused ) => { + const run = newRun(); + const { seen, stop } = track( () => run[name].notAvailable ); + used.forEach( ( value ) => { + setAnalysis( run, value ); + expect( run[name].notAvailable ).toBe( false ); + } ); + unused.forEach( ( value ) => { + setAnalysis( run, value ); + expect( run[name].notAvailable ).toBe( true ); + } ); + stop(); + expect( seen ).toContain( true ); + expect( seen ).toContain( false ); + } ); + + it( 'numRepetitionsNg is available for the bootstrap analyses of RAxML-NG', () => { + const run = newRun(); + set( run.binary, 'raxml-ng' ); + const { seen, stop } = track( () => run.numRepetitionsNg.notAvailable ); + setAnalysis( run, 'TI' ); + setAnalysis( run, 'ML+tBS+con' ); + stop(); + expect( seen ).toEqual( [false, true, false] ); + } ); + + it( 'numRuns is available for RAxML-NG tree inference', () => { + const run = newRun(); + set( run.binary, 'raxml-ng' ); + setAnalysis( run, 'TI' ); + expect( run.numRuns.notAvailable ).toBe( false ); + setAnalysis( run, 'SC' ); + expect( run.numRuns.notAvailable ).toBe( true ); + } ); +} ); + +describe( 'option lists', () => { + it( 'lists the values the run offers', () => { + const run = newRun(); + const values = ( option ) => option.options.map( ( o ) => o.value ); + expect( values( run.numRuns ) ).toEqual( [1, 10, 20, 50, 100, 500] ); + expect( values( run.numRepetitions ) ).toEqual( + [100, 200, 500, 1000, 10000, 'autoMR', 'autoMRE', 'autoMRE_IGN', 'autoFC'], + ); + expect( values( run.numRepetitionsNg ) ).toEqual( + [100, 200, 500, 1000, 10000, 'autoMRE'], + ); + expect( values( run.startingTree ) ).toEqual( ['Maximum parsimony', 'User defined'] ); + expect( values( run.baseFrequencies ) ).toEqual( ['default', 'F', 'X'] ); + expect( values( run.aaMatrixName ).length ).toBeGreaterThan( 0 ); + expect( values( run.multistateModel ).length ).toBeGreaterThan( 0 ); + } ); +} ); + +describe( 'CombinedOutput', () => { + it( 'is used only when checked and available', () => { + const run = newRun(); + setAnalysis( run, 'ML' ); + const { seen, stop } = track( () => run.combinedOutput.isUsed ); + set( run.combinedOutput, true ); + setAnalysis( run, 'FT' ); + stop(); + expect( seen.map( Boolean ) ).toEqual( [false, true, false] ); + } ); +} ); + +describe( 'option values reach the run command', () => { + it( 'branchLength and sHlike add their follow-up commands', () => { + const run = newRun(); + set( run.binary, plain.name ); + setAnalysis( run, 'FT' ); + const { seen, stop } = track( () => run.command ); + set( run.branchLength, true ); + set( run.sHlike, true ); + stop(); + const steps = ( command ) => command.split( ' &&\\\n' ).length; + expect( seen.map( steps ) ).toEqual( [1, 2, 3] ); + } ); + + it( 'numRuns and numRepetitions change the command', () => { + const run = newRun(); + set( run.binary, plain.name ); + setAnalysis( run, 'ML' ); + const runs = track( () => run.command ); + set( run.numRuns, 10 ); + runs.stop(); + expect( runs.seen[0] ).toContain( '-N 1 ' ); + expect( runs.seen[1] ).toContain( '-N 10 ' ); + + setAnalysis( run, 'ML+rBS' ); + const reps = track( () => run.command ); + set( run.numRepetitions, 200 ); + reps.stop(); + expect( reps.seen[0] ).toContain( '100' ); + expect( reps.seen[1] ).toContain( '200' ); + } ); + + it( 'numRepetitionsNg changes the RAxML-NG command', () => { + const run = newRun(); + set( run.binary, 'raxml-ng' ); + setAnalysis( run, 'ML+tBS+con' ); + const { seen, stop } = track( () => run.command ); + set( run.numRepetitionsNg, 500 ); + stop(); + expect( seen[0] ).toContain( '100' ); + expect( seen[1] ).toContain( '500' ); + } ); +} ); + +describe( 'data type options', () => { + it( 'AAMatrixName is available only for protein', () => { + const run = newRun(); + const { seen, stop } = track( () => run.aaMatrixName.notAvailable ); + addAlignment( run, 'protein' ); + stop(); + expect( seen ).toEqual( [true, false] ); + expect( run.aaMatrixName.value ).toBe( 'BLOSUM62' ); + } ); + + + it( 'EstimatedFrequencies is unavailable for protein and RAxML-NG', () => { + const run = newRun(); + set( run.binary, plain.name ); + const { seen, stop } = track( () => run.estimatedFrequencies.notAvailable ); + addAlignment( run, 'protein' ); + stop(); + expect( seen ).toEqual( [false, true] ); + const ng = newRun(); + set( ng.binary, 'raxml-ng' ); + expect( ng.estimatedFrequencies.notAvailable ).toBe( true ); + } ); + + it( 'BaseFrequencies is available only for protein with RAxML', () => { + const run = newRun(); + set( run.binary, plain.name ); + const { seen, stop } = track( () => run.baseFrequencies.notAvailable ); + addAlignment( run, 'protein' ); + set( run.binary, 'raxml-ng' ); + stop(); + expect( seen ).toEqual( [true, false, true] ); + } ); + + it( 'MultistateModel is available only for multistate with RAxML', () => { + const run = newRun(); + set( run.binary, plain.name ); + const { seen, stop } = track( () => run.multistateModel.notAvailable ); + addAlignment( run, 'multistate' ); + set( run.binary, 'raxml-ng' ); + stop(); + expect( seen ).toEqual( [true, false, true] ); + expect( run.multistateModel.value ).toBe( 'GTR' ); + } ); + + it( 'value changes of the data type options reach reactions', () => { + const run = newRun(); + set( run.binary, plain.name ); + addAlignment( run, 'multistate' ); + setAnalysis( run, 'FT' ); + const { seen, stop } = track( () => run.command ); + set( run.multistateModel, 'ORDERED' ); + stop(); + expect( seen[0] ).toContain( '-K GTR' ); + expect( seen[1] ).toContain( '-K ORDERED' ); + } ); + + it( 'EstimatedFrequencies adds X to the model for nucleotide data', () => { + const run = newRun(); + addAlignment( run, 'nucleotide' ); + const { seen, stop } = track( () => run.raxmlSubstitutionModelCmd ); + set( run.estimatedFrequencies, true ); + stop(); + expect( seen[1] ).toBe( `${seen[0]}X` ); + } ); + + it( 'BaseFrequencies adds its suffix to the model for protein data', () => { + const run = newRun(); + addAlignment( run, 'protein' ); + const { seen, stop } = track( () => run.raxmlSubstitutionModelCmd ); + set( run.baseFrequencies, 'F' ); + set( run.baseFrequencies, 'default' ); + stop(); + expect( seen[1] ).toBe( `${seen[0]}F` ); + expect( seen[2] ).toBe( seen[0] ); + } ); + + // No page store computed reads these two values, so the reaction reads them itself. + it( 'a reaction on StartingTree and AAMatrixName values updates when they are set', () => { + const run = newRun(); + const { seen, stop } = track( () => [run.startingTree.value, run.aaMatrixName.value] ); + set( run.startingTree, 'User defined' ); + set( run.aaMatrixName, 'WAG' ); + stop(); + expect( seen ).toEqual( [ + ['Maximum parsimony', 'BLOSUM62'], + ['User defined', 'BLOSUM62'], + ['User defined', 'WAG'], + ] ); + } ); +} ); diff --git a/src/app/store/StoreBase.js b/src/app/store/StoreBase.js index b2054448..8efd2ac6 100644 --- a/src/app/store/StoreBase.js +++ b/src/app/store/StoreBase.js @@ -1,3 +1,5 @@ +import { runInAction } from 'mobx'; + export const runEvents = { onRunStdout: 'onRunStdout', onRunStderr: 'onRunStderr', @@ -33,14 +35,17 @@ export default class StoreBase { } }; - dispose = () => { + // A method: a field here would clash with a subclass's dispose field. + dispose() { this.unlisten(); - }; + } _init = () => { const { rendererBridge } = /** @type {any} */ ( window ); rendererBridge.getVersion().then( ( version ) => { - this.version = version; + runInAction( () => { + this.version = version; + } ); } ); }; } diff --git a/src/app/store/alignmentStore.test.js b/src/app/store/alignmentStore.test.js new file mode 100644 index 00000000..bd97d9fa --- /dev/null +++ b/src/app/store/alignmentStore.test.js @@ -0,0 +1,570 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { runInAction } from 'mobx'; + +import { stubBridge as sharedStubBridge, track } from '../../../jest/storeBridge'; + +import Run from './Run'; +import { runEvents } from './StoreBase'; + +let bridge; +let listeners; +let fire; + +// Alignment construction subscribes to bridge events and parses. +function stubBridge( extra = {} ) { + ( { bridge, listeners, fire } = sharedStubBridge( { + parseAlignment: () => new Promise( () => {} ), + startModelSelection: jest.fn( async () => {} ), + cancelModelSelection: jest.fn(), + ...extra, + } ) ); +} + +function setup( { onError = () => {}, path = '/data/primates.fasta' } = {} ) { + const run = new Run( { onError }, 7 ); + run.addAlignments( [{ path }] ); + return { run, alignment: run.alignments[0] }; +} + +function set( object, values ) { + runInAction( () => Object.assign( object, values ) ); +} + +const parsed = { + sequences: [ + { taxon: 'Homo', code: 'ACGT' }, + { taxon: 'Mus', code: 'ACGA' }, + ], + fileFormat: 'fasta', + numSequences: 2, + length: 4, + dataType: 'dna', + hasInvariantSites: true, + typecheckingComplete: true, +}; + +beforeEach( () => stubBridge() ); + +describe( 'Alignment observable fields update the page store', () => { + it( 'path updates id, name, dir, base, filename and ok', () => { + const { alignment } = setup(); + const { seen, stop } = track( () => [ + alignment.id, + alignment.name, + alignment.dir, + alignment.base, + alignment.filename, + alignment.ok, + ] ); + set( alignment, { path: '/other/apes.fasta' } ); + expect( seen[seen.length - 1][0] ).toBe( '7_/other/apes.fasta' ); + expect( seen.length ).toBe( 2 ); + expect( alignment.ok ).toBe( true ); + set( alignment, { path: '' } ); + expect( alignment.ok ).toBe( false ); + stop(); + } ); + + it( 'error, parsingComplete, typecheckingComplete and checkRunComplete drive status', () => { + const { alignment } = setup(); + const { seen, stop } = track( () => alignment.status ); + set( alignment, { parsingComplete: true } ); + set( alignment, { typecheckingComplete: true } ); + set( alignment, { checkRunComplete: true } ); + set( alignment, { error: 'bad file' } ); + expect( seen ).toEqual( [ + 'Parsing...', + 'Type checking...', + 'Check run with RAxML...', + 'ok', + 'Error: bad file', + ] ); + stop(); + } ); + + it( 'sequences update taxons and the run taxons', () => { + const { run, alignment } = setup(); + const { seen, stop } = track( () => run.taxons ); + expect( alignment.taxons ).toEqual( [] ); + set( alignment, { sequences: parsed.sequences } ); + expect( alignment.taxons ).toEqual( ['Homo', 'Mus'] ); + expect( seen ).toEqual( [[], ['Homo', 'Mus']] ); + stop(); + } ); + + it( 'length updates numSites and getSequenceCode padding', () => { + const { alignment } = setup(); + const { seen, stop } = track( () => alignment.numSites ); + set( alignment, { sequences: parsed.sequences, length: 4 } ); + expect( seen ).toEqual( [0, 4] ); + expect( alignment.getSequenceCode( 'Homo' ) ).toBe( 'ACGT' ); + expect( alignment.getSequenceCode( 'Missing' ) ).toBe( '----' ); + stop(); + } ); + + it( 'dataType updates partitionType, modelTestCanRun and modelExtra', () => { + const { run, alignment } = setup(); + runInAction( () => { + run.binary.value = 'raxml-ng'; + } ); + runInAction( () => { + run.binary.value = run.binary.options.find( + ( { value } ) => !value.includes( 'raxml-ng' ), + ).value; + } ); + expect( run.usesRaxmlNg ).toBe( false ); + const { seen, stop } = track( () => [ + alignment.partitionType, + alignment.modelTestCanRun, + alignment.modelExtra && alignment.modelExtra.value, + ] ); + const types = { + dna: ['DNA', false, null], + nucleotide: ['DNA', true, null], + protein: ['BLOSUM62', true, 'BLOSUM62'], + binary: ['BIN', false, null], + multistate: ['MULTI', false, null], + mixed: ['mixed', false, null], + }; + for ( const [dataType, expected] of Object.entries( types ) ) { + set( alignment, { dataType } ); + expect( seen[seen.length - 1] ).toEqual( expected ); + } + stop(); + } ); + + it( 'aaMatrixName updates partitionType and modelExtra, and onChangeAAMatrixName sets it', () => { + const { run, alignment } = setup(); + set( run.binary, { + value: run.binary.options.find( ( { value } ) => !value.includes( 'raxml-ng' ) ).value, + } ); + set( alignment, { dataType: 'protein' } ); + const { seen, stop } = track( () => [ + alignment.partitionType, + alignment.modelExtra?.value, + ] ); + alignment.modelExtra.onChange( 'WAG' ); + expect( alignment.aaMatrixName ).toBe( 'WAG' ); + expect( seen[seen.length - 1] ).toEqual( ['WAG', 'WAG'] ); + stop(); + } ); + + it( 'modelExtra is null for protein with raxml-ng', () => { + const { run, alignment } = setup(); + set( alignment, { dataType: 'protein' } ); + const ng = run.binary.options.find( ( { value } ) => value.includes( 'raxml-ng' ) ); + const old = run.binary.options.find( ( { value } ) => !value.includes( 'raxml-ng' ) ); + set( run.binary, { value: old.value } ); + const { seen, stop } = track( () => alignment.modelExtra?.value ); + set( run.binary, { value: ng.value } ); + expect( run.usesRaxmlNg ).toBe( true ); + expect( seen ).toEqual( ['BLOSUM62', undefined] ); + stop(); + } ); + + it( 'partitionText and the partition flag update showPartition', () => { + const { run, alignment } = setup(); + const { seen, stop } = track( () => alignment.showPartition ); + alignment.setShowPartition(); + expect( run.showPartitionFor ).toBe( alignment ); + alignment.hidePartition(); + alignment.setShowPartition( true ); + alignment.setShowPartition( false ); + expect( seen ).toEqual( [false, true, false, true, false] ); + alignment.setPartitionText( 'DNA, a = 1-4' ); + expect( alignment.partitionText ).toBe( 'DNA, a = 1-4' ); + stop(); + } ); + + it( 'dataType, length and aaMatrixName update partitionFileContent', () => { + const { run, alignment } = setup(); + set( alignment, { dataType: 'nucleotide', length: 10 } ); + const ng = run.binary.options.find( ( { value } ) => value.includes( 'raxml-ng' ) ); + const old = run.binary.options.find( ( { value } ) => !value.includes( 'raxml-ng' ) ); + set( run.binary, { value: old.value } ); + const { seen, stop } = track( () => alignment.partitionFileContent ); + set( alignment, { length: 12 } ); + set( alignment, { dataType: 'protein' } ); + set( alignment, { aaMatrixName: 'JTT' } ); + expect( seen ).toEqual( [ + 'DNA, nucleotide_0 = 1-10\n', + 'DNA, nucleotide_0 = 1-12\n', + 'BLOSUM62, protein_0 = 1-12\n', + 'JTT, protein_0 = 1-12\n', + ] ); + set( run.binary, { value: ng.value } ); + expect( alignment.partitionFileContent ).toBe( + `${alignment.ngSubstitutionModelCmd}, protein_0 = 1-12\n`, + ); + stop(); + } ); + + it( 'the model options update ngSubstitutionModelCmd', () => { + const { alignment } = setup(); + set( alignment, { dataType: 'nucleotide' } ); + alignment.substitutionModel.setValue( 'GTR' ); + const { seen, stop } = track( () => alignment.ngSubstitutionModelCmd ); + alignment.ngStationaryFrequencies.setValue( '+FO' ); + alignment.ngInvariantSites.setValue( '+I' ); + alignment.ngRateHeterogeneity.setValue( '+G' ); + alignment.ngAscertainmentBias.setValue( '+ASC_LEWIS' ); + expect( seen ).toEqual( [ + 'GTR', + 'GTR+FO', + 'GTR+FO+I', + 'GTR+FO+I+G', + 'GTR+FO+I+G+ASC_LEWIS', + ] ); + stop(); + } ); + + it( 'multistateNumber updates the multistate model command', () => { + const { alignment } = setup(); + set( alignment, { dataType: 'multistate' } ); + alignment.substitutionModel.setValue( 'MULTIx_GTR' ); + const { seen, stop } = track( () => alignment.ngSubstitutionModelCmd ); + alignment.multistateNumber.setValue( 5 ); + expect( seen[0] ).toContain( 'MULTI' ); + expect( seen[seen.length - 1] ).toBe( alignment.substitutionModel.value.replace( 'x', '5' ) + '' ); + stop(); + } ); + + it( 'hasInvariantSites updates ascertainment bias availability', () => { + const { run, alignment } = setup(); + const ng = run.binary.options.find( ( { value } ) => value.includes( 'raxml-ng' ) ); + set( run.binary, { value: ng.value } ); + const { seen, stop } = track( () => alignment.ngAscertainmentBias.notAvailable ); + set( alignment, { hasInvariantSites: true } ); + expect( seen ).toEqual( [false, true] ); + stop(); + } ); + + it( 'modified fields update the run converted and modified flags', () => { + const { run, alignment } = setup(); + const { seen, stop } = track( () => [run.converted, run.modified] ); + set( alignment, { converted: true } ); + set( alignment, { modified: true } ); + const last = seen[seen.length - 1]; + expect( last ).toEqual( [true, true] ); + expect( seen.length ).toBeGreaterThanOrEqual( 3 ); + stop(); + } ); + + it( 'the dialog and snack flags are set and cleared by clearModified', () => { + const { alignment } = setup(); + const { seen, stop } = track( () => [alignment.showModifiedSnack, alignment.showModifiedDialog] ); + set( alignment, { showModifiedSnack: true, showModifiedDialog: true } ); + alignment.clearModified(); + expect( seen ).toEqual( [[false, false], [true, true], [false, false]] ); + stop(); + } ); + + it( 'dataType updates the final alignment data type of the run', () => { + const { run, alignment } = setup(); + const { seen, stop } = track( () => run.dataType ); + set( alignment, { dataType: 'protein' } ); + expect( run.dataType ).toBe( 'protein' ); + expect( seen[0] ).not.toBe( 'protein' ); + expect( seen[seen.length - 1] ).toBe( 'protein' ); + stop(); + } ); + + it( 'the remaining observable fields can be set and read back', () => { + const { alignment } = setup(); + const values = { + size: 1, + fileFormat: 'fasta', + convertedFrom: 'nexus', + modificationMessages: ['a'], + numSequences: 3, + checkRunData: 'out', + checkRunSuccess: true, + loading: true, + modeltestLoading: true, + partitionText: 'x', + }; + const { seen, stop } = track( () => JSON.stringify( Object.keys( values ).map( ( k ) => alignment[k] ) ) ); + set( alignment, values ); + for ( const [key, value] of Object.entries( values ) ) { + expect( alignment[key] ).toEqual( value ); + } + expect( seen.length ).toBe( 2 ); + stop(); + } ); +} ); + +describe( 'Alignment onChangeModel', () => { + it( 'sets model from the event target', () => { + const { alignment } = setup(); + alignment.onChangeModel( { target: { value: 'GTR' } } ); + expect( alignment.model ).toBe( 'GTR' ); + } ); +} ); + +describe( 'Alignment stdout and stderr', () => { + it( 'appends content for its own id only', () => { + const { run, alignment } = setup(); + const { seen, stop } = track( () => [run.stdout, run.stderr] ); + fire( runEvents.onRunStdout, { id: 'other', content: 'no' } ); + fire( runEvents.onRunStdout, { id: alignment.id, content: 'a' } ); + fire( runEvents.onRunStdout, { id: alignment.id, content: 'b' } ); + fire( runEvents.onRunStderr, { id: alignment.id, content: 'e' } ); + expect( run.stdout ).toBe( 'ab' ); + expect( run.stderr ).toBe( 'e' ); + expect( seen[seen.length - 1] ).toEqual( ['ab', 'e'] ); + stop(); + } ); +} ); + +describe( 'Alignment constructor', () => { + it( 'builds the option objects and the partition', () => { + const { alignment } = setup(); + expect( alignment.substitutionModel.run ).toBe( alignment.run ); + expect( alignment.multistateNumber ).toBeDefined(); + expect( alignment.partition ).toBeDefined(); + expect( typeof alignment.modeltestDisabled ).toBe( 'boolean' ); + } ); + + it( 'disables modeltest on Windows 7', () => { + window.rendererBridge = { ...bridge, host: { ...bridge.host, windows: true, release: '6.1.7601' } }; + jest.isolateModules( () => { + const IsolatedRun = require( './Run' ).default; + const run = new IsolatedRun( {}, 1 ); + run.addAlignments( [{ path: '/a.fasta' }] ); + expect( run.alignments[0].modeltestDisabled ).toBe( true ); + } ); + } ); +} ); + +describe( 'Alignment loadParsedAlignment', () => { + async function load( parse, run ) { + let pending; + stubBridge( { + parseAlignment: ( ...args ) => { + pending = parse( ...args ); + return pending; + }, + } ); + const result = setup(); + await pending.catch( () => {} ); + return result; + } + + it( 'writes the parsed fields', async () => { + const parseAlignment = jest.fn( async () => ( { alignment: parsed, change: null } ) ); + const { alignment } = await load( parseAlignment ); + expect( parseAlignment ).toHaveBeenCalledWith( '7_/data/primates.fasta', '/data/primates.fasta' ); + expect( alignment.sequences ).toEqual( parsed.sequences ); + expect( alignment.numSequences ).toBe( 2 ); + expect( alignment.parsingComplete ).toBe( true ); + expect( alignment.loading ).toBe( false ); + expect( alignment.status ).toBe( 'Check run with RAxML...' ); + } ); + + it( 'writes the substitution model default and the substitution matrix default', async () => { + const { run, alignment } = await load( async () => ( { + alignment: { ...parsed, dataType: 'protein' }, + change: null, + } ) ); + expect( alignment.substitutionModel.value ).toBe( 'Blosum62' ); + expect( run.substitutionMatrix.value ).toBe( 'BLOSUM62' ); + } ); + + it( 'keeps the substitution matrix when the run data type is unchanged', async () => { + const { run, alignment } = await load( async () => ( { + alignment: { ...parsed, dataType: 'dna' }, + change: null, + } ) ); + expect( run.substitutionMatrix.value ).toBe( 'GTR' ); + expect( alignment.substitutionModel.value ).toBe( 'GTR' ); + } ); + + it( 'a modification with messages shows the dialog', async () => { + const { alignment } = await load( async () => ( { + alignment: parsed, + change: { + newFilePath: '/data/primates_modified.fas', + format: 'nexus', + converted: true, + modified: true, + modificationMessages: ['fixed a name'], + }, + } ) ); + expect( alignment.path ).toBe( '/data/primates_modified.fas' ); + expect( alignment.convertedFrom ).toBe( 'nexus' ); + expect( alignment.converted ).toBe( true ); + expect( alignment.modified ).toBe( true ); + expect( alignment.showModifiedDialog ).toBe( true ); + expect( alignment.showModifiedSnack ).toBe( false ); + } ); + + it( 'a conversion without messages shows the snack', async () => { + const { alignment } = await load( async () => ( { + alignment: parsed, + change: { + newFilePath: '/data/primates.fas', + format: 'nexus', + converted: true, + modified: false, + modificationMessages: [], + }, + } ) ); + expect( alignment.showModifiedSnack ).toBe( true ); + expect( alignment.showModifiedDialog ).toBe( false ); + } ); + + it( 'a failed parse sets the error, removes the alignment and stops listening', async () => { + const error = new Error( 'unrecognized format' ); + const { run, alignment } = await load( async () => { + throw error; + } ); + expect( alignment.error ).toBe( error ); + expect( alignment.loading ).toBe( false ); + expect( run.error ).toBe( error ); + expect( run.alignments ).toEqual( [] ); + expect( listeners[runEvents.onModelSelectionSuccess] ).toEqual( [] ); + } ); +} ); + +describe( 'Alignment model selection', () => { + it( 'runModelTest reports an error for fewer than three sequences', async () => { + const onError = jest.fn(); + const { alignment } = setup( { onError } ); + set( alignment, { numSequences: 2 } ); + await alignment.runModelTest(); + expect( onError ).toHaveBeenCalledTimes( 1 ); + expect( onError.mock.calls[0][0].message ).toBe( + 'ModelTest can only be run on alignments with more than two sequences.', + ); + expect( alignment.modeltestLoading ).toBe( false ); + expect( bridge.startModelSelection ).not.toHaveBeenCalled(); + } ); + + it( 'start sets loading and calls the bridge', async () => { + const { run, alignment } = setup(); + run.setOutputDir( '/out' ); + set( alignment, { numSequences: 4, dataType: 'nucleotide' } ); + const { seen, stop } = track( () => alignment.modeltestLoading ); + await alignment.runModelTest(); + expect( seen ).toEqual( [false, true] ); + expect( bridge.startModelSelection ).toHaveBeenCalledWith( { + id: '7_/data/primates.fasta', + filePath: '/data/primates.fasta', + outputDir: '/out', + dataType: 'nucleotide', + numThreads: run.numThreads.value, + binaryName: run.modeltestName, + } ); + stop(); + } ); + + it( 'cancel clears loading and calls the bridge only while loading', () => { + const { alignment } = setup(); + alignment.cancelModelTest(); + expect( bridge.cancelModelSelection ).not.toHaveBeenCalled(); + set( alignment, { modeltestLoading: true } ); + alignment.cancelModelTest(); + expect( alignment.modeltestLoading ).toBe( false ); + expect( bridge.cancelModelSelection ).toHaveBeenCalledWith( alignment.id ); + } ); + + it( 'success for its own id sets the model and ends the run', () => { + const { run, alignment } = setup(); + set( alignment, { modeltestLoading: true } ); + set( run, { running: true } ); + const result = { raxml: 'GTRGAMMA', extraFlag: '--HKY85', raxmlNG: 'HKY+G' }; + fire( runEvents.onModelSelectionSuccess, { id: 'other', result } ); + expect( alignment.modeltestLoading ).toBe( true ); + expect( run.running ).toBe( true ); + fire( runEvents.onModelSelectionSuccess, { id: alignment.id, result } ); + expect( alignment.modeltestLoading ).toBe( false ); + expect( alignment.substitutionModel.value ).toBe( 'HKY' ); + expect( alignment.ngRateHeterogeneity.value ).toBe( '+G' ); + expect( run.substitutionMatrix.value ).toBe( 'HKY' ); + expect( run.substitutionRate.value ).toBe( 'GAMMA' ); + expect( run.running ).toBe( false ); + } ); + + it( 'failure for its own id sets the run error and ends the run', () => { + const { run, alignment } = setup(); + set( alignment, { modeltestLoading: true } ); + set( run, { running: true } ); + fire( runEvents.onModelSelectionFailure, { id: 'other', error: 'x' } ); + expect( run.error ).toBe( null ); + fire( runEvents.onModelSelectionFailure, { id: alignment.id, error: 'missing binary' } ); + expect( run.error ).toBe( 'missing binary' ); + expect( alignment.modeltestLoading ).toBe( false ); + expect( run.running ).toBe( false ); + } ); + + it( 'dispose stops listening and cancels a running model selection', () => { + const { alignment } = setup(); + set( alignment, { modeltestLoading: true } ); + const before = listeners[runEvents.onModelSelectionSuccess].length; + alignment.dispose(); + expect( bridge.cancelModelSelection ).toHaveBeenCalledWith( alignment.id ); + expect( listeners[runEvents.onModelSelectionSuccess].length ).toBe( before - 1 ); + } ); + + it( 'remove disposes and removes the alignment from the run', () => { + const { run, alignment } = setup(); + alignment.remove(); + expect( run.alignments ).toEqual( [] ); + } ); +} ); + +describe( 'Alignment setModelFromString', () => { + function apply( result, dataType = 'nucleotide' ) { + const { run, alignment } = setup(); + set( alignment, { dataType, modeltestLoading: true } ); + alignment.setModelFromString( result ); + return { run, alignment }; + } + + it( 'maps renamed models and the ng parameters', () => { + const { alignment } = apply( { raxml: 'GTRGAMMAIF', extraFlag: '', raxmlNG: 'TrN+FO+IC+GA+ASC_LEWIS' } ); + expect( alignment.modeltestLoading ).toBe( false ); + expect( alignment.substitutionModel.value ).toBe( 'TN93' ); + expect( alignment.ngStationaryFrequencies.value ).toBe( '+FO' ); + expect( alignment.ngInvariantSites.value ).toBe( '+IC' ); + expect( alignment.ngRateHeterogeneity.value ).toBe( '+GA' ); + expect( alignment.ngAscertainmentBias.value ).toBe( '+ASC_LEWIS' ); + } ); + + it( 'maps TPM1 to K81', () => { + const { alignment } = apply( { raxml: 'GTRGAMMA', extraFlag: '', raxmlNG: 'TPM1' } ); + expect( alignment.substitutionModel.value ).toBe( 'K81' ); + } ); + + it( 'reads the raxml flags F, X, invariant sites and rate', () => { + const f = apply( { raxml: 'GTRGAMMAIF', extraFlag: '', raxmlNG: 'GTR' } ); + expect( f.run.baseFrequencies.value ).toBe( 'F' ); + expect( f.run.substitutionI.value ).toBe( '+I (ML estimate)' ); + expect( f.run.substitutionRate.value ).toBe( 'GAMMA' ); + expect( f.run.substitutionAscertainment.value ).toBe( 'none' ); + + const x = apply( { raxml: 'GTRCATX', extraFlag: '', raxmlNG: 'GTR' } ); + expect( x.run.estimatedFrequencies.value ).toBe( true ); + expect( x.run.baseFrequencies.value ).toBe( 'X' ); + expect( x.run.substitutionRate.value ).toBe( 'CAT' ); + expect( x.run.substitutionI.value ).toBe( 'none' ); + + const d = apply( { raxml: 'GTRGAMMA', extraFlag: '', raxmlNG: 'GTR' } ); + expect( d.run.baseFrequencies.value ).toBe( 'default' ); + } ); + + it( 'maps the extra flags to the substitution matrix', () => { + const jc = apply( { raxml: 'GTRCAT', extraFlag: '--JC69', raxmlNG: 'JC' } ); + expect( jc.run.substitutionMatrix.value ).toBe( 'JC' ); + expect( jc.run.substitutionRate.value ).toBe( 'GAMMA' ); + const k80 = apply( { raxml: 'GTRCAT', extraFlag: '--K80', raxmlNG: 'K80' } ); + expect( k80.run.substitutionMatrix.value ).toBe( 'K80' ); + const hky = apply( { raxml: 'GTRCAT', extraFlag: '--HKY85', raxmlNG: 'HKY' } ); + expect( hky.run.substitutionMatrix.value ).toBe( 'HKY' ); + } ); + + it( 'parses the amino acid matrix for protein', () => { + const { alignment } = apply( { raxml: 'PROTGAMMAWAGF', extraFlag: '', raxmlNG: 'WAG+FO' }, 'protein' ); + expect( alignment.aaMatrixName ).toBe( 'WAG' ); + } ); +} ); diff --git a/src/app/store/checkOutputName.test.js b/src/app/store/checkOutputName.test.js index 2d6327a8..bc7ba708 100644 --- a/src/app/store/checkOutputName.test.js +++ b/src/app/store/checkOutputName.test.js @@ -19,7 +19,7 @@ it( 'the output-name check uses checkOutput', async () => { let seen; await when( () => { const value = run.outputNameAvailable.get(); - if ( run.outputNameAvailable.busy || value.outputNameUnused !== 'tree_1' ) { + if ( value.outputNameUnused !== 'tree_1' ) { return false; } seen = { diff --git a/src/app/store/citationConfig.test.js b/src/app/store/citationConfig.test.js new file mode 100644 index 00000000..6ebd4380 --- /dev/null +++ b/src/app/store/citationConfig.test.js @@ -0,0 +1,175 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { reaction, runInAction } from 'mobx'; + +import AppStore from './AppStore'; + +let listeners; +let bridge; + +beforeEach( () => { + listeners = {}; + const subscribe = ( key ) => jest.fn( ( listener ) => { + listeners[key] = listener; + return () => { + delete listeners[key]; + }; + } ); + bridge = { + getVersion: jest.fn( async () => '2.0.0' ), + getDarkMode: jest.fn( async () => false ), + setDarkMode: jest.fn( async () => {} ), + copyText: jest.fn( async () => {} ), + onLightMode: subscribe( 'light' ), + onDarkMode: subscribe( 'dark' ), + }; + window.rendererBridge = bridge; +} ); + +async function settle() { + await Promise.all( bridge.getDarkMode.mock.results.map( ( r ) => r.value ) ); +} + +function track( expression ) { + const seen = []; + const stop = reaction( expression, ( value ) => seen.push( value ) ); + return { seen, stop }; +} + +describe( 'citation', () => { + it( 'offers plain text, RIS and BibTeX, plain text first', () => { + const { citation } = new AppStore(); + expect( citation.formats.map( ( f ) => f.value ) ).toEqual( ['txt', 'ris', 'bib'] ); + expect( citation.format ).toBe( 'txt' ); + } ); + + it( 'plain text format text', () => { + const { citation } = new AppStore(); + const lines = citation.allText.split( '\n' ); + expect( lines ).toHaveLength( 4 ); + expect( lines[0] ).toBe( 'Edler, D, Klein, J, Antonelli, A, Silvestro, D. raxmlGUI 2.0: A graphical interface and toolkit for phylogenetic analyses using RAxML. Methods Ecol Evol. 2021; 12: 373– 377. https://doi.org/10.1111/2041-210X.13512' ); + expect( lines[1] ).toMatch( /^Alexandros Stamatakis, RAxML version 8: .*btu033$/ ); + expect( lines[2] ).toMatch( /^Alexey M Kozlov, .*RAxML-NG: .*btz305$/ ); + expect( lines[3] ).toMatch( /^Diego Darriba, .*ModelTest-NG: .*msz189$/ ); + } ); + + it( 'RIS format text', () => { + const { citation } = new AppStore(); + citation.setFormat( 'ris' ); + const text = citation.allText; + expect( text.match( /^TY {2}- JOUR$/gm ) ).toHaveLength( 4 ); + expect( text.match( /^ER {2}- ?$/gm ) ).toHaveLength( 4 ); + expect( text.startsWith( '\nTY - JOUR\nT1 - raxmlGUI 2.0:' ) ).toBe( true ); + for ( const doi of ['10.1111/2041-210X.13512', '10.1093/bioinformatics/btu033', '10.1093/bioinformatics/btz305', '10.1093/molbev/msz189'] ) { + expect( text ).toContain( `UR - https://doi.org/${doi}` ); + } + expect( text ).not.toContain( '@article' ); + } ); + + it( 'BibTeX format text', () => { + const { citation } = new AppStore(); + citation.setFormat( 'bib' ); + const text = citation.allText; + expect( text.match( /@article\{/g ) ).toHaveLength( 4 ); + expect( text.startsWith( '@article{https://doi.org/10.1111/2041-210X.13512,\nauthor = {Edler, Daniel' ) ).toBe( true ); + expect( text ).toContain( '@article{10.1093/bioinformatics/btu033,' ); + expect( text ).toContain( '@article{10.1093/bioinformatics/btz305,' ); + expect( text.endsWith( 'eprint = {https://academic.oup.com/mbe/article-pdf/37/1/291/32085561/msz189.pdf},\n}' ) ).toBe( true ); + expect( text ).not.toContain( 'TY - JOUR' ); + } ); + + it( 'allText follows format, set by action or directly', () => { + const { citation } = new AppStore(); + const { seen, stop } = track( () => citation.allText ); + + citation.setFormat( 'bib' ); + runInAction( () => { + citation.format = 'ris'; + } ); + stop(); + + expect( seen ).toHaveLength( 2 ); + expect( seen[0] ).toContain( '@article{' ); + expect( seen[1] ).toContain( 'TY - JOUR' ); + } ); + + it( 'show and hide switch visibility, and a reaction sees it', () => { + const { citation } = new AppStore(); + expect( citation.visible ).toBe( false ); + const { seen, stop } = track( () => citation.visible ); + + citation.show(); + expect( citation.visible ).toBe( true ); + citation.hide(); + expect( citation.visible ).toBe( false ); + runInAction( () => { + citation.visible = true; + } ); + stop(); + + expect( seen ).toEqual( [true, false, true] ); + } ); + + it( 'copyToClipboard copies the text in the current format', async () => { + jest.spyOn( console, 'log' ).mockImplementation( () => {} ); + const { citation } = new AppStore(); + citation.setFormat( 'bib' ); + await citation.copyToClipboard(); + expect( bridge.copyText ).toHaveBeenCalledWith( citation.allText ); + expect( bridge.copyText.mock.calls[0][0] ).toContain( '@article{' ); + } ); +} ); + +describe( 'config dark mode', () => { + it( 'starts light and loads dark mode from the renderer bridge', async () => { + bridge.getDarkMode.mockImplementation( async () => 1 ); + const { config } = new AppStore(); + expect( config.isDarkMode ).toBe( false ); + await settle(); + expect( config.isDarkMode ).toBe( true ); + } ); + + it( 'a falsy loaded value stays light', async () => { + bridge.getDarkMode.mockImplementation( async () => undefined ); + const { config } = new AppStore(); + await settle(); + expect( config.isDarkMode ).toBe( false ); + } ); + + it( 'setDarkMode switches the theme and tells the bridge, as a boolean', async () => { + const { config } = new AppStore(); + await settle(); + const { seen, stop } = track( () => config.isDarkMode ); + + config.setDarkMode( 'yes' ); + expect( config.isDarkMode ).toBe( true ); + config.setDarkMode( 0 ); + expect( config.isDarkMode ).toBe( false ); + runInAction( () => { + config.isDarkMode = true; + } ); + stop(); + + expect( seen ).toEqual( [true, false, true] ); + expect( bridge.setDarkMode.mock.calls ).toEqual( [[true], [false]] ); + } ); + + it( 'dark and light menu events switch the theme', async () => { + const { config } = new AppStore(); + await settle(); + + listeners.dark(); + expect( config.isDarkMode ).toBe( true ); + listeners.light(); + expect( config.isDarkMode ).toBe( false ); + expect( bridge.setDarkMode.mock.calls ).toEqual( [[true], [false]] ); + } ); + + it( 'dispose stops listening for menu events', async () => { + const { config } = new AppStore(); + await settle(); + expect( Object.keys( listeners ).sort() ).toEqual( ['dark', 'light'] ); + + config.dispose(); + expect( listeners ).toEqual( {} ); + } ); +} ); diff --git a/src/app/store/darkMode.test.js b/src/app/store/darkMode.test.js deleted file mode 100644 index 24bffd1d..00000000 --- a/src/app/store/darkMode.test.js +++ /dev/null @@ -1,21 +0,0 @@ -// @ts-nocheck — Jest globals. checkJs has no test runner types. -import { act } from 'react'; - -import Config from './Config'; - -it( 'loads dark mode from the renderer bridge', async () => { - const getDarkMode = jest.fn( async () => true ); - const setDarkMode = jest.fn( async () => {} ); - window.rendererBridge = { getDarkMode, setDarkMode }; - - const config = new Config(); - expect( config.isDarkMode ).toBe( false ); - await act( async () => { - await getDarkMode.mock.results[0].value; - } ); - expect( config.isDarkMode ).toBe( true ); - - config.setDarkMode( false ); - expect( config.isDarkMode ).toBe( false ); - expect( setDarkMode ).toHaveBeenCalledWith( false ); -} ); diff --git a/src/app/store/finalAlignment.test.js b/src/app/store/finalAlignment.test.js new file mode 100644 index 00000000..50e79769 --- /dev/null +++ b/src/app/store/finalAlignment.test.js @@ -0,0 +1,206 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; + +// The final alignment reads its run's alignments; build a real run with +// sequences set directly, as writeConcatenatedAlignment.test.js does. +function makeRun( alignments ) { + const run = new Run( {}, 7 ); + // outputNameAvailable is a promisedComputed that only settles inside a reaction (outside one each read calls the bridge); pin it. + run.outputNameAvailable = { get: () => ( { outputNameUnused: 'out' } ) }; + window.rendererBridge = { parseAlignment: () => new Promise( () => {} ) }; + run.addAlignments( alignments.map( ( { path } ) => ( { path } ) ) ); + runInAction( () => { + run.outputDir = '/out'; + alignments.forEach( ( spec, i ) => { + const a = run.alignments[i]; + a.sequences = spec.sequences; + a.length = spec.length; + a.dataType = spec.dataType || 'nucleotide'; + a.hasInvariantSites = !!spec.hasInvariantSites; + } ); + } ); + return run; +} + +const A = { + path: '/data/a.fasta', + length: 2, + sequences: [ + { taxon: 'Homo', code: 'AT' }, + { taxon: 'Mus', code: 'GC' }, + ], +}; +const B = { + path: '/data/b.fasta', + length: 3, + dataType: 'protein', + sequences: [ + { taxon: 'Mus', code: 'AAA' }, + { taxon: 'Rat', code: 'CCC' }, + ], +}; + +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +describe( 'FinalAlignment computeds', () => { + it( 'uses the single alignment file as is', () => { + const { finalAlignment: f } = makeRun( [A] ); + expect( f.numAlignments ).toBe( 1 ); + expect( f.filename ).toBe( 'a.fasta' ); + expect( f.dir ).toBe( '/data' ); + expect( f.path ).toBe( '/data/a.fasta' ); + expect( f.length ).toBe( 2 ); + expect( f.dataType ).toBe( 'nucleotide' ); + expect( f.partitionFilePath ).toBe( '' ); + } ); + + it( 'names a concatenated file in the output dir', () => { + const run = makeRun( [A, B] ); + const f = run.finalAlignment; + expect( f.numAlignments ).toBe( 2 ); + expect( f.filename ).toBe( `RAxML_${run.outputNameSafe}_concat.txt` ); + expect( f.dir ).toBe( '/out' ); + expect( f.path ).toBe( `/out/${f.filename}` ); + expect( f.length ).toBe( 5 ); + expect( f.partitionFilePath ).toBe( + `/out/RAxML_${run.outputNameSafe}_concat.part.txt`, + ); + expect( f.partitionFileContent ).toBe( f.partition.text ); + expect( f.partitionFileContent ).not.toBe( '' ); + } ); + + it( 'reports no model flag without alignments, else the first one', () => { + expect( makeRun( [] ).finalAlignment.modelFlagName ).toBe( 'none' ); + const run = makeRun( [A, B] ); + expect( run.finalAlignment.modelFlagName ).toBe( + run.alignments[0].modelFlagName, + ); + } ); + + it( 'combines data types and invariant sites over alignments', () => { + const run = makeRun( [A, B] ); + expect( run.finalAlignment.dataType ).toBe( 'mixed' ); + expect( run.finalAlignment.hasInvariantSites ).toBe( false ); + runInAction( () => { + run.alignments[1].hasInvariantSites = true; + } ); + expect( run.finalAlignment.hasInvariantSites ).toBe( true ); + } ); +} ); + +describe( 'FinalAlignment observables', () => { + it( 'fillTaxonGapsWithEmptySeqeunces switches taxons between union and intersection', () => { + const f = makeRun( [A, B] ).finalAlignment; + const { seen, stop } = track( () => [f.taxons, f.numSequences] ); + expect( seen[0] ).toEqual( [['Homo', 'Mus', 'Rat'], 3] ); + f.setFillTaxonGapsWithEmptySeqeunces( false ); + expect( seen[1] ).toEqual( [['Mus'], 1] ); + runInAction( () => { + f.fillTaxonGapsWithEmptySeqeunces = true; + } ); + expect( seen[2] ).toEqual( [['Homo', 'Mus', 'Rat'], 3] ); + stop(); + } ); + + it( 'parsingComplete is seen by a reaction', () => { + const f = makeRun( [A] ).finalAlignment; + const { seen, stop } = track( () => f.parsingComplete ); + runInAction( () => { + f.parsingComplete = false; + } ); + expect( seen ).toEqual( [true, false] ); + stop(); + } ); +} ); + +describe( 'FinalAlignment actions', () => { + function stubBridge() { + const bridge = { + writeFile: jest.fn( async () => {} ), + openPath: jest.fn( async () => {} ), + showItemInFolder: jest.fn( async () => {} ), + }; + window.rendererBridge = bridge; + return bridge; + } + + beforeEach( () => { + jest.spyOn( console, 'log' ).mockImplementation( () => {} ); + jest.spyOn( console, 'error' ).mockImplementation( () => {} ); + } ); + afterEach( () => jest.restoreAllMocks() ); + + it( 'writeConcatenatedAlignment fills gaps or drops taxons', async () => { + const f = makeRun( [A, B] ).finalAlignment; + const bridge = stubBridge(); + f.setFillTaxonGapsWithEmptySeqeunces( false ); + await f.writeConcatenatedAlignment(); + expect( bridge.writeFile ).toHaveBeenCalledWith( f.path, '>Mus\nGCAAA' ); + } ); + + it( 'writeConcatenatedAlignment rethrows a write failure', async () => { + const f = makeRun( [A] ).finalAlignment; + stubBridge().writeFile.mockRejectedValue( new Error( 'disk' ) ); + await expect( f.writeConcatenatedAlignment() ).rejects.toThrow( 'disk' ); + } ); + + it( 'writePartition writes the partition text and rethrows failures', async () => { + const f = makeRun( [A, B] ).finalAlignment; + const bridge = stubBridge(); + await f.writePartition(); + expect( bridge.writeFile ).toHaveBeenCalledWith( + f.partitionFilePath, + f.partitionFileContent, + ); + bridge.writeFile.mockRejectedValue( new Error( 'nope' ) ); + await expect( f.writePartition() ).rejects.toThrow( 'nope' ); + } ); + + it( 'writeConcatenatedAlignmentAndPartition writes both files', async () => { + const f = makeRun( [A, B] ).finalAlignment; + const bridge = stubBridge(); + await f.writeConcatenatedAlignmentAndPartition(); + expect( bridge.writeFile.mock.calls.map( ( c ) => c[0] ) ).toEqual( [ + f.path, + f.partitionFilePath, + ] ); + } ); + + it( 'openFile writes then opens the alignment', async () => { + const f = makeRun( [A, B] ).finalAlignment; + const bridge = stubBridge(); + await f.openFile(); + expect( bridge.writeFile ).toHaveBeenCalledTimes( 1 ); + expect( bridge.openPath ).toHaveBeenCalledWith( f.path ); + } ); + + it( 'openPartition writes both files then opens the partition', async () => { + const f = makeRun( [A, B] ).finalAlignment; + const bridge = stubBridge(); + await f.openPartition(); + expect( bridge.writeFile ).toHaveBeenCalledTimes( 2 ); + expect( bridge.openPath ).toHaveBeenCalledWith( f.partitionFilePath ); + } ); + + it( 'showFileInFolder writes then reveals the alignment', async () => { + const f = makeRun( [A, B] ).finalAlignment; + const bridge = stubBridge(); + await f.showFileInFolder(); + expect( bridge.writeFile ).toHaveBeenCalledTimes( 1 ); + expect( bridge.showItemInFolder ).toHaveBeenCalledWith( f.path ); + } ); + + it( 'openFolder writes both files then reveals the folder', async () => { + const f = makeRun( [A, B] ).finalAlignment; + const bridge = stubBridge(); + await f.openFolder(); + expect( bridge.writeFile ).toHaveBeenCalledTimes( 2 ); + expect( bridge.showItemInFolder ).toHaveBeenCalledWith( f.dir ); + } ); +} ); diff --git a/src/app/store/menu.test.js b/src/app/store/menu.test.js index a7f0dbed..0eb30898 100644 --- a/src/app/store/menu.test.js +++ b/src/app/store/menu.test.js @@ -29,17 +29,6 @@ it( 'onAddRun and onRemoveRun update the page runs', () => { expect( runs.runs ).toHaveLength( 1 ); } ); -it( 'onLightMode and onDarkMode update the page theme', () => { - const listeners = bridge(); - const runs = new RunList(); - - listeners.dark(); - expect( runs.config.isDarkMode ).toBe( true ); - - listeners.light(); - expect( runs.config.isDarkMode ).toBe( false ); -} ); - it( 'onToggleBackboneConstraint and onToggleMultifurcatingConstraint update those constraints', () => { const listeners = bridge(); const runs = new RunList(); diff --git a/src/app/store/modelSelection.test.js b/src/app/store/modelSelection.test.js index 6194defb..0643a58b 100644 --- a/src/app/store/modelSelection.test.js +++ b/src/app/store/modelSelection.test.js @@ -1,4 +1,5 @@ // @ts-nocheck — Jest globals. checkJs has no test runner types. +import { runInAction } from 'mobx'; import Run from './Run'; import { runEvents } from './StoreBase'; @@ -34,8 +35,10 @@ it( 'startModelSelection starts model selection', async () => { run.setOutputDir( '/out' ); run.addAlignments( [{ path: '/data/primates.fasta' }] ); const alignment = run.alignments[0]; - alignment.numSequences = 4; - alignment.dataType = 'nucleotide'; + runInAction( () => { + alignment.numSequences = 4; + alignment.dataType = 'nucleotide'; + } ); await alignment.runModelTest(); diff --git a/src/app/store/pageStoreGaps.test.js b/src/app/store/pageStoreGaps.test.js new file mode 100644 index 00000000..1501fbfe --- /dev/null +++ b/src/app/store/pageStoreGaps.test.js @@ -0,0 +1,96 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; +import RunList from './RunList'; + +let bridge; + +beforeEach( () => { + bridge = { + cancelModelSelection: jest.fn(), + parseAlignment: () => new Promise( () => {} ), + }; + window.rendererBridge = bridge; +} ); + +function makeRun() { + const parent = { onError: jest.fn(), deleteRun: jest.fn() }; + const run = new Run( parent, 7 ); + run.addAlignments( [{ path: '/data/a.fasta' }, { path: '/data/b.fasta' }] ); + return { run, parent }; +} + +describe( 'cancelModeltestOnAlignment', () => { + it( 'cancels the model selection of each loading alignment only', () => { + const { run } = makeRun(); + const [ loading, idle ] = run.alignments; + runInAction( () => { loading.modeltestLoading = true; } ); + + run.cancelModeltestOnAlignment(); + + expect( loading.modeltestLoading ).toBe( false ); + expect( run.modelTestIsRunningOnAlignment ).toBe( false ); + expect( bridge.cancelModelSelection ).toHaveBeenCalledTimes( 1 ); + expect( bridge.cancelModelSelection ).toHaveBeenCalledWith( loading.id ); + expect( idle.modeltestLoading ).toBe( false ); + } ); +} ); + +describe( 'clearShowModified', () => { + it( 'hides the modified snack and dialog on every alignment', () => { + const { run } = makeRun(); + runInAction( () => { + run.alignments.forEach( ( a ) => { + a.showModifiedSnack = true; + a.showModifiedDialog = true; + } ); + } ); + + run.clearShowModified(); + + run.alignments.forEach( ( a ) => { + expect( a.showModifiedSnack ).toBe( false ); + expect( a.showModifiedDialog ).toBe( false ); + } ); + } ); +} ); + +describe( 'removeRun', () => { + it( 'asks the run list to delete this run', () => { + const { run, parent } = makeRun(); + + run.removeRun(); + + expect( parent.deleteRun ).toHaveBeenCalledWith( run ); + } ); + + it( 'removes the run from a real run list', () => { + const list = new RunList(); + list.addRun(); + const [ first, second ] = list.runs; + + second.removeRun(); + + expect( list.runs ).toEqual( [ first ] ); + } ); +} ); + +describe( 'disableCheckUndeterminedSequence', () => { + it( 'is observed by the run: the -O argument follows it', () => { + const { run } = makeRun(); + runInAction( () => { run.binary.value = 'raxmlHPC'; } ); + // analysis is a computed that builds its option; keep it observed so a set value sticks. + const keepAnalysis = autorun( () => run.analysis ); + runInAction( () => { run.analysis.value = 'FT'; } ); + const seen = []; + const stop = autorun( () => seen.push( run.args.flat().includes( '-O' ) ) ); + + runInAction( () => { run.disableCheckUndeterminedSequence = false; } ); + runInAction( () => { run.disableCheckUndeterminedSequence = true; } ); + stop(); + keepAnalysis(); + + expect( seen ).toEqual( [ true, false, true ] ); + } ); +} ); diff --git a/src/app/store/runInputActions.test.js b/src/app/store/runInputActions.test.js new file mode 100644 index 00000000..cc1c27f6 --- /dev/null +++ b/src/app/store/runInputActions.test.js @@ -0,0 +1,321 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; + +const stayParsed = async () => ( { + alignment: { + sequences: [], + fileFormat: 'fasta', + numSequences: 0, + length: 0, + dataType: 'dna', + hasInvariantSites: false, + typecheckingComplete: true, + }, + change: null, +} ); + +const checkOutput = jest.fn( async ( { outputName } ) => ( { + ok: true, + outputNameUnused: outputName, + resultFilenames: [], +} ) ); + +const flush = () => new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); + +// Runs `read` in an autorun and returns every value it saw, newest last. +function watch( read ) { + const seen = []; + const dispose = autorun( () => seen.push( read() ) ); + return { seen, dispose }; +} + +let run; + +beforeEach( () => { + checkOutput.mockClear(); + window.rendererBridge = { parseAlignment: stayParsed, checkOutput }; + run = new Run( {}, 7 ); +} ); + +describe( 'output name and directory', () => { + it( 'setOutputName replaces spaces and trims the name', () => { + run.setOutputName( ' my run ' ); + expect( run.outputName ).toBe( '_my_run_' ); + } ); + + it( 'a new output name reaches the output check and the safe name', async () => { + const { seen, dispose } = watch( () => run.outputNameSafe ); + await flush(); + run.setOutputName( 'primates' ); + await flush(); + dispose(); + + expect( checkOutput ).toHaveBeenLastCalledWith( { + outputDir: '', + outputName: 'primates', + } ); + expect( seen[seen.length - 1] ).toBe( 'primates' ); + } ); + + it( 'setOutputDir sets the directory and moves the settings file path', () => { + const { seen, dispose } = watch( () => run.settingsFilePath ); + run.setOutputDir( '/out' ); + dispose(); + + expect( run.outputDir ).toBe( '/out' ); + expect( seen[seen.length - 1] ).toContain( '/out' ); + expect( seen[seen.length - 1] ).toContain( 'RAxML_GUI_Settings_' ); + } ); + + it( 'openOutputDir opens the output directory', async () => { + const openPath = jest.fn( async () => {} ); + window.rendererBridge = { checkOutput, openPath }; + run.setOutputDir( '/out' ); + + await run.openOutputDir(); + + expect( openPath ).toHaveBeenCalledWith( '/out' ); + } ); +} ); + +describe( 'random seed', () => { + it( 'setRandomSeed accepts a number and the seeds follow', () => { + const { seen, dispose } = watch( () => run.seedBootstrap ); + run.setRandomSeed( '12345' ); + dispose(); + + expect( run.randomSeed ).toBe( 12345 ); + expect( run.seedParsimony ).toBe( 12345 ); + expect( run.seedRapidBootstrap ).toBe( 12345 ); + expect( seen[seen.length - 1] ).toBe( 12345 ); + } ); + + it.each( [ '0', 'abc', '1000000', '2000000' ] )( + 'setRandomSeed ignores %s', + ( value ) => { + run.setRandomSeed( '42' ); + run.setRandomSeed( value ); + expect( run.randomSeed ).toBe( 42 ); + }, + ); +} ); + +describe( 'alignments', () => { + it( 'addAlignments adds the paths and names the run after the first', () => { + const { seen, dispose } = watch( () => run.haveAlignments ); + run.addAlignments( [ + { path: '/data/primates.fasta' }, + { path: '/data/cats.phy' }, + ] ); + dispose(); + + expect( run.alignments ).toHaveLength( 2 ); + expect( run.alignments[0].path ).toBe( '/data/primates.fasta' ); + expect( run.outputName ).toBe( run.alignments[0].name ); + expect( run.outputDir ).toBe( run.alignments[0].dir ); + expect( seen ).toEqual( [ false, true ] ); + } ); + + it( 'addAlignments keeps an output directory that is already set', () => { + run.setOutputDir( '/elsewhere' ); + run.addAlignments( [{ path: '/data/primates.fasta' }] ); + expect( run.outputDir ).toBe( '/elsewhere' ); + } ); + + it( 'a loaded alignment lets the partition file load, a second one blocks it', () => { + const { seen, dispose } = watch( () => run.canLoadPartitionFile ); + run.addAlignments( [{ path: '/data/primates.fasta' }] ); + run.addAlignments( [{ path: '/data/cats.phy' }] ); + dispose(); + + expect( seen ).toEqual( [ false, true, false ] ); + } ); + + it( 'removeAlignment removes it and keeps the partition while others remain', async () => { + window.rendererBridge = { + parseAlignment: stayParsed, + checkOutput, + readFile: async () => 'DNA, g = 1-10\n', + }; + run.addAlignments( [ + { path: '/data/primates.fasta' }, + { path: '/data/cats.phy' }, + ] ); + await run.addPartitionFiles( [{ path: '/data/g.part' }] ); + + run.removeAlignment( run.alignments[0] ); + + expect( run.alignments.map( ( a ) => a.path ) ).toEqual( [ '/data/cats.phy' ] ); + expect( run.partitionFile ).toBe( '/data/g.part' ); + } ); + + it( 'removing the last alignment resets the partition file', async () => { + window.rendererBridge = { + parseAlignment: stayParsed, + checkOutput, + readFile: async () => 'DNA, g = 1-10\n', + }; + run.addAlignments( [{ path: '/data/primates.fasta' }] ); + await run.addPartitionFiles( [{ path: '/data/g.part' }] ); + const { seen, dispose } = watch( () => run.haveAlignments ); + + run.removeAlignment( run.alignments[0] ); + dispose(); + + expect( seen ).toEqual( [ true, false ] ); + expect( run.partitionFile ).toBe( '' ); + expect( run.partitionFileContent ).toBe( '' ); + } ); + + it( 'removeAlignment ignores an alignment the run does not hold', () => { + run.addAlignments( [{ path: '/data/primates.fasta' }] ); + const other = new Run( {}, 8 ); + other.addAlignments( [{ path: '/data/other.fasta' }] ); + + run.removeAlignment( other.alignments[0] ); + + expect( run.alignments ).toHaveLength( 1 ); + } ); + + it( 'showPartition marks that alignment as shown, hidePartition clears it', () => { + run.addAlignments( [{ path: '/data/primates.fasta' }] ); + const [ alignment ] = run.alignments; + const { seen, dispose } = watch( () => alignment.showPartition ); + + run.showPartition( alignment ); + expect( run.showPartitionFor ).toBe( alignment ); + run.hidePartition(); + dispose(); + + expect( run.showPartitionFor ).toBeNull(); + expect( seen ).toEqual( [ false, true, false ] ); + } ); +} ); + +describe( 'ASTRAL tree', () => { + it( 'addAstralFiles sets the tree, the name and the directory once', () => { + const { seen, dispose } = watch( () => run.hasAstralTree ); + run.addAstralFiles( { path: '/data/trees.tre' } ); + run.addAstralFiles( { path: '/data/second.tre' } ); + dispose(); + + expect( run.astralTree.path ).toBe( '/data/trees.tre' ); + expect( run.outputName ).toBe( run.astralTree.name ); + expect( run.outputDir ).toBe( run.astralTree.dir ); + expect( seen ).toEqual( [ false, true ] ); + } ); + + it( 'removeAstralTree clears the tree', () => { + run.addAstralFiles( { path: '/data/trees.tre' } ); + const { seen, dispose } = watch( () => run.hasAstralTree ); + + run.removeAstralTree(); + dispose(); + + expect( run.astralTree ).toBeNull(); + expect( seen ).toEqual( [ true, false ] ); + } ); +} ); + +describe( 'partition file', () => { + it( 'loadPartitionFile shows the path and content after the read resolves', async () => { + let finishRead; + const readFile = jest.fn( + () => new Promise( ( resolve ) => { finishRead = resolve; } ), + ); + window.rendererBridge = { + checkOutput, + selectPartitionFile: async () => '/data/genes.part', + readFile, + }; + const { seen, dispose } = watch( () => `${run.partitionFile}|${run.partitionFileContent}` ); + + const loading = run.loadPartitionFile(); + await flush(); + expect( readFile ).toHaveBeenCalledWith( '/data/genes.part' ); + expect( run.partitionFile ).toBe( '' ); + expect( run.partitionFileContent ).toBe( '' ); + + finishRead( 'DNA, gene = 1-100\n' ); + await loading; + dispose(); + + expect( run.partitionFile ).toBe( '/data/genes.part' ); + expect( run.partitionFileContent ).toBe( 'DNA, gene = 1-100\n' ); + expect( seen[seen.length - 1] ).toBe( '/data/genes.part|DNA, gene = 1-100\n' ); + } ); + + it( 'a loaded partition file moves its computeds and blocks the alignment picker', async () => { + window.rendererBridge = { checkOutput, readFile: async () => 'x' }; + const name = watch( () => run.partitionFileName ); + const have = watch( () => run.havePartitionFile ); + const canLoad = watch( () => run.canLoadAlignment ); + + await run.addPartitionFiles( [{ path: '/data/genes.part' }] ); + name.dispose(); + have.dispose(); + canLoad.dispose(); + + expect( name.seen[name.seen.length - 1] ).toBe( 'genes.part' ); + expect( have.seen ).toEqual( [ false, true ] ); + expect( canLoad.seen ).toEqual( [ true, false ] ); + } ); + + it( 'addPartitionFiles with no files changes nothing', async () => { + window.rendererBridge = { checkOutput, readFile: jest.fn() }; + await run.addPartitionFiles( [] ); + expect( run.partitionFile ).toBe( '' ); + expect( window.rendererBridge.readFile ).not.toHaveBeenCalled(); + } ); + + it( 'removePartitionFile clears the path and the content', async () => { + window.rendererBridge = { checkOutput, readFile: async () => 'x' }; + await run.addPartitionFiles( [{ path: '/data/genes.part' }] ); + const { seen, dispose } = watch( () => run.havePartitionFile ); + + run.removePartitionFile(); + dispose(); + + expect( run.partitionFile ).toBe( '' ); + expect( run.partitionFileContent ).toBe( '' ); + expect( seen ).toEqual( [ true, false ] ); + } ); +} ); + +describe( 'tree files', () => { + it.each( [ 'tree', 'backboneConstraint', 'multifurcatingConstraint' ] )( + 'addTreeFiles sets the %s file', + ( type ) => { + const { seen, dispose } = watch( () => run[type].haveFile ); + run.addTreeFiles( type, [{ path: '/data/t.nwk' }] ); + dispose(); + + expect( run[type].filePath ).toBe( '/data/t.nwk' ); + expect( run[type].filename ).toBe( 't.nwk' ); + expect( seen ).toEqual( [ false, true ] ); + }, + ); + + it( 'addTreeFiles ignores an unknown type and an empty list', () => { + run.addTreeFiles( 'other', [{ path: '/data/t.nwk' }] ); + run.addTreeFiles( 'tree', [] ); + + expect( run.tree.filePath ).toBe( '' ); + expect( run.backboneConstraint.filePath ).toBe( '' ); + expect( run.multifurcatingConstraint.filePath ).toBe( '' ); + } ); +} ); + +describe( 'state set directly', () => { + it( 'setting the alignments inside runInAction moves numSites', () => { + const { seen, dispose } = watch( () => run.numSites ); + runInAction( () => { + run.alignments = [ 3, 4 ]; + } ); + dispose(); + + expect( seen ).toEqual( [ 0, 7 ] ); + } ); +} ); diff --git a/src/app/store/runLifecycle.test.js b/src/app/store/runLifecycle.test.js new file mode 100644 index 00000000..24d5208c --- /dev/null +++ b/src/app/store/runLifecycle.test.js @@ -0,0 +1,354 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; +import { runEvents } from './StoreBase'; + +let listeners; +let bridge; + +function subscribeTo( byName, name ) { + return ( listener ) => { + ( byName[name] ||= [] ).push( listener ); + return () => { + byName[name] = byName[name].filter( ( l ) => l !== listener ); + }; + }; +} + +// The run subscribes to bridge events at construction; keep each listener so a test can fire it. +beforeEach( () => { + listeners = {}; + bridge = { + startRun: jest.fn( async () => {} ), + startAstral: jest.fn( async () => {} ), + cancelRun: jest.fn(), + writeFile: jest.fn( async () => {} ), + checkOutput: jest.fn( async () => ( { ok: true, resultFilenames: ['out.tre'] } ) ), + parseAlignment: () => new Promise( () => {} ), + }; + for ( const name of Object.values( runEvents ) ) { + bridge[name] = subscribeTo( listeners, name ); + } + window.rendererBridge = bridge; +} ); + +function fire( name, payload ) { + ( listeners[name] || [] ).forEach( ( listener ) => listener( payload ) ); +} + +// Records every value a reaction sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +function makeRun( { numSequences = 4 } = {} ) { + const parent = { onError: jest.fn() }; + const run = new Run( parent, 7 ); + run.addAlignments( [{ path: '/data/primates.fasta' }] ); + run.alignments[0].sequences = Array.from( { length: numSequences }, ( _, i ) => ( { + taxon: `T${i}`, + } ) ); + run.setOutputDir( '/out' ); + return { run, parent }; +} + +describe( 'start', () => { + it( 'marks the run running and starts it on the bridge', async () => { + const { run } = makeRun(); + const startDisabled = track( () => run.startDisabled ); + expect( startDisabled.seen.at( -1 ) ).toBe( false ); + + await run.start(); + + expect( run.running ).toBe( true ); + expect( bridge.startRun ).toHaveBeenCalledTimes( 1 ); + expect( bridge.startRun.mock.calls[0][0] ).toMatchObject( { + id: 7, + binaryName: run.binary.value, + outputDir: '/out', + inputPath: '/data/primates.fasta', + } ); + expect( startDisabled.seen.at( -1 ) ).toBe( true ); + startDisabled.stop(); + } ); + + it( 'writes the settings file before starting', async () => { + const { run } = makeRun(); + await run.start(); + expect( bridge.writeFile ).toHaveBeenCalledWith( + run.settingsFilePath, + run.settingsFileContent, + ); + } ); + + it( 'reports an error and does not start with fewer than four sequences', async () => { + const { run, parent } = makeRun( { numSequences: 3 } ); + + await run.start(); + + expect( parent.onError ).toHaveBeenCalledTimes( 1 ); + expect( parent.onError.mock.calls[0][0].message ).toMatch( /at least four sequences/ ); + expect( run.running ).toBe( false ); + expect( bridge.startRun ).not.toHaveBeenCalled(); + } ); + + it( 'adopts the safe output name, which a reaction on the name sees', async () => { + const { run } = makeRun(); + bridge.checkOutput = jest.fn( async () => ( { + ok: false, + outputNameUnused: 'primates_2', + resultFilenames: [], + } ) ); + const name = track( () => run.outputName ); + const safe = track( () => run.outputNameSafe ); + await new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); + expect( safe.seen.at( -1 ) ).toBe( 'primates_2' ); + + await run.start(); + + expect( run.outputName ).toBe( 'primates_2' ); + expect( name.seen.at( -1 ) ).toBe( 'primates_2' ); + name.stop(); + safe.stop(); + } ); +} ); + +describe( 'streamed output', () => { + it( 'appends stdout and stderr for this run only, and reactions see it', () => { + const { run } = makeRun(); + const report = track( () => run.generateReport().stdout ); + const stderr = track( () => run.stderr ); + + fire( runEvents.onRunStdout, { id: 7, content: 'tree\n' } ); + fire( runEvents.onRunStdout, { id: 7, content: 'more\n' } ); + fire( runEvents.onRunStdout, { id: 8, content: 'other run' } ); + fire( runEvents.onRunStderr, { id: 7, content: 'warn\n' } ); + fire( runEvents.onRunStderr, { id: 8, content: 'other run' } ); + + expect( run.stdout ).toBe( 'tree\nmore\n' ); + expect( run.stderr ).toBe( 'warn\n' ); + expect( report.seen.at( -1 ) ).toBe( 'tree\nmore\n' ); + expect( stderr.seen.at( -1 ) ).toBe( 'warn\n' ); + report.stop(); + stderr.stop(); + } ); + + it( 'clearing the console empties both streams for reactions', () => { + const { run } = makeRun(); + fire( runEvents.onRunStdout, { id: 7, content: 'a' } ); + fire( runEvents.onRunStderr, { id: 7, content: 'b' } ); + const both = track( () => `${run.stdout}|${run.stderr}` ); + + run.clearConsole(); + + expect( both.seen.at( -1 ) ).toBe( '|' ); + both.stop(); + } ); +} ); + +describe( 'finish', () => { + it( 'records the result and frees the run', async () => { + const { run } = makeRun(); + const startDisabled = track( () => run.startDisabled ); + const finished = track( () => [run.finished, run.exitCode] ); + const haveResult = track( () => run.haveResult ); + await new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); + runInAction( () => { + run.running = true; + } ); + expect( startDisabled.seen.at( -1 ) ).toBe( true ); + expect( haveResult.seen.at( -1 ) ).toBe( false ); + + fire( runEvents.onRunFinished, { + id: 7, + resultDir: '/out', + resultFilenames: ['out.tre'], + exitCode: 0, + } ); + + expect( run.resultDir ).toBe( '/out' ); + expect( run.finished ).toBe( true ); + expect( run.exitCode ).toBe( 0 ); + expect( run.running ).toBe( false ); + expect( startDisabled.seen.at( -1 ) ).toBe( false ); + expect( finished.seen.at( -1 ) ).toEqual( [true, 0] ); + await new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); + expect( haveResult.seen.at( -1 ) ).toBe( true ); + startDisabled.stop(); + finished.stop(); + haveResult.stop(); + } ); + + it( 'records a non-zero exit code and clearFinished resets it', () => { + const { run } = makeRun(); + const finished = track( () => [run.finished, run.exitCode] ); + + fire( runEvents.onRunFinished, { + id: 7, + resultDir: '/out', + resultFilenames: [], + exitCode: 2, + } ); + expect( finished.seen.at( -1 ) ).toEqual( [true, 2] ); + + run.clearFinished(); + expect( finished.seen.at( -1 ) ).toEqual( [false, 0] ); + finished.stop(); + } ); + + it( 'ignores a finish for another run', () => { + const { run } = makeRun(); + runInAction( () => { + run.running = true; + } ); + + fire( runEvents.onRunFinished, { id: 8, resultDir: '/x', resultFilenames: [], exitCode: 1 } ); + + expect( run.finished ).toBe( false ); + expect( run.running ).toBe( true ); + expect( run.resultDir ).toBe( '' ); + } ); + + it( 'checks the output again after the run, so the result list refreshes', async () => { + const { run } = makeRun(); + const files = track( () => run.resultFilenames ); + await new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); + const before = bridge.checkOutput.mock.calls.length; + + fire( runEvents.onRunFinished, { + id: 7, + resultDir: '/out', + resultFilenames: ['out.tre'], + exitCode: 0, + } ); + await new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); + + expect( bridge.checkOutput.mock.calls.length ).toBeGreaterThan( before ); + expect( files.seen.at( -1 ) ).toEqual( ['out.tre'] ); + files.stop(); + } ); +} ); + +describe( 'failure', () => { + it( 'shows the error, frees the run, and ok follows the error', () => { + const { run } = makeRun(); + runInAction( () => { + run.running = true; + } ); + const ok = track( () => run.ok ); + const error = track( () => run.error ); + expect( ok.seen.at( -1 ) ).toBe( true ); + + fire( runEvents.onRunError, { id: 7, error: 'missing binary' } ); + + expect( run.error ).toBe( 'missing binary' ); + expect( run.running ).toBe( false ); + expect( run.finished ).toBe( false ); + expect( ok.seen.at( -1 ) ).toBe( false ); + expect( error.seen.at( -1 ) ).toBe( 'missing binary' ); + + run.clearError(); + expect( ok.seen.at( -1 ) ).toBe( true ); + ok.stop(); + error.stop(); + } ); + + it( 'ignores an error for another run', () => { + const { run } = makeRun(); + + fire( runEvents.onRunError, { id: 8, error: 'not mine' } ); + + expect( run.error ).toBe( null ); + } ); +} ); + +describe( 'cancel', () => { + it( 'tells the bridge, frees the run, and stays quiet', () => { + const { run, parent } = makeRun(); + runInAction( () => { + run.running = true; + } ); + const startDisabled = track( () => run.startDisabled ); + const ok = track( () => run.ok ); + expect( startDisabled.seen.at( -1 ) ).toBe( true ); + + run.cancel(); + + expect( bridge.cancelRun ).toHaveBeenCalledWith( 7 ); + expect( run.running ).toBe( false ); + expect( startDisabled.seen.at( -1 ) ).toBe( false ); + expect( run.error ).toBe( null ); + expect( ok.seen.at( -1 ) ).toBe( true ); + expect( run.finished ).toBe( false ); + expect( parent.onError ).not.toHaveBeenCalled(); + startDisabled.stop(); + ok.stop(); + } ); + + it( 'stops a start that is still writing files from starting the run', async () => { + const { run } = makeRun(); + let release; + bridge.writeFile = jest.fn( + () => new Promise( ( resolve ) => { + release = resolve; + } ), + ); + + const pending = run.start(); + run.cancel(); + release(); + await pending; + + expect( bridge.startRun ).not.toHaveBeenCalled(); + expect( run.running ).toBe( false ); + expect( run.error ).toBe( null ); + } ); + + it( 'dispose cancels the run and unsubscribes its listeners', () => { + const { run } = makeRun(); + + run.dispose(); + + expect( bridge.cancelRun ).toHaveBeenCalledWith( 7 ); + fire( runEvents.onRunStdout, { id: 7, content: 'late' } ); + expect( run.stdout ).toBe( '' ); + } ); +} ); + +describe( 'ASTRAL', () => { + it( 'shows ASTRAL is running and starts it on the bridge', async () => { + const { run } = makeRun(); + const startDisabled = track( () => run.startDisabled ); + + await run.startAstral(); + + expect( run.running ).toBe( true ); + expect( startDisabled.seen.at( -1 ) ).toBe( true ); + expect( bridge.startAstral ).toHaveBeenCalledWith( { + id: 7, + binaryName: run.binary.value, + args: run.args, + } ); + startDisabled.stop(); + } ); + + it( 'reports the ASTRAL result for this run', () => { + const { run } = makeRun(); + runInAction( () => { + run.running = true; + } ); + const finished = track( () => [run.finished, run.exitCode, run.running] ); + + fire( runEvents.onAstralSuccess, { id: 8, exitCode: 4 } ); + expect( finished.seen.at( -1 ) ).toEqual( [false, 0, true] ); + + fire( runEvents.onAstralSuccess, { id: 7, exitCode: 0 } ); + + expect( run.resultDir ).toBe( '/out' ); + expect( finished.seen.at( -1 ) ).toEqual( [true, 0, false] ); + finished.stop(); + } ); +} ); diff --git a/src/app/store/showItemInFolder.test.js b/src/app/store/showItemInFolder.test.js index ffa6a094..d51fc798 100644 --- a/src/app/store/showItemInFolder.test.js +++ b/src/app/store/showItemInFolder.test.js @@ -1,5 +1,5 @@ // @ts-nocheck — Jest globals. checkJs has no test runner types. -import InputFile from './InputFile'; +import { runInAction } from 'mobx'; import Run from './Run'; it( 'shows a tree file in its folder', async () => { @@ -13,25 +13,17 @@ it( 'shows a tree file in its folder', async () => { expect( showItemInFolder ).toHaveBeenCalledWith( '/data/start.nwk' ); } ); -it( 'shows an input file in its folder', async () => { - const file = new InputFile( { id: 7 }, '/data/primates.fasta' ); - const showItemInFolder = jest.fn( async () => {} ); - window.rendererBridge = { showItemInFolder }; - - await file.showFileInFolder(); - - expect( showItemInFolder ).toHaveBeenCalledWith( '/data/primates.fasta' ); -} ); - it( 'shows the concatenated alignment in its folder', async () => { const run = new Run( {}, 7 ); window.rendererBridge = { parseAlignment: () => new Promise( () => {} ) }; run.addAlignments( [ { path: '/data/a.fasta' } ] ); - run.alignments[0].sequences = [ - { taxon: 'Homo', code: 'AT' }, - { taxon: 'Mus', code: 'GC' }, - ]; - run.alignments[0].length = 2; + runInAction( () => { + run.alignments[0].sequences = [ + { taxon: 'Homo', code: 'AT' }, + { taxon: 'Mus', code: 'GC' }, + ]; + run.alignments[0].length = 2; + } ); const showItemInFolder = jest.fn( async () => {} ); window.rendererBridge = { writeFile: jest.fn( async () => {} ), diff --git a/src/app/store/substitutionOptions.test.js b/src/app/store/substitutionOptions.test.js new file mode 100644 index 00000000..fcc67056 --- /dev/null +++ b/src/app/store/substitutionOptions.test.js @@ -0,0 +1,315 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; + +// Run's constructor subscribes to bridge events; a no-op stub is enough here. +beforeEach( () => { + window.rendererBridge = new Proxy( {}, { + get: ( _, name ) => { + if ( name === 'getVersion' ) { + return () => Promise.resolve( '2.0.0' ); + } + // A load that never settles keeps the test in control of dataType. + return name === 'parseAlignment' + ? () => new Promise( () => {} ) + : () => () => {}; + }, + } ); +} ); + +const binaryNamed = ( run, prefix ) => run.binary.options + .map( ( o ) => o.value ).find( ( v ) => v.startsWith( prefix ) ); +const ngName = () => binaryNamed( new Run( { onError() {} }, 1 ), 'raxml-ng' ); + +// The default binary depends on the host platform, so pin a classic RAxML one. +function newRun() { + const run = new Run( { onError() {} }, 1 ); + run.binary.setValue( binaryNamed( run, 'raxmlHPC' ) ); + return run; +} + +function makeRun( dataType = 'nucleotide' ) { + const run = newRun(); + run.addAlignments( [{ path: '/data/a.fasta' }] ); + runInAction( () => { + run.alignments[0].dataType = dataType; + } ); + return run; +} + +// Records every value an autorun sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +const noAlignmentRun = newRun; + +describe( 'SubstitutionMatrix', () => { + it( 'has no options without alignments, then lists them per data type', () => { + const run = noAlignmentRun(); + const { seen, stop } = track( () => run.substitutionMatrix.options ); + expect( seen[0] ).toEqual( [] ); + run.addAlignments( [{ path: '/a.fasta' }] ); + runInAction( () => { + run.alignments[0].dataType = 'nucleotide'; + } ); + expect( run.substitutionMatrix.options ).toEqual( [ + { value: 'JC', title: 'JC + GAMMA' }, + { value: 'K80', title: 'K80 + GAMMA' }, + { value: 'HKY', title: 'HKY + GAMMA' }, + { value: 'GTR', title: 'GTR' }, + ] ); + expect( seen[seen.length - 1] ).toHaveLength( 4 ); + stop(); + } ); + + it( 'has no options for a data type without settings', () => { + const run = makeRun( 'unknown' ); + expect( run.substitutionMatrix.options ).toEqual( [] ); + } ); + + it( 'is not available without alignments, for other data types or raxml-ng', () => { + const run = noAlignmentRun(); + const { seen, stop } = track( () => run.substitutionMatrix.notAvailable ); + expect( seen[0] ).toBe( true ); + run.addAlignments( [{ path: '/a.fasta' }] ); + runInAction( () => { + run.alignments[0].dataType = 'nucleotide'; + } ); + expect( run.substitutionMatrix.notAvailable ).toBe( false ); + for ( const type of ['binary', 'protein', 'multistate'] ) { + runInAction( () => { + run.alignments[0].dataType = type; + } ); + expect( run.substitutionMatrix.notAvailable ).toBe( true ); + } + runInAction( () => { + run.alignments[0].dataType = 'nucleotide'; + } ); + run.binary.setValue( ngName() ); + expect( run.substitutionMatrix.notAvailable ).toBe( true ); + expect( seen ).toContain( false ); + stop(); + } ); + + it( 'maps the data type and value to the command value', () => { + const run = makeRun( 'nucleotide' ); + const { seen, stop } = track( () => run.substitutionMatrix.cmdValue ); + expect( seen[0] ).toBe( 'GTR' ); + for ( const [value, cmd] of [['JC', 'GTR'], ['K80', 'GTR'], ['HKY', 'GTR']] ) { + run.substitutionMatrix.setValue( value ); + expect( run.substitutionMatrix.cmdValue ).toBe( cmd ); + } + for ( const [type, cmd] of [['binary', 'BIN'], ['protein', 'PROT'], ['multistate', 'MULTI']] ) { + runInAction( () => { + run.alignments[0].dataType = type; + } ); + expect( run.substitutionMatrix.cmdValue ).toBe( cmd ); + } + expect( seen ).toEqual( ['GTR', 'BIN', 'PROT', 'MULTI'] ); + stop(); + } ); + + it( 'passes the value through for a mixed run', () => { + const run = makeRun( 'mixed' ); + run.substitutionMatrix.setValue( 'BIN' ); + expect( run.substitutionMatrix.cmdValue ).toBe( 'BIN' ); + } ); + + it( 'gives the extra raxml-ng flag and notGTR per value', () => { + const run = makeRun(); + const matrix = run.substitutionMatrix; + const flags = track( () => matrix.extraCmdValue ); + const notGTR = track( () => matrix.notGTR ); + expect( flags.seen[0] ).toBe( '' ); + expect( notGTR.seen[0] ).toBe( false ); + for ( const [value, flag] of [['JC', '--JC69'], ['K80', '--K80'], ['HKY', '--HKY85'], ['GTR', '']] ) { + matrix.setValue( value ); + expect( matrix.extraCmdValue ).toBe( flag ); + expect( matrix.notGTR ).toBe( value !== 'GTR' ); + } + expect( flags.seen ).toEqual( ['', '--JC69', '--K80', '--HKY85', ''] ); + expect( notGTR.seen ).toEqual( [false, true, false] ); + flags.stop(); + notGTR.stop(); + } ); +} ); + +describe( 'SubstitutionRate', () => { + it( 'lists rate options once there are alignments', () => { + const run = noAlignmentRun(); + const { seen, stop } = track( () => run.substitutionRate.options ); + expect( seen[0] ).toEqual( [] ); + run.addAlignments( [{ path: '/a.fasta' }] ); + expect( run.substitutionRate.options ).toEqual( [ + { value: 'CAT', title: 'CAT' }, + { value: 'GAMMA', title: 'GAMMA' }, + ] ); + expect( seen ).toHaveLength( 2 ); + stop(); + } ); + + it( 'is unavailable without alignments, for non-GTR nucleotide or raxml-ng', () => { + const run = noAlignmentRun(); + const { seen, stop } = track( () => run.substitutionRate.notAvailable ); + expect( seen[0] ).toBe( true ); + run.addAlignments( [{ path: '/a.fasta' }] ); + runInAction( () => { + run.alignments[0].dataType = 'nucleotide'; + } ); + expect( run.substitutionRate.notAvailable ).toBe( false ); + run.substitutionMatrix.setValue( 'HKY' ); + expect( run.substitutionRate.notAvailable ).toBe( true ); + runInAction( () => { + run.alignments[0].dataType = 'protein'; + } ); + expect( run.substitutionRate.notAvailable ).toBe( false ); + run.binary.setValue( ngName() ); + expect( run.substitutionRate.notAvailable ).toBe( true ); + expect( seen ).toEqual( [true, false, true, false, true] ); + stop(); + } ); + + it( 'forces GAMMA unless the matrix is GTR, and reports CAT', () => { + const run = makeRun(); + const rate = run.substitutionRate; + const cmd = track( () => rate.cmdValue ); + const cat = track( () => rate.isCAT ); + expect( cmd.seen[0] ).toBe( 'GAMMA' ); + expect( cat.seen[0] ).toBe( false ); + rate.setValue( 'CAT' ); + expect( rate.cmdValue ).toBe( 'CAT' ); + expect( rate.isCAT ).toBe( true ); + run.substitutionMatrix.setValue( 'K80' ); + expect( rate.cmdValue ).toBe( 'GAMMA' ); + expect( rate.isCAT ).toBe( true ); + expect( cmd.seen ).toEqual( ['GAMMA', 'CAT', 'GAMMA'] ); + expect( cat.seen ).toEqual( [false, true] ); + cmd.stop(); + cat.stop(); + } ); +} ); + +describe( 'SubstitutionI', () => { + it( 'lists the invariant-sites options once there are alignments', () => { + const run = noAlignmentRun(); + const { seen, stop } = track( () => run.substitutionI.options ); + expect( seen[0] ).toEqual( [] ); + run.addAlignments( [{ path: '/a.fasta' }] ); + expect( run.substitutionI.options ).toEqual( [ + { value: 'none', title: 'none' }, + { value: '+I (ML estimate)', title: '+I (ML estimate)' }, + ] ); + expect( seen ).toHaveLength( 2 ); + stop(); + } ); + + it( 'is unavailable without alignments, with ascertainment set or raxml-ng', () => { + const run = noAlignmentRun(); + const { seen, stop } = track( () => run.substitutionI.notAvailable ); + expect( seen[0] ).toBe( true ); + run.addAlignments( [{ path: '/a.fasta' }] ); + expect( run.substitutionI.notAvailable ).toBe( false ); + run.substitutionAscertainment.setValue( "Lewis' method" ); + expect( run.substitutionI.notAvailable ).toBe( true ); + run.substitutionAscertainment.setValue( 'none' ); + run.binary.setValue( ngName() ); + expect( run.substitutionI.notAvailable ).toBe( true ); + expect( seen ).toEqual( [true, false, true, false, true] ); + stop(); + } ); + + it( 'gives I and isSet once a value is chosen', () => { + const run = makeRun(); + const cmd = track( () => run.substitutionI.cmdValue ); + const set = track( () => run.substitutionI.isSet ); + expect( cmd.seen ).toEqual( [''] ); + expect( set.seen ).toEqual( [false] ); + run.substitutionI.setValue( '+I (ML estimate)' ); + expect( cmd.seen ).toEqual( ['', 'I'] ); + expect( set.seen ).toEqual( [false, true] ); + cmd.stop(); + set.stop(); + } ); +} ); + +describe( 'SubstitutionAscertainment', () => { + it( 'lists the ascertainment options once there are alignments', () => { + const run = noAlignmentRun(); + const { seen, stop } = track( () => run.substitutionAscertainment.options ); + expect( seen[0] ).toEqual( [] ); + run.addAlignments( [{ path: '/a.fasta' }] ); + expect( run.substitutionAscertainment.options.map( ( o ) => o.value ) ).toEqual( [ + 'none', + "Lewis' method", + "Felsenstein's method", + "Stamatakis' method", + ] ); + expect( seen ).toHaveLength( 2 ); + stop(); + } ); + + it( 'is unavailable without alignments, mixed data, invariant sites, +I or raxml-ng', () => { + const run = noAlignmentRun(); + const { seen, stop } = track( () => run.substitutionAscertainment.notAvailable ); + expect( seen[0] ).toBe( true ); + run.addAlignments( [{ path: '/a.fasta' }] ); + runInAction( () => { + run.alignments[0].dataType = 'nucleotide'; + } ); + expect( run.substitutionAscertainment.notAvailable ).toBe( false ); + runInAction( () => { + run.alignments[0].dataType = 'mixed'; + } ); + expect( run.substitutionAscertainment.notAvailable ).toBe( true ); + runInAction( () => { + run.alignments[0].dataType = 'nucleotide'; + } ); + runInAction( () => { + run.alignments[0].hasInvariantSites = true; + } ); + expect( run.substitutionAscertainment.notAvailable ).toBe( true ); + runInAction( () => { + run.alignments[0].hasInvariantSites = false; + } ); + run.substitutionI.setValue( '+I (ML estimate)' ); + expect( run.substitutionAscertainment.notAvailable ).toBe( true ); + run.substitutionI.setValue( 'none' ); + run.binary.setValue( ngName() ); + expect( run.substitutionAscertainment.notAvailable ).toBe( true ); + expect( seen ).toEqual( [true, false, true, false, true, false, true, false, true] ); + stop(); + } ); + + it( 'gives ASC_, the raxml-ng flag and isSet per value', () => { + const run = makeRun(); + const asc = run.substitutionAscertainment; + const cmd = track( () => asc.cmdValue ); + const extra = track( () => asc.extraCmdValue ); + const set = track( () => asc.isSet ); + expect( [cmd.seen[0], extra.seen[0], set.seen[0]] ).toEqual( ['', '', false] ); + for ( const [value, flag] of [ + [ "Lewis' method", '--asc-corr=lewis' ], + [ "Felsenstein's method", '--asc-corr=felsenstein' ], + [ "Stamatakis' method", '--asc-corr=stamatakis' ], + ] ) { + asc.setValue( value ); + expect( asc.cmdValue ).toBe( 'ASC_' ); + expect( asc.extraCmdValue ).toBe( flag ); + expect( asc.isSet ).toBe( true ); + } + asc.setValue( 'none' ); + expect( [asc.cmdValue, asc.extraCmdValue, asc.isSet] ).toEqual( ['', '', false] ); + expect( extra.seen ).toEqual( [ + '', '--asc-corr=lewis', '--asc-corr=felsenstein', '--asc-corr=stamatakis', '', + ] ); + expect( cmd.seen ).toEqual( ['', 'ASC_', ''] ); + expect( set.seen ).toEqual( [false, true, false] ); + cmd.stop(); + extra.stop(); + set.stop(); + } ); +} ); diff --git a/src/app/store/treeFileOptions.test.js b/src/app/store/treeFileOptions.test.js new file mode 100644 index 00000000..190c420e --- /dev/null +++ b/src/app/store/treeFileOptions.test.js @@ -0,0 +1,159 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; + +const files = [ + [ 'tree', '/data/start.nwk' ], + [ 'backboneConstraint', '/data/backbone.tre' ], + [ 'multifurcatingConstraint', '/data/multi.tre' ], +]; + +let showItemInFolder; +let openPath; +let selectTree; +let run; +let disposers; + +// Records every value an autorun sees, so a test can prove it re-ran. +// Run.analysis is a computed that builds a new option; observing it keeps the set value. +function observe( fn ) { + const seen = []; + disposers.push( autorun( () => seen.push( fn() ) ) ); + return { seen }; +} + +beforeEach( () => { + showItemInFolder = jest.fn( async () => {} ); + openPath = jest.fn( async () => {} ); + selectTree = jest.fn(); + window.rendererBridge = { showItemInFolder, openPath, selectTree }; + run = new Run( {}, 3 ); + disposers = []; + // The default binary is raxml-ng; these tests use the classic RAxML analyses. + run.binary.setValue( run.binary.options.find( ( { value } ) => value.includes( 'raxmlHPC' ) ).value ); + observe( () => run.analysis.value ); +} ); + +afterEach( () => { + disposers.forEach( ( stop ) => stop() ); +} ); + +describe.each( files )( '%s file', ( key, filePath ) => { + const option = () => run[key]; + const filename = filePath.split( '/' ).pop(); + const stem = filename.replace( /\.\w+$/, '' ); + + it( 'starts without a file', () => { + expect( option().filePath ).toBe( '' ); + expect( option().haveFile ).toBe( false ); + expect( option().filename ).toBe( '' ); + expect( option().dir ).toBe( '' ); + } ); + + it( 'loading a file sets path, filename, name, dir and haveFile', async () => { + selectTree.mockResolvedValue( { type: key, filePath } ); + const load = { + tree: run.loadTreeFile, + backboneConstraint: run.loadBackboneConstraintFile, + multifurcatingConstraint: run.loadMultifurcatingConstraintFile, + }[key]; + await load(); + expect( selectTree ).toHaveBeenCalledWith( 3, key ); + expect( option().filePath ).toBe( filePath ); + expect( option().haveFile ).toBe( true ); + expect( option().filename ).toBe( filename ); + expect( option().name ).toBe( stem ); + expect( option().dir ).toBe( '/data' ); + } ); + + it( 'setFilePath updates every computed', () => { + const { seen } = observe( () => [ + option().haveFile, option().filename, option().name, option().dir, + ] ); + option().setFilePath( filePath ); + expect( seen ).toEqual( [ + [ false, '', '', '' ], + [ true, filename, stem, '/data' ], + ] ); + } ); + + it( 'a reaction sees filePath set directly', () => { + const { seen } = observe( () => option().haveFile ); + runInAction( () => { + option().filePath = filePath; + } ); + expect( seen ).toEqual( [ false, true ] ); + } ); + + it( 'remove clears the file', () => { + option().setFilePath( filePath ); + const { seen } = observe( () => option().haveFile ); + option().remove(); + expect( option().filePath ).toBe( '' ); + expect( seen ).toEqual( [ true, false ] ); + } ); + + it( 'openFolder and openFile pass the path to the bridge', async () => { + option().setFilePath( filePath ); + await option().openFolder(); + await option().openFile(); + expect( showItemInFolder ).toHaveBeenCalledWith( filePath ); + expect( openPath ).toHaveBeenCalledWith( filePath ); + } ); +} ); + +describe( 'Tree notAvailable', () => { + it( 'is unavailable for the default analysis', () => { + expect( run.tree.notAvailable ).toBe( true ); + } ); + + it( 'follows the analysis that takes a tree', () => { + const { seen } = observe( () => run.tree.notAvailable ); + run.analysis.setValue( 'AS' ); + run.analysis.setValue( 'ML+rBS' ); + expect( seen ).toEqual( [ true, false, true ] ); + } ); + + it( 'follows a user defined starting tree', () => { + const { seen } = observe( () => run.tree.notAvailable ); + run.analysis.setValue( 'PD' ); + run.startingTree.setValue( 'User defined' ); + run.startingTree.setValue( 'Maximum parsimony' ); + expect( seen ).toEqual( [ true, false, true ] ); + } ); +} ); + +describe.each( [ + [ 'backboneConstraint', 'useBackboneConstraint', 'onBackboneConstraint' ], + [ 'multifurcatingConstraint', 'useMultifurcatingConstraint', 'onMultifurcatingConstraint' ], +] )( '%s toggle', ( key, flag, toggle ) => { + const option = () => run[key]; + + it( 'notAvailable follows the toggle', () => { + const { seen } = observe( () => option().notAvailable ); + run[toggle](); + run[toggle](); + expect( seen ).toEqual( [ true, false, true ] ); + } ); + + it( 'notAvailable follows the analysis', () => { + runInAction( () => { + run[flag] = true; + } ); + const { seen } = observe( () => [ option().canConstraint, option().notAvailable ] ); + run.analysis.setValue( 'FT' ); + expect( seen ).toEqual( [ [ true, false ], [ false, true ] ] ); + } ); + + it( 'isSet needs the toggle and a file', () => { + const { seen } = observe( () => option().isSet ); + run[toggle](); + option().setFilePath( '/data/c.tre' ); + run[toggle](); + option().remove(); + run[toggle](); + // the computed only notifies when its value changes + expect( seen ).toEqual( [ false, true, false ] ); + } ); +} ); diff --git a/src/app/store/writeConcatenatedAlignment.test.js b/src/app/store/writeConcatenatedAlignment.test.js index f06655ea..e641f4db 100644 --- a/src/app/store/writeConcatenatedAlignment.test.js +++ b/src/app/store/writeConcatenatedAlignment.test.js @@ -1,4 +1,5 @@ // @ts-nocheck — Jest globals. checkJs has no test runner types. +import { runInAction } from 'mobx'; import Run from './Run'; it( 'writes one concatenated FASTA', async () => { @@ -8,16 +9,18 @@ it( 'writes one concatenated FASTA', async () => { { path: '/data/a.fasta' }, { path: '/data/b.fasta' }, ] ); - run.alignments[0].sequences = [ - { taxon: 'Homo', code: 'AT' }, - { taxon: 'Mus', code: 'GC' }, - ]; - run.alignments[0].length = 2; - run.alignments[1].sequences = [ - { taxon: 'Homo', code: 'TT' }, - { taxon: 'Mus', code: 'AA' }, - ]; - run.alignments[1].length = 2; + runInAction( () => { + run.alignments[0].sequences = [ + { taxon: 'Homo', code: 'AT' }, + { taxon: 'Mus', code: 'GC' }, + ]; + run.alignments[0].length = 2; + run.alignments[1].sequences = [ + { taxon: 'Homo', code: 'TT' }, + { taxon: 'Mus', code: 'AA' }, + ]; + run.alignments[1].length = 2; + } ); const writeFile = jest.fn( async () => {} ); window.rendererBridge = { writeFile }; diff --git a/src/main/menu/subMenuFile.ts b/src/main/menu/subMenuFile.ts index eb151602..324f2efc 100644 --- a/src/main/menu/subMenuFile.ts +++ b/src/main/menu/subMenuFile.ts @@ -3,7 +3,6 @@ import * as ipc from '../../constants/ipc'; import { appStore } from '../appStore'; import { activeWindow } from '../utils/utils'; -// The page's store class is decorated. This build does not compile decorators. const sendToFocusedWindow = ( channel: string ): void => { const win = activeWindow(); if ( !win ) { diff --git a/src/mobxActionWarning.test.js b/src/mobxActionWarning.test.js new file mode 100644 index 00000000..cff9546e --- /dev/null +++ b/src/mobxActionWarning.test.js @@ -0,0 +1,27 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { observable, runInAction, autorun } from 'mobx'; + +import { actionWarnings } from '../jest/mobxActionWarning'; + +function observed() { + const box = observable.box( 0 ); + const stop = autorun( () => box.get() ); + return { box, stop }; +} + +describe( 'MobX action warning check', () => { + test( 'a write inside runInAction passes', () => { + const { box, stop } = observed(); + runInAction( () => box.set( 1 ) ); + stop(); + expect( actionWarnings() ).toHaveLength( 0 ); + } ); + + test( 'a write outside an action is collected, and would fail the test', () => { + const { box, stop } = observed(); + box.set( 1 ); + stop(); + expect( actionWarnings() ).toHaveLength( 1 ); + actionWarnings().length = 0; // consumed here, so the global afterEach does not fail this proof + } ); +} ); diff --git a/tsconfig.json b/tsconfig.json index 61517d59..0f13d91b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -8,8 +8,7 @@ "lib": ["ESNext", "DOM"], "module": "ESNext", "moduleResolution": "bundler", - "experimentalDecorators": true, - "useDefineForClassFields": false, + "useDefineForClassFields": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": false, diff --git a/yarn.lock b/yarn.lock index e958fc50..108174ca 100644 --- a/yarn.lock +++ b/yarn.lock @@ -684,15 +684,6 @@ "@babel/helper-plugin-utils" "^7.24.7" "@babel/plugin-syntax-decorators" "^7.24.7" -"@babel/plugin-proposal-decorators@^7.29.7": - version "7.29.7" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-decorators/-/plugin-proposal-decorators-7.29.7.tgz#ebc57bd4d711df920a553de8a456a3a020ce0d72" - integrity sha512-EtU0Hi3GvrTqD56xKmZvV/uCXK2ZbwVNPNLAquVItcAZpUhkXwWlo3Fmj0c2LxgSf2I8IDULeAepwNP1OefLXg== - dependencies: - "@babel/helper-create-class-features-plugin" "^7.29.7" - "@babel/helper-plugin-utils" "^7.29.7" - "@babel/plugin-syntax-decorators" "^7.29.7" - "@babel/plugin-proposal-nullish-coalescing-operator@^7.16.0": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-nullish-coalescing-operator/-/plugin-proposal-nullish-coalescing-operator-7.18.6.tgz#fdd940a99a740e577d6c753ab6fbb43fdb9467e1" @@ -726,12 +717,7 @@ "@babel/helper-create-class-features-plugin" "^7.18.6" "@babel/helper-plugin-utils" "^7.18.6" -"@babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2": - version "7.21.0-placeholder-for-preset-env.2" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz#7844f9289546efa9febac2de4cfe358a050bd703" - integrity sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w== - -"@babel/plugin-proposal-private-property-in-object@^7.21.11": +"@babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2", "@babel/plugin-proposal-private-property-in-object@7.21.11", "@babel/plugin-proposal-private-property-in-object@^7.21.11": version "7.21.11" resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.11.tgz#69d597086b6760c4126525cfa154f34631ff272c" integrity sha512-0QZ8qP/3RLDVBwBFoWAwCtgcDZJVwA5LUJRZU8x2YFfKNuFq161wK3cuGrALu5yiPu+vzwTAg/sMWVNeWeNyaw== @@ -776,13 +762,6 @@ dependencies: "@babel/helper-plugin-utils" "^7.24.7" -"@babel/plugin-syntax-decorators@^7.29.7": - version "7.29.7" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-decorators/-/plugin-syntax-decorators-7.29.7.tgz#9a23ab91fb8e61d142684108bca6f343ceee88f6" - integrity sha512-9MTTLbF39X6sqM92JPEsoI7++26hjZvzkxKZy64aMhWLH2mPkJ/Q3AV4QLmls3R14FpSpkOwQQfUh962JGQxxg== - dependencies: - "@babel/helper-plugin-utils" "^7.29.7" - "@babel/plugin-syntax-dynamic-import@^7.8.3": version "7.8.3" resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-dynamic-import/-/plugin-syntax-dynamic-import-7.8.3.tgz#62bf98b2da3cd21d626154fc96ee5b3cb68eacb3" @@ -4528,11 +4507,6 @@ compare-version@^0.1.2: resolved "https://registry.yarnpkg.com/compare-version/-/compare-version-0.1.2.tgz#0162ec2d9351f5ddd59a9202cba935366a725080" integrity sha512-pJDh5/4wrEnXX/VWRZvruAGHkzKdr46z11OlTPN+VrATlWWhSKewNCJ1futCO5C7eJB3nPMFZA1LeYtcFboZ2A== -computed-async-mobx@^4.2.0: - version "4.2.1" - resolved "https://registry.yarnpkg.com/computed-async-mobx/-/computed-async-mobx-4.2.1.tgz#868c899f209af0bcdecaf677abd9bb50f9f39105" - integrity sha512-kThbGHul+3YrXWFfxRJpuHAv9CdEl/UVGI79BmMq3m6UMuWggZq3Hyp2tj1hEe3ZScokTzg+Quxk7X5cN3YKpA== - concat-map@0.0.1: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" @@ -7945,20 +7919,20 @@ mkdirp@^1.0.3: resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== -mobx-react-lite@^2.2.2: - version "2.2.2" - resolved "https://registry.yarnpkg.com/mobx-react-lite/-/mobx-react-lite-2.2.2.tgz#87c217dc72b4e47b22493daf155daf3759f868a6" - integrity sha512-2SlXALHIkyUPDsV4VTKVR9DW7K3Ksh1aaIv3NrNJygTbhXe2A9GrcKHZ2ovIiOp/BXilOcTYemfHHZubP431dg== +mobx-react-lite@^5.1.3: + version "5.1.3" + resolved "https://registry.yarnpkg.com/mobx-react-lite/-/mobx-react-lite-5.1.3.tgz#8ef099ee04332bef4c5b616626bb782341fcb1a6" + integrity sha512-/Qh+wwtyNp9zXXns+B2MxVHC/npHsYvnVJNe0ddvHW4rgAxTOgVr0z/6hWSm2mqdT0jv1QWYZuJ6+3dediv+wQ== -mobx-utils@^5.6.2: - version "5.6.2" - resolved "https://registry.yarnpkg.com/mobx-utils/-/mobx-utils-5.6.2.tgz#4858acbdb03f0470e260854f87e8c2ba916ebaec" - integrity sha512-a/WlXyGkp6F12b01sTarENpxbmlRgPHFyR1Xv2bsSjQBm5dcOtd16ONb40/vOqck8L99NHpI+C9MXQ+SZ8f+yw== +mobx-utils@^6.1.0: + version "6.1.1" + resolved "https://registry.yarnpkg.com/mobx-utils/-/mobx-utils-6.1.1.tgz#61c66563e7646fb75462c189f4110a76d2e35768" + integrity sha512-ZR4tOKucWAHOdMjqElRl2BEvrzK7duuDdKmsbEbt2kzgVpuLuoYLiDCjc3QwWQl8CmOlxPgaZQpZ7emwNqPkIg== -mobx@^5.15.7: - version "5.15.7" - resolved "https://registry.yarnpkg.com/mobx/-/mobx-5.15.7.tgz#b9a5f2b6251f5d96980d13c78e9b5d8d4ce22665" - integrity sha512-wyM3FghTkhmC+hQjyPGGFdpehrcX1KOXsDuERhfK2YbJemkUhEB+6wzEN639T21onxlfYBmriA1PFnvxTUhcKw== +mobx@^7.1.7: + version "7.1.7" + resolved "https://registry.yarnpkg.com/mobx/-/mobx-7.1.7.tgz#12281ff4c4329c0e31bf9ad846b602090bd56c0c" + integrity sha512-fzFPm0u0xHxrAyjFsjfA/a99JgyvLh8R/bnTe7uD37cwbO5O7OUrv/e6Q4rlYdBGCf3rR/pVvh1OVMPF10ghng== ms@2.0.0: version "2.0.0"