TestFormat2

Script: testformat2.sh Package: jgi Class: TestFormat.java Last modified: September 26, 2026

Reads the entire file to find extended information about the format and contents. This file analyzer examines sequence files to determine format characteristics, quality metrics, composition statistics, and provides detailed reports for quality assessment and pipeline planning. For GFF, BED, and VCF files it runs format validation checks and reports their limited coverage.

Basic Usage

testformat2.sh <file>

The tool accepts one or more files as input and performs analysis to determine file format, compression, quality metrics, base composition, and various other characteristics important for bioinformatics pipeline planning. Sequence statistics from multiple files are accumulated and printed once; GFF, BED, and VCF validation reports are printed per file.

If a validation or I/O error is detected, the tool prints its results and then exits with a nonzero status. Running with full=f skips full-file analysis and validation entirely.

Parameters

TestFormat2 organizes parameters into functional groups for analysis control and output generation. The tool provides customization options for different analysis depths and output formats.

Analysis Control Parameters

full=t
Process the full file. When true, scans the whole file to gather all statistics and runs the GFF, BED, or VCF validator. When false, only the header-level summary is printed for sequence files (Format, Compression, Interleaved, SortOrder when present, MaxLen, MinLen, AvgLen, StdevLen, ModeLen, QualOffset, NegativeQuals). Validators and the nucleotide or amino acid statistics are not run.
speed=f
Print processing time and throughput statistics. Prints "Time", then reads per second for sequence files, or variants per second for VAR and VCF files.
fast=t
Parsed, but has no effect on output in the current source. The alternate processing path it was intended to control is commented out in TestFormat.java, so statistics are always computed the same way.
slow=f
Inverse of fast: sets the same internal flag to !value. Like fast, it has no effect on output in the current source.

Format Validation Parameters

bedfields=auto
Infer BED3-9 or BED12 standard fields (complete block columns). Set 3-9 or 12 for BEDn+ files; later custom fields are unchecked. Accepted values are auto, 3 through 9, or 12; any other value causes an error. With auto, a valid single-tab interpretation is preferred; otherwise horizontal whitespace is tried. Field counts must agree within each track.

Sequence-Specific Analysis

zmw=t
Parse PacBio ZMW (Zero Mode Waveguide) IDs from sequence headers. Enables ZMW-specific statistics and pass count analysis for PacBio data. Aliases: parseZmw, zmws.
barcodelist=
Optional list of expected barcodes. May be a filename with one line per barcode, or a comma-delimited literal string. Used for barcode validation and statistics. Aliases: expectedbarcodes, expectedindexes, expectedindices, indexlist.
merge=t
Calculate mergability statistics via BBMerge algorithm. Attempts to merge paired reads to determine insert size distributions and adapter contamination. Only pairs where both reads are longer than 10 bases are attempted.
sketch=t
(card) Calculate cardinality via BBSketch. If enabled, also sends the sketch to the RefSeq server for taxonomic identification. Provides genome size estimates and species identification. Alias: card. Required for the khist and zmwhist outputs.
trim=t
Calculate trimmability statistics from quality scores. Simulates quality-based trimming at various thresholds to predict trim rates. Reported at Q5, Q10, Q15, and Q20.
dimer=t
Count 2-mer dimer statistics for nucleotide sequences (Strandedness, AAATRatio, CCCGRatio, HHRatio, PPRatio). Enabled by default. Aliases: dimers, countdimers. The metric definitions are implemented in tracker.KmerTracker, which was not reviewed for this page.
sketchsize=40000
Size of sketch to generate for cardinality estimation. Larger sketches provide more accurate cardinality estimates but require more memory. Accepts K and M suffixes.
bhistlen=10k
Maximum read length for base composition histogram calculation. Reads longer than this value are excluded from bhist.txt. Set to 0 to include all reads. Alias: maxbhistlen.
maxbhistlen=10000
Alias for bhistlen parameter. Controls the maximum read length included in base composition analysis.

Output Control Parameters

printjunk=f
Print headers of junk reads to stdout. Junk reads are those with invalid bases, format errors, or other quality issues.
printbarcodes=f
Print barcode sequences and their occurrence counts to stdout. Useful for validating expected barcode lists and identifying contamination.
printqhist=f
Print quality score histogram to stdout. Shows distribution of quality scores across all bases in the file.
printihist=f
Print insert size histogram to stdout. Derived from paired-read merging analysis when merge=t is enabled.
edist=f
Calculate and report edit distances for barcode analysis. Computes minimum edit distances between observed and expected barcodes. Aliases: calcedist, edits.

File Output Parameters (these can be eliminated by setting to null)

junk=junk.txt
Print headers of junk reads to this file. Contains sequence identifiers for reads that failed quality checks or format validation. Written only when junk reads are found.
barcodes=barcodes.txt
Print barcode analysis results to this file. Includes barcode sequences, counts, and validation results against expected barcode lists.
hist=t
Master switch for histogram file generation. Setting to false will clear all default histogram file outputs (qhist, ihist, khist, bhist, lhist, gchist, zmwhist).
qhist=qhist.txt
Print quality histogram to this file. Contains quality score distributions with frequency counts for each quality value observed.
ihist=ihist.txt
Print insert size histogram to this file. Generated from paired-read overlap analysis and contains insert size frequency distribution.
khist=khist.txt
Print k-mer frequency histogram to this file. Derived from sketch analysis and shows k-mer depth distribution for genome size estimation. Written only when sketch=t.
bhist=bhist.txt
Print base composition histogram to this file. Contains per-read base composition statistics including GC content distribution.
lhist=lhist.txt
Accepted as a parameter, but the current TestFormat.java does not write a length histogram. The code that would collect it is commented out, so no lhist file is produced.
gchist=gchist.txt
Print GC content histogram to this file. Contains detailed GC content distribution statistics for quality assessment. Enables the GCMedian, GCMode, and GCSTDev output lines.
zmwhist=zmwhist.txt
Print ZMW pass count histogram to this file. For PacBio data, shows distribution of how many passes each ZMW had. Written only when sketch=t and zmw=t.

Output Terminology Reference

Format
File format detected (e.g., FASTA, FASTQ, SAM, BAM). Determined by header analysis and content structure.
Compression
Compression format identified (e.g., gzip, bzip2, uncompressed). Important for pipeline processing requirements. Reported as bgzip for bgzip-compressed files.
Interleaved
True if paired reads are stored in a single file with alternating mate pairs. False indicates separate files or unpaired data.
SortOrder
Sort order declared for SAM or BAM input. Printed only when the input is SAM or BAM.
MaxLen
Maximum observed read length in the dataset. Critical for memory allocation and processing parameters.
MinLen
Minimum observed read length in the dataset. Useful for quality filtering and adapter detection.
AvgLen
Mean read length: total bases divided by total reads, printed with two decimals.
StdevLen
Standard deviation of read lengths. Indicates length variability within the dataset.
ModeLen
Most common read length in the dataset. Typically represents the primary sequencing technology read length.
QualOffset
Quality score encoding offset (typically 33 or 64). Essential for proper quality score interpretation. Printed for FASTQ and SAM/BAM input, not FASTA.
NegativeQuals
Number of bases with negative quality scores after offset correction. Indicates potential encoding issues.
Content
Sequence content type classification: Nucleotides or AminoAcids based on character analysis.
Type
Nucleic acid type classification: DNA (no U present), RNA (no T present), or Mixed (both present).
FirstHeader
Header line of the first record in the file.
Reads
Total number of sequence reads processed in the analysis. For amino acid input, reported as Sequences.
-JunkReads
Reads with invalid bases, format errors, or other quality issues that failed validation.
-ChastityFail
Reads failing Illumina's chastity filter as indicated in sequence headers.
-BadPairNames
Paired reads whose sequence identifiers don't match expected pairing patterns.
Bases
Total number of nucleotide bases processed across all reads. For amino acid input, reported as Residues.
-Lowercase
Count of lowercase nucleotide bases. Often indicates low-quality or soft-masked regions.
-Uppercase
Count of uppercase nucleotide bases. Typically indicates high-confidence sequence.
-Non-Letter
Count of non-alphabetic characters in sequence data. May indicate formatting issues.
-FullyDefined
Count of standard nucleotide bases (A, C, G, T, or U). Represents well-defined sequence content.
-No-call
Count of ambiguous 'N' bases where sequencing could not determine the nucleotide.
-Degenerate
Count of valid IUPAC ambiguity codes (other than N) representing multiple possible bases.
-Gap
Count of gap characters (-) in the sequence data.
-Invalid
Count of characters that are not valid sequence symbols according to standard conventions.
-Stop
Count of stop symbols (*) in amino acid sequence data.
GC
GC content calculated as (C+G)/(C+G+A+T+U). Important for sequencing bias assessment and genome characterization.
-GCMedian, -GCMode, -GCSTDev
Median, mode, and standard deviation of per-read GC content. Printed only when the GC histogram is enabled (gchist).
Strandedness, AAATRatio, CCCGRatio, HHRatio, PPRatio
Dimer statistics for nucleotide sequences, printed when dimer=t (the default). Definitions are in tracker.KmerTracker, which was not reviewed for this page.
Cardinality
Approximate number of unique 31-mers in the file, estimated via MinHash sketching. Provides genome size estimates. Printed when sketch=t.
Cardinality_3+
Cardinality estimate computed from k-mers observed at least 3 times. Printed when sketch=t.
Organism
Taxonomic name of the top-matching organism from BBSketch RefSeq server comparison. Printed only when the server returns a result.
TaxID
NCBI Taxonomy ID corresponding to the organism identification from sketch analysis.
Barcodes
Number of unique barcode sequences observed in Illumina-style sequence headers.
ZMWs
Number of unique Zero Mode Waveguide identifiers observed in PacBio sequence data.
Mergable
Percentage of read pairs that successfully overlap and can be merged into single consensus sequences. Printed with a percent sign.
-InsertMean
Average insert size calculated from successfully merged read pairs. Printed only when more than 2% of pairs merge.
-InsertMode
Most common insert size from the merge analysis distribution. Printed only when more than 2% of pairs merge.
-AdapterReads
Percentage of reads containing adapter sequences, detected through overlap analysis. Printed only when more than 2% of pairs merge.
-AdapterBases
Percentage of total bases that represent adapter sequence contamination. Printed only when more than 2% of pairs merge.
-Adapter1, -Adapter2
Adapter sequences derived from overlap analysis, printed when adapter sequences were stored.
QErrorRate
Average estimated error rate derived from quality score analysis across all bases.
-QAvgLog
Logarithmic average of quality scores, providing error-weighted quality assessment.
-QAvgLinear
Linear average of quality scores across all bases in the dataset.
-qMinUncalled, -qMaxUncalled, -qMinCalled, -qMaxCalled
Minimum and maximum quality scores over bases that are uncalled (not A, C, G, or T) and called (A, C, G, or T).
-qScoreRange
Ranges of quality scores that occur in the data, as comma-separated values.
-TrimmedAtQ5
Percentage of bases that would be removed by quality trimming at Q5 threshold.
-TrimmedAtQ10
Percentage of bases that would be removed by quality trimming at Q10 threshold.
-TrimmedAtQ15
Percentage of bases that would be removed by quality trimming at Q15 threshold.
-TrimmedAtQ20
Percentage of bases that would be removed by quality trimming at Q20 threshold.
Qhist
Quality score histogram showing frequency distribution of all quality values observed.
Ihist
Insert size histogram derived from paired-read merging analysis.
BarcodeList
Complete list of observed barcode sequences with occurrence counts.
JunkList
List of sequence headers from reads that failed quality or format validation.
ValidationScope
GFF output only. States which parts of the file were checked and which were not.
FeatureLines, InvalidFeatures, CommentLines, BlankLines, UncheckedFastaLines
GFF output only. Counts of feature lines, lines failing core checks, comment lines, blank lines, and embedded FASTA lines (which are not checked).
HeaderLines, Variants, Ploidy, PairingRate, MapqAvg, QualityAvg, ReadLengthAvg
Variant (VAR) summary output. HeaderLines and Variants count header and data lines; the averages and ploidy are read from "#" header lines in the file, and are printed only when present.

Format Validation

Full-file analysis (full=t, the default) validates three annotation and variant formats instead of computing sequence statistics. Validation is limited to the checks listed below; anything not listed is unchecked, and each report states its scope.

GFF

Checks nine nonempty fields, control characters, positive ordered coordinates, decimal score syntax, strand, and phase (phase is required for CDS features). Attributes, directives, ontology, feature relationships, and embedded FASTA contents are not validated. The report includes FeatureLines, InvalidFeatures, CommentLines, BlankLines, UncheckedFastaLines, and ValidationScope, plus the line number and message of the first error. If any core check fails, or a read, decompression, or close failure occurs, the tool exits nonzero.

BED

Checks standard fields and block structure, and accepts UCSC track headers. Custom columns beyond the standard field count are reported as unchecked. Reference bounds and sorting are not checked. Use bedfields (see Format Validation Parameters) to declare the standard field count for BEDn+ files; the default auto mode infers BED3-9 or BED12.

VCF

Checks VCF4.1 through VCF4.5 headers, column counts, POS, REF, and QUAL syntax, and FORMAT and sample column structure. Blank lines after the version line are tolerated; the final newline is not checked. The following remain unchecked: ALT and GT semantics, INFO, FILTER, and ID semantics, declaration matching, numeric ranges, reference agreement, and sorting.

VAR Summary Files

For VAR files the tool counts variant lines and header lines, and reads the "#" header keys ploidy, pairingRate, totalQualityAvg, mapqAvg, and readLengthAvg. Each value is printed only when its header is present. Variants per second is reported when speed=t.

Multiple Inputs and Mixed Types

Sequence statistics from several files are accumulated and printed once, using the metadata of the last file processed. GFF, BED, and VCF reports are per file, and their metadata does not carry into the sequence summary. In the current source, mixing sequence and VAR inputs suppresses the VAR summary; per-file reporting for mixed inputs is not implemented yet.

Examples

Basic File Analysis

# Analyze a FASTQ file with default settings
testformat2.sh reads.fastq

# Header-level summary only, without full-file analysis
testformat2.sh reads.fastq full=f

# Analysis with timing information
testformat2.sh reads.fastq speed=t

These examples demonstrate basic usage patterns for file format analysis and timing assessment.

Advanced Analysis with Custom Output

# Full analysis with custom histogram files
testformat2.sh reads.fastq qhist=quality_dist.txt ihist=insert_sizes.txt

# Barcode analysis with expected barcode validation
testformat2.sh barcoded_reads.fastq barcodelist=expected_barcodes.txt printbarcodes=t

# PacBio data analysis with ZMW tracking
testformat2.sh pacbio_reads.fastq zmw=t zmwhist=zmw_passes.txt

Advanced examples showing specialized analysis for different data types and custom output configurations.

Quality Assessment and Trimming Simulation

# Quality assessment with trim simulation
testformat2.sh reads.fastq trim=t printqhist=t

# Disable sketching for faster processing of large files
testformat2.sh large_file.fastq sketch=f merge=f

# Keep the default histogram outputs and include reads of all lengths in bhist.txt
testformat2.sh reads.fastq hist=t bhistlen=0

Examples focused on quality control and comprehensive statistical analysis.

Format Validation

# Validate a GFF3 file; exits nonzero if core checks fail
testformat2.sh annotation.gff3

# BED file with a standard BED6 prefix followed by custom columns
testformat2.sh regions.bed bedfields=6

# Validate a VCF file
testformat2.sh variants.vcf

Validation reports state their scope. Attributes, ALT and GT semantics, and reference agreement are not checked; see the Format Validation section.

Algorithm Details

Multi-threaded Analysis Architecture

TestFormat2 runs one worker thread per available thread reported by the runtime (Shared.threads()). When that count is 48 or more, the tool uses min(40, threads/2) workers to limit resource contention. Each worker processes lists of reads from a shared ConcurrentReadInputStream and keeps its own histograms, which are merged after all workers finish.

Format Detection Strategy

The tool uses a dual-phase format detection approach: filename-based initial detection followed by content-based validation. This strategy first examines file extensions and compression indicators, then validates the prediction by analyzing file headers and content structure. Quality offset detection specifically tests both Phred+33 and Phred+64 encodings to ensure accurate quality score interpretation.

Statistical Analysis Methods

Base composition analysis uses specialized lookup tables (toNum, toLUS, toAmino arrays) for high-speed character classification. Quality score statistics employ error probability calculations using QualityTools.PROB_ERROR arrays for accurate error rate estimation. Length statistics utilize SuperLongList data structures optimized for large datasets with efficient median and mode calculations.

Sketching and Cardinality Estimation

When sketching is enabled, the tool implements MinHash sketching through SketchMakerMini with configurable sketch sizes (default 40,000). The sketching algorithm automatically detects PacBio vs Illumina data characteristics and adjusts parameters accordingly. Cardinality estimation uses both simple and 3+ k-mer frequency thresholds for robust genome size estimation, with optional RefSeq server queries for taxonomic identification.

Merging and Insert Size Analysis

Paired-read merging employs the BBMerge.findOverlapLoose algorithm to detect read pair overlaps without requiring perfect matches. The algorithm identifies adapter contamination by comparing successful merge lengths with read lengths, tracking both adapter-containing reads and total adapter bases. Insert size histograms are generated from successful merges with automatic binning optimization.

Quality-Based Trimming Simulation

Trim analysis uses TrimRead.testOptimal for every quality threshold from Q5 through Q20, and reports the Q5, Q10, Q15, and Q20 results. The algorithm employs error probability matrices to determine optimal trim points that balance data retention with quality requirements, providing predictive data for downstream processing decisions.

Memory Management and Scalability

The launcher script passes --xmx=2g, --xms=2g, --percent=42, and --mode=auto to the shared Java argument parser, so heap size follows those defaults unless overridden. Large file processing uses streaming analysis to minimize memory footprint while maintaining statistical accuracy. Histogram arrays are fixed in size: 256 quality bins (offset by 128), 1000 insert size bins, and 51 trim bins.

Error Handling and Data Validation

Each worker, histogram writer, and reader sets a shared error flag on failure. After all output is printed, the tool throws a RuntimeException if the flag is set, which exits with a nonzero status. Validation failures for GFF, BED, and VCF set the same flag. Detected errors are reported in the output so the user can see which checks failed; the output may be incomplete when the tool exits nonzero.

Support

For questions and support: