I have a file containing lines like:

tree my_tree = ((t1:961.00,t2:902.00):961:00,t3:878:00);

which represents a tree structure with branch lengths. I want to multiply all branch lengths in each line, i.e. numbers after:, by (preferably unique) random numbers between 0 and 1. Also it would be great if there is any random number generator utility in which the distribution can be specified, say normal with given mean and standard deviation.

I know how to generate random numbers with, say, $RANDOM or shuf whithin a specific range >1. I also know how to replace a regex with sed in file sed -i 's/:[0-9\.]+/My_RANDOM_NUMBER/g' my_file. But I'm still struggling to achieve the task.



I'd use something like perl or awk that can handle arithmetic operations, rather than sed (which can only really do regular expression replacement).

For example, using perl

$ printf 'tree my_tree = ((t1:961.00,t2:902.00):961:00,t3:878:00);\n' | 
    perl -pe 's/:([0-9.]+)/sprintf ":%.2f", $1*rand()/ge'
tree my_tree = ((t1:918.95,t2:880.40):633.34:0.00,t3:648.35:0.00);

You can replace perl's rand() by another random library function of your choice - for example, using Math::Random from the libmath-random-perl package:

$ printf 'tree my_tree = ((t1:961.00,t2:902.00):961:00,t3:878:00);\n' | 
  perl -MMath::Random=random_normal -pe 's/:([0-9.]+)/sprintf ":%.2f", $1*random_normal(0.0, 1.0)/ge'
tree my_tree = ((t1:-362.08,t2:822.35):-254.87:0.00,t3:1158.46:0.00);
  • Is there also any way I can restrict the numbers generated from Math::Random=randome_normal to be only positive? i.e. numbers are drawn from the positive side of, for example, N(0,1) distribution. – havij Jul 30 '16 at 20:16
  • 1
    I'm not aware of a way to restrict them - but you could take the absolute value $1*abs(random_normal(0.0, 1.0)) – steeldriver Jul 30 '16 at 20:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.