#!/usr/bin/env python
#
# Copyright John Reid 2012
#

"""
Randomises the columns of PWMs.
"""

import logging
logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s - %(levelname)s - %(message)s")
from cookbook.script_basics import log_options
from optparse import OptionParser
import stempy
import stempy.meme_parse
import numpy
import sys
import os


#
# Parse options and arguments from command line
#
sys.argv = [a.encode(sys.stdin.encoding or 'ascii') for a in sys.argv]
parser = OptionParser()
parser.add_option(
    "--seed",
    type="int",
    default=0,
    metavar='SEED',
    help="Seed the random number with SEED."
)
options, args = parser.parse_args()
log_options(parser, options)


#
# Check we have the correct number of arguments
#
if len(args) != 2:
    raise RuntimeError(
        'USAGE: %s <options> input-motifs output-motifs', sys.argv[0])
input_motifs_filename = args.pop(0)
output_motifs_filename = args.pop(0)


#
# Load the motifs
#
meme_info = stempy.meme_parse.do_parse_and_extract(
    open(input_motifs_filename).read())
motifs = meme_info.motifs
logging.info('Loaded %d motifs from: %s', len(motifs), input_motifs_filename)


#
# Seed numpy if requested
#
if options.seed:
    logging.info('Using seed for random number generator: %d', options.seed)
    numpy.random.seed(options.seed)


#
# Randomise motifs
#
for i, motif in enumerate(motifs):
    logging.info('Motif %2d W=%2d (%s)', i, W, motif.name)
    motif.letter_probs.values[:] = numpy.random.permutation(
        motif.letter_probs.values)
    # print motif.letter_probs.values.sum(axis=1) # check these are 1.


#
# Write motifs out
#
logging.info('Writing randomised motifs to: %s', output_motifs_filename)
stempy.meme_parse.write_pwms(open(output_motifs_filename, 'w'), meme_info)
