diff --git a/src/app/store/Alignment.ts b/src/app/store/Alignment.ts index 6d8e3986..bb7c0911 100644 --- a/src/app/store/Alignment.ts +++ b/src/app/store/Alignment.ts @@ -46,7 +46,7 @@ interface AlignmentOwner { substitutionRate: SettableOption; substitutionMatrix: SettableOption; alignments: Alignment[]; - dataType: string; + dataType: string | undefined; error: unknown; afterRun: () => void; removeAlignment: ( alignment: Alignment ) => void; @@ -215,7 +215,8 @@ class Alignment extends InputFile { case 'multistate': return 'MULTI'; default: - return this.dataType; + // '' until the alignment is parsed. + return this.dataType ?? ''; } } @@ -292,15 +293,24 @@ class Alignment extends InputFile { ); return; } + const { dataType } = this; + // dataType check narrows for the compiler; modelTestCanRun already excludes undefined. + if ( !this.modelTestCanRun || dataType === undefined ) { + return; + } + const binaryName = this.run.modeltestName; + if ( binaryName === undefined ) { + throw new Error( 'No modeltest binary in the binaries list' ); + } this.modeltestLoading = true; const { rendererBridge } = window; await rendererBridge.startModelSelection( { id: this.id, filePath: this.path, outputDir: this.run.outputDir, - dataType: this.dataType, + dataType, numThreads: this.run.numThreads.value, - binaryName: this.run.modeltestName, + binaryName, } ); }; @@ -320,14 +330,17 @@ class Alignment extends InputFile { 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] ); + const frequencies = raxmlNG.match( /\+F[O|E]?/ ); + if ( frequencies ) { + this.ngStationaryFrequencies.setValue( frequencies[0] ); } - if ( /\+IC?/.test( raxmlNG ) ) { - this.ngInvariantSites.setValue( /\+IC?/.exec( raxmlNG )[0] ); + const invariantSites = raxmlNG.match( /\+IC?/ ); + if ( invariantSites ) { + this.ngInvariantSites.setValue( invariantSites[0] ); } - if ( /\+GA?/.test( raxmlNG ) ) { - this.ngRateHeterogeneity.setValue( /\+GA?/.exec( raxmlNG )[0] ); + const rateHeterogeneity = raxmlNG.match( /\+GA?/ ); + if ( rateHeterogeneity ) { + this.ngRateHeterogeneity.setValue( rateHeterogeneity[0] ); } if ( /\+ASC_LEWIS/.test( raxmlNG ) ) { this.ngAscertainmentBias.setValue( '+ASC_LEWIS' ); @@ -350,7 +363,8 @@ class Alignment extends InputFile { console.log( 'parsing matrix name...' ); const { options } = raxmlSettings.aminoAcidSubstitutionMatrixOptions; const re = new RegExp( `(${options.join( '|' )})$` ); - const matrixName = re.exec( model )[1]; + // Null on an unlisted matrix throws a TypeError, as before; #403 owns that case. + const matrixName = re.exec( model )![1]; this.aaMatrixName = matrixName; model = model.replace( re, '' ); } @@ -396,11 +410,10 @@ class Alignment extends InputFile { try { const parsed = await rendererBridge.parseAlignment( this.id, this.path ); const { alignment, change } = parsed; - const newDataType = getFinalDataType( - this.run.alignments - .map( ( { dataType } ) => dataType ) - .concat( alignment.dataType ), - ); + const newDataType = getFinalDataType( [ + ...this.run.alignments.map( ( { dataType } ) => dataType ), + alignment.dataType, + ] ); runInAction( () => { if ( this.run.dataType !== newDataType ) { this.run.substitutionMatrix.value = @@ -422,8 +435,8 @@ class Alignment extends InputFile { if ( change ) { this.path = change.newFilePath; this.convertedFrom = change.format; - this.converted = change.converted; - this.modified = change.modified; + this.converted = change.converted ?? false; + this.modified = change.modified ?? false; this.modificationMessages = change.modificationMessages; if ( change.modificationMessages.length > 0 ) { this.showModifiedDialog = true; diff --git a/src/app/store/AlignmentOptions.ts b/src/app/store/AlignmentOptions.ts index fa86cae1..436fcc14 100644 --- a/src/app/store/AlignmentOptions.ts +++ b/src/app/store/AlignmentOptions.ts @@ -18,7 +18,7 @@ interface RunLike { interface AlignmentLike { run: RunLike; - dataType: string; + dataType: string | undefined; hasInvariantSites: boolean; multistateNumber: { value: string }; } @@ -35,7 +35,7 @@ class RaxmlNgAlignmentSubstitutionModel extends Option { this.alignment = alignment; } get options(): Choice[] { - if ( !this.alignment.run.haveAlignments ) { + if ( !this.alignment.run.haveAlignments || this.alignment.dataType === undefined ) { return []; } const modelSettings = ( raxmlNgModelOptions as Record )[this.alignment.dataType]; diff --git a/src/app/store/InputFile.ts b/src/app/store/InputFile.ts index 3c75805e..3ccbed72 100644 --- a/src/app/store/InputFile.ts +++ b/src/app/store/InputFile.ts @@ -8,7 +8,7 @@ interface InputFileOwner { } class InputFile extends StoreBase { - run: Owner = null; + run: Owner; constructor( run: Owner, path: string ) { super(); diff --git a/src/app/store/Option.ts b/src/app/store/Option.ts index 81d95bf6..528ad41c 100644 --- a/src/app/store/Option.ts +++ b/src/app/store/Option.ts @@ -13,8 +13,8 @@ class Option { run: Owner; defaultValue: Value; title: string; - description: string; - hoverInfo: string; + description: string | undefined; + hoverInfo: string | undefined; schema: Schema; allowOnlyValidChange: boolean; helperText: string; diff --git a/src/app/store/PartOptions.ts b/src/app/store/PartOptions.ts index aad62b71..2a0d8da4 100644 --- a/src/app/store/PartOptions.ts +++ b/src/app/store/PartOptions.ts @@ -16,7 +16,7 @@ interface Choice { interface AlignmentLike { run: unknown; - dataType: string; + dataType: string | undefined; partitionType: string; length: number; partition: { partToAdd: { type: { value: string } } }; @@ -85,6 +85,9 @@ class PartType extends PartBase { } get options(): Choice[] { const { dataType } = this.alignment; + if ( dataType === undefined ) { + return []; + } let opts = [dataType]; if ( dataType === '' || dataType === 'mixed' ) { opts = ['DNA', 'BIN', 'MULTI', 'protein']; @@ -156,7 +159,7 @@ class PartEnd extends PartBase { name: 'part-end', message: () => `Must be in interval [${this.min}, ${this.max}]`, test: ( value ) => { - return value >= this.min && value <= this.max; + return value !== undefined && value >= this.min && value <= this.max; }, } ), allowOnlyValidChange: false, diff --git a/src/app/store/Partition.ts b/src/app/store/Partition.ts index de45ae2a..2739d9b1 100644 --- a/src/app/store/Partition.ts +++ b/src/app/store/Partition.ts @@ -15,7 +15,7 @@ interface PartitionAlignment { // Read by the part options, which this file hands each part to. run: unknown; partition: Partition; - dataType: string; + dataType: string | undefined; partitionType: string; aaMatrixName: string; length: number; @@ -30,7 +30,7 @@ interface PartValues { codon: string; } -const getPartitionType = ( dataType: string, aaMatrixName = 'BLOSUM62' ): string => { +const getPartitionType = ( dataType: string | undefined, aaMatrixName = 'BLOSUM62' ): string => { // for old raxml switch ( dataType ) { case 'dna': @@ -43,7 +43,8 @@ const getPartitionType = ( dataType: string, aaMatrixName = 'BLOSUM62' ): string case 'multistate': return 'MULTI'; default: - return dataType; + // '' until the alignment is parsed. + return dataType ?? ''; } }; diff --git a/src/app/store/Run.ts b/src/app/store/Run.ts index 1674acf0..6b55b8ca 100644 --- a/src/app/store/Run.ts +++ b/src/app/store/Run.ts @@ -36,6 +36,7 @@ import { MultifurcatingConstraintTree, } from './RunOptions'; import type { AnalysisChoice } from './RunOptions'; +import type { DataType } from '../../common/typecheckAlignment'; import { basename, join, quote } from '../paths'; import remove from 'lodash/remove'; import UserFixError from '../../common/errors'; @@ -207,10 +208,14 @@ class Run extends StoreBase { } get analysisOption(): AnalysisChoice { - return this.raxmlNgSwitch( + const option = this.raxmlNgSwitch( raxmlNgAnalysisOptions.find( ( opt ) => opt.value === this.analysis.value ), analysisOptions.find( ( opt ) => opt.value === this.analysis.value ), ); + if ( !option ) { + throw new Error( `No analysis option for analysis '${this.analysis.value}'` ); + } + return option; } // Analysis params @@ -362,7 +367,7 @@ class Run extends StoreBase { : []; } - get dataType(): string { + get dataType(): DataType | undefined { return this.finalAlignment.dataType; } @@ -536,7 +541,7 @@ class Run extends StoreBase { return null; } const convertedAlignments = this.alignments.filter( ( a ) => a.converted ); - return convertedAlignments[0].convertedFrom; + return convertedAlignments[0].convertedFrom ?? null; } clearShowModified = (): void => { @@ -567,7 +572,9 @@ class Run extends StoreBase { astralArgs = (): string[][] => { const first: string[] = []; - first.push( '-i', quote( this.astralTree?.path, { windows } ) ); + if ( this.astralTree ) { + first.push( '-i', quote( this.astralTree.path, { windows } ) ); + } first.push( '-o', quote( join( this.outputDir, `ASTRAL_${this.outputNameSafe}.tre` ), { windows } ), diff --git a/src/app/store/RunOptions.ts b/src/app/store/RunOptions.ts index 091d55ff..2d5696d5 100644 --- a/src/app/store/RunOptions.ts +++ b/src/app/store/RunOptions.ts @@ -18,7 +18,7 @@ interface RunOwner { finalAlignment: { hasInvariantSites: boolean }; taxons: string[]; haveAlignments: boolean; - dataType: string; + dataType: string | undefined; usesRaxmlNg: boolean; usesModeltestNg: boolean; useBackboneConstraint: boolean; @@ -528,7 +528,7 @@ export class SubstitutionMatrix extends Option { } ); } get options(): Choice[] { - if ( !this.run.haveAlignments ) { + if ( !this.run.haveAlignments || this.run.dataType === undefined ) { return []; } const modelSettings = ( raxmlMatrixOptions as Record )[this.run.dataType]; diff --git a/src/app/store/StoreBase.ts b/src/app/store/StoreBase.ts index b0689e00..d6b4f164 100644 --- a/src/app/store/StoreBase.ts +++ b/src/app/store/StoreBase.ts @@ -40,7 +40,7 @@ export default class StoreBase { unlisten = (): void => { while ( this.eventStops.length ) { - this.eventStops.pop()(); + this.eventStops.pop()?.(); } }; diff --git a/src/common/io.ts b/src/common/io.ts index f8b2e677..bef2d216 100644 --- a/src/common/io.ts +++ b/src/common/io.ts @@ -4,6 +4,9 @@ import util from 'util'; import phylipParser from './phylipParser'; import fastaParser from './fastaParser'; import typecheckAlignment from './typecheckAlignment'; +import type { TypecheckedAlignment } from './typecheckAlignment'; +import type { FastaAlignment } from './fastaParser'; +import type { PhylipAlignment } from './phylipParser'; import UserFixError from './errors'; interface AlignmentSequence { @@ -16,7 +19,7 @@ interface Alignment { length: number; } -export const parseAlignment = async ( filePath: string ): Promise => { +export const parseAlignment = async ( filePath: string ): Promise => { try { await fs.promises.access( filePath ); } catch ( err: unknown ) { @@ -32,7 +35,7 @@ export const parseAlignment = async ( filePath: string ): Promise => } ); const lines: string[] = []; let error: Error | null = null; - let alignment: Alignment | null = null; + let alignment: FastaAlignment | PhylipAlignment | null = null; rl.on( 'line', ( line ) => { lines.push( line ); } ).on( 'close', () => { @@ -55,17 +58,18 @@ export const parseAlignment = async ( filePath: string ): Promise => if ( !alignment || alignment.sequences.length === 0 ) { return reject( new Error( `Couldn't parse any sequences from file ${filePath}` ) ); } + let typechecked: TypecheckedAlignment; try { - typecheckAlignment( alignment ); + typechecked = typecheckAlignment( alignment ); } catch ( err: unknown ) { console.error( 'Error checking data type:', err ); return reject( err ); } - const alignmentRestricted = Object.assign( {}, alignment, { - sequences: alignment.sequences.slice( 0, 2 ), + const alignmentRestricted = Object.assign( {}, typechecked, { + sequences: typechecked.sequences.slice( 0, 2 ), } ); console.log( 'Alignment with first two sequences:', alignmentRestricted ); - resolve( alignment ); + resolve( typechecked ); } } ); } ); @@ -91,7 +95,7 @@ export const writeAlignment = async ( filePath: string, alignment: Alignment ): }; interface Io { - parseAlignment: ( filePath: string ) => Promise; + parseAlignment: ( filePath: string ) => Promise; writeAlignment: ( filePath: string, alignment: Alignment ) => Promise; } diff --git a/src/common/typecheckAlignment.test.ts b/src/common/typecheckAlignment.test.ts new file mode 100644 index 00000000..4b397749 --- /dev/null +++ b/src/common/typecheckAlignment.test.ts @@ -0,0 +1,23 @@ +import { expect, it } from 'vitest'; +import typecheckAlignment from './typecheckAlignment'; + +const alignment = ( ...codes: string[] ) => ( { + sequences: codes.map( ( code, i ) => ( { taxon: `t${i}`, code } ) ), + length: codes[0].length, + numSequences: codes.length, + fileFormat: 'FASTA', +} ); + +it( 'typecheckAlignment sets the data type, invariant sites and completion', () => { + expect( typecheckAlignment( alignment( 'ACGT', 'ACGA' ) ) ).toMatchObject( { + dataType: 'nucleotide', + hasInvariantSites: true, + typecheckingComplete: true, + } ); +} ); + +it( 'typecheckAlignment throws when no sequence has a data type', () => { + expect( () => typecheckAlignment( alignment( 'TT-T', '----' ) ) ).toThrow( + 'cannot determine data type of any of the 2 sequences', + ); +} ); diff --git a/src/common/typecheckAlignment.ts b/src/common/typecheckAlignment.ts index cdf6d364..830e2f81 100644 --- a/src/common/typecheckAlignment.ts +++ b/src/common/typecheckAlignment.ts @@ -5,12 +5,23 @@ export type DataType = 'protein' | 'nucleotide' | 'multistate' | 'binary' | 'mix export interface TypecheckableAlignment { sequences: { taxon: string; code: string; dataType?: DataType }[]; length: number; + numSequences: number; + fileFormat: string; hasInvariantSites?: boolean; dataType?: DataType; typecheckingComplete?: boolean; } -export const getFinalDataType = ( dataTypes: ( DataType | undefined )[] ): DataType | undefined => { +export type TypecheckedAlignment = T & { + dataType: DataType; + hasInvariantSites: boolean; + typecheckingComplete: boolean; +}; + +// A list that ends in a parsed alignment's data type always has a final data type. +export function getFinalDataType( dataTypes: [...( DataType | undefined )[], DataType] ): DataType; +export function getFinalDataType( dataTypes: ( DataType | undefined )[] ): DataType | undefined; +export function getFinalDataType( dataTypes: ( DataType | undefined )[] ): DataType | undefined { const notUndefinedTypes = dataTypes.filter( ( d ) => d !== undefined ); if ( notUndefinedTypes.length === 0 ) { return undefined; @@ -28,7 +39,7 @@ export const getFinalDataType = ( dataTypes: ( DataType | undefined )[] ): DataT } } return firstType; -}; +} // Valid characters taken from Standard-RAxML (axml.c) const reInvalidBinary = /[^01-?]/g; const reInvalidDNA = /[^ABCDGHKMRSTUVWYNOX?-]/gi; @@ -77,7 +88,7 @@ function hasInvariantSites( length: number, sequences: TypecheckableAlignment['s } return false; } -export default function typecheckAlignment( alignment: T ): T { +export default function typecheckAlignment( alignment: T ): TypecheckedAlignment { const acgMatch = /[ACGN?]/i; // Include 'N' and '?' as symbols for missing characters in DNA // const proteinMatch = /[RNDEQHILKMFPSWYVXBZJ]/i; const proteinMatch = /[EFJIJLOPQZX]/i; @@ -151,8 +162,13 @@ export default function typecheckAlignment( al throw new UserFixError( `Invalid character '${seq.code[invalidSiteIndex]}' at site ${invalidSiteIndex + 1} in sequence ${index + 1} (${sample}) for inferred data type '${dataType}'` ); } } ); - alignment.hasInvariantSites = hasInvariantSites( alignment.length, alignment.sequences ); - alignment.dataType = dataType; - alignment.typecheckingComplete = true; - return alignment; + if ( dataType === undefined ) { + // Every sequence matched no data type, for example only 'T' or '-'. + throw new UserFixError( `Invalid alignment: cannot determine data type of any of the ${numSequencesTypechecked} sequences` ); + } + return Object.assign( alignment, { + hasInvariantSites: hasInvariantSites( alignment.length, alignment.sequences ), + dataType, + typecheckingComplete: true, + } ); } diff --git a/src/main/parseAlignment.ts b/src/main/parseAlignment.ts index 53e55a39..2d185544 100644 --- a/src/main/parseAlignment.ts +++ b/src/main/parseAlignment.ts @@ -1,22 +1,14 @@ import path from 'path'; -import type { DataType } from '../common/typecheckAlignment'; +import type { TypecheckedAlignment } from '../common/typecheckAlignment'; export interface AlignmentSequence { taxon: string; code: string; } -// Optional fields: the parsers and typecheck add them, io.parseAlignment does not declare them. -export interface Alignment { - sequences: AlignmentSequence[]; - length: number; - numSequences?: number; - fileFormat?: string; - dataType?: DataType; - hasInvariantSites?: boolean; - typecheckingComplete?: boolean; -} +// What io.parseAlignment resolves: parsed, then typechecked. +export type Alignment = TypecheckedAlignment; interface AlignmentParseTools { readFormat: ( filePath: string ) => Promise;