GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - Pappulab/colgrab: Script which extracts a number of columns from a text file while ignoring headers. Basically awk for those who can't use awk.

BranchesTags
Open more actions menu

Latest commit

 

History

15 Commits
15 Commits

Folders and files

NameName
Last commit message
Last commit date
examples
examples
 
 
src/colgrab
src/colgrab
 
 
tests
tests
 
 
.gitignore
.gitignore
 
 
LICENSE
LICENSE
 
 
README.md
README.md
 
 
pyproject.toml
pyproject.toml
 
 

Repository files navigation

colgrab

Pull numbers out of text files, then print, filter, rescale, summarize or reformat them. It's the handful of things you'd normally reach for awk, sed and cut to do, but with plain command-line options instead of a mini-language you have to look up every time.

It was written for simulation output (CAMPARI, GROMACS, LAMMPS and friends) but it'll work on anything that's lines of columns: whitespace-separated, CSV, TSV, or whatever else you've been handed.

colgrab energy.xvg                      # print column 2
colgrab energy.xvg -c 2-3 --stats all   # summarize columns 2 and 3
colgrab energy.xvg --histogram 50       # histogram column 2

Numbers get converted as they're read, so scientific notation (and Fortran's 1.5D+03) comes out as ordinary floats.

Install

From the top of the repository:

pip install .

That gives you the colgrab command. It needs Python 3.9 or newer and numpy (which pip will pull in for you). If you're going to be editing the code, pip install -e . installs it so that your changes take effect straight away.

Don't want to install it? You can run it straight from a checkout instead:

PYTHONPATH=src python -m colgrab examples/energy.xvg

The basics

The examples below use the two (made-up) files in examples/, so you can run them yourself from the top of the repository.

energy.xvg is laid out the way GROMACS writes energies: some # and @ header lines, then time, potential energy and kinetic energy in columns. With no options you get column 2, and the header lines are skipped for you:

$ colgrab examples/energy.xvg
-34125.0
-34098.0
-34152.0
...

Pick different columns with -c. They come out in the order you ask for them:

# columns 1 and 3, first three rows only
$ colgrab examples/energy.xvg -c 1,3 -r 1-3
0.0 8250.0
10.0 8310.0
20.0 8190.0

-c and -r (rows) understand the same shorthand:

You write You get
2 just number 2
1,3 1 and 3, in that order
2-5 2 through 5
3- 3 through to the end
-3 the start through to 3
last the final one
all everything

Rows are counted from 1 and only rows of data count, so comments and blank lines don't throw the numbering off.

No file? colgrab reads from STDIN, so it slots into a pipeline:

$ grep -v '^[#@]' examples/energy.xvg | colgrab -c last --stats mean,std
# column mean std
3 8260.0 43.474130238568314

Splitting lines into columns

By default columns are separated by any run of spaces or tabs. For anything else use -s, either with a name (comma, tab, space, semicolon, colon, pipe) or with the literal text:

colgrab data.csv -s comma
colgrab data.txt -s '::'

If one separator won't cut it, -S splits on a regular expression:

$ echo 'x = 1.5; y = 2.5' | colgrab -S '\s*[=;]\s*' -c 2,4
1.5 2.5

With an explicit separator an empty field is still a column (so 1,,3 has three columns and nothing shifts sideways). If you'd rather treat repeated separators as one, add --merge-separators.

Choosing which lines count

Option What it does
-i '#@' Lines starting with any of these characters are ignored (this is the default; use -i '' to ignore nothing)
--skip-lines N Throw away the first N lines, whatever's in them
--match REGEX Only use lines containing this regular expression
--exclude REGEX Leave out lines containing this regular expression
-H, --header The first line of data holds column names
--skip-bad-rows Leave out lines that are missing a column or have text where a number should be

Only the columns you actually use are converted to numbers, so text in other columns is fine. If colgrab does hit something that isn't a number it stops and tells you where, rather than quietly dropping it:

$ colgrab examples/chains.csv -s comma -c 2
[FATAL ERROR]: line 1 has 'length' in column 2, which isn't a number (use --skip-bad-rows to leave out lines like this)

Here that's the header line, and --header is the right fix because it lets you use the names:

# rg_nm for every chain longer than 100 residues
$ colgrab examples/chains.csv -s comma -H -c rg_nm --where 'length > 100'
2.72
3.31
3.79

Filtering rows

-r picks rows by position and --every N takes every Nth one, which covers the usual "drop the equilibration, then subsample":

# from row 6 onwards, every second row
$ colgrab examples/energy.xvg -c 1 -r 6- --every 2
50.0
70.0
90.0

--where picks rows by value. Columns are c1, c2, c3... (or their names with --header):

# time and potential energy, for frames with low potential and high kinetic energy
$ colgrab examples/energy.xvg -c 1,2 --where 'c2 < -34120 and c3 > 8200'
0.0 -34125.0
50.0 -34139.0
80.0 -34146.0

You can give --where more than once, in which case a row has to pass all of them. Rows are whittled down in a fixed order: --rows, then --every, then --where.

--where can match text too. Put the text in quotes and compare it with == or !=:

# rg_nm for the chain called chain_b
$ colgrab examples/chains.csv -s comma -H -c rg_nm --where 'name == "chain_b"'
3.31

# length of every chain over 100 residues, apart from chain_b
$ colgrab examples/chains.csv -s comma -H -c length --where 'name != "chain_b" and length > 100'
137.0
111.0

There's nothing to switch on: a column is read as text wherever you compare it with quoted text, and as a number everywhere else. The match is exact, so case matters and "3" doesn't match a field that says 3.0 (leave the quotes off, c2 == 3, for a numeric comparison).

Calculating new columns

-e (or --compute) adds a column worked out from the others:

# time, and potential energy converted from kJ/mol to kcal/mol
$ colgrab examples/energy.xvg -c 1 -e 'c2/4.184' -F .0f -F .2f -r 1-3
0 -8156.07
10 -8149.62
20 -8162.52

Use -e without -c and you get only the computed column. Give it several times for several columns.

A test (rather than a sum) comes out as 1 where it's true and 0 where it isn't, which makes counting easy:

# how many chains are longer than 100 residues?
$ colgrab examples/chains.csv -s comma -H -e 'length > 100' --stats sum --no-labels
3.0

Expressions (for both --where and --compute) are written the way you'd write them in Python:

Arithmetic + - * / // % and ** for powers (not ^)
Comparisons < <= > >= == !=, and chains like 1 < c2 < 5
Logic and, or, not
Text == and != against quoted text, e.g. c1 == "ALA"
Functions abs min max round sqrt exp log log10 log2 sin cos tan floor ceil
Constants pi

If an expression can't be evaluated for some row (dividing by zero, the log of a negative number) colgrab stops and tells you which line of the file did it.

Summarizing

--stats prints statistics instead of the rows. Ask for any of n, mean, std, min, max, median and sum, or just all:

$ colgrab examples/energy.xvg -c 2-3 --stats all
# column n mean std min max median sum
2 10 -34115.5 23.8589605808803 -34152.0 -34076.0 -34113.5 -341155.0
3 10 8260.0 43.474130238568314 8190.0 8330.0 8260.0 82600.0

std is the population standard deviation (it divides by n, the same as numpy.std). Keep in mind that neighbouring frames of a simulation are correlated, so it isn't a shortcut to an error bar.

Statistics work on computed columns too:

# mean, min and max of Re^2/Rg^2 across the chains
$ colgrab examples/chains.csv -s comma -H -e 're_nm**2 / rg_nm**2' --stats mean,min,max -F .2f
# column mean min max
re_nm**2/rg_nm**2 5.54 4.03 6.42

In a shell script you usually want the bare number, which is what --no-labels is for:

$ colgrab examples/energy.xvg --stats mean --no-labels
-34115.5

--histogram BINS prints a histogram: the center of each bin, then the count for each column.

$ colgrab examples/energy.xvg --histogram 4
# bin_center 2
-34142.5 3
-34123.5 2
-34104.5 3
-34085.5 2

The bins run from the smallest to the largest value unless you set them with --bin-range MIN MAX (colgrab tells you if any values fall outside). --density normalizes the histogram so it integrates to 1.

Got a matrix and want to treat it as one long list of numbers? --flatten does that:

$ printf '1 2 3\n4 5 6\n' | colgrab -c all --flatten --stats sum --no-labels
21.0

Formatting the output

Option What it does
-o SEPARATOR What goes between columns (tab, comma... or literal text). A single space by default
-F FORMAT How numbers are written: .3f, 12.4e, or printf-style %.3f
--print-header Write the column names (or numbers) as the first line

By default numbers are written with as many digits as it takes to reproduce them exactly, so nothing is lost. That does mean whole numbers come out as 137.0. Give -F once to format every column the same way, or once per column:

# CSV to tab-separated, keeping the header, with length as an integer
$ colgrab examples/chains.csv -s comma -H -c length,rg_nm -o tab --print-header -F .0f -F .2f
length	rg_nm
137	2.72
163	3.31
81	2.85
93	2.87
111	3.79
56	1.21

--stats and --histogram output starts with a # header line, which colgrab (and gnuplot, xmgrace and numpy.loadtxt) skips, so you can feed the output straight back in.

Messages

Results go to STDOUT. Errors ([FATAL ERROR]: ..., exit status 1) and warnings about anything left out ([WARNING]: ...) go to STDERR, so they never end up mixed into your numbers.

Coming from colgrab v1?

Every v1 command still works: -f, -c, -s, -i and -m do what they did, column 2 is still the default, and -m still prints Mean = <value>. A few things are different:

  • Columns are split on any whitespace by default, so tab-separated files work without -s $'\t'.
  • With an explicit separator (other than a single space) empty fields are kept as columns rather than being squeezed out. Use --merge-separators to get the old behaviour.
  • Blank lines are skipped rather than being a fatal error.
  • Errors are written to STDERR rather than STDOUT.
  • colgrab is now a package you install rather than a single script you copy (see Install above).
  • Numbers in scientific notation are now converted exactly. v1 rebuilt them as mantissa x 10^exponent, which was sometimes off in the 16th significant figure (-5.356694e-01 came out as -0.5356694000000001).

For the full list of options:

colgrab --help

Working on colgrab

The code lives in src/colgrab/, one module per job:

Module What it does
cli.py The command line. The only module that touches argparse, files, or STDIN/STDOUT/STDERR
pipeline.py Strings the stages together: lines of text in, lines of text out
options.py The settings for each stage, as plain dataclasses
reader.py Raw lines to rows of text fields (comments, separators, the header)
selection.py Works out what 1,3-5,last means
expressions.py Parses and evaluates --where / --compute expressions
numeric.py Rows of text fields to arrays of numbers
summaries.py Statistics and histograms
formatting.py Numbers to lines of text
separators.py The separator names (tab, comma...) shared by -s and -o
errors.py The exception colgrab raises when it can't do what you asked

Each module has a matching file in tests/. The tests run against the source tree, so there's nothing to install first:

pytest

About

Script which extracts a number of columns from a text file while ignoring headers. Basically awk for those who can't use awk.

Resources

Readme
GPL-2.0 license
Activity
Custom properties

Stars

1 star

Watchers

1 watching

Forks

0 forks
Report repository

Releases

Packages

Contributors

Languages

You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.