import sys
import collections
import fasta


try:
	import motility
except:
	print >>sys.stderr, "Error: Cannot find \'motility\' module. Download and install 'motility' from \'http://cartwheel.caltech.edu/motility/\'"

def sites2pwm (sites_file):
	'''Convert Jaspar sites file into PWM. Each site must have the same length. For example:
	>Fox
	AACACTGTGTAAATATGTGGATT
	>Fox
	ATAACTCAGCAAATACGATGGAA
	>Fox
	TTCACTGGATAAATAATGGAAAA
	'''
	sites=collections.defaultdict(list)
	pwm_dict={}
	
	for line in open(sites_file,'r'):
		if line.startswith('#'):continue
		line=line.strip()	
		if line	=='':continue
		line=line.upper()
		if line.startswith('>'):
			motif_id = line.split()[0].replace('>','')	
			continue
		else:
			sites[motif_id].append(line)
	#return sites
	for id in sites:
		pwm_dict[id] = motility.make_pwm(sites[id])
	return pwm_dict
		
def sites2iupac (sites_file):
	'''Convert Jaspar sites file into IUPAC string. Each site must have the same length. For example:
	>Fox
	AACACTGTGTAAATATGTGGATT
	>Fox
	ATAACTCAGCAAATACGATGGAA
	>Fox
	TTCACTGGATAAATAATGGAAAA
	'''
	sites=collections.defaultdict(list)
	iupac_dict={}
	
	for line in open(sites_file,'r'):
		if line.startswith('#'):continue
		line=line.strip()	
		if line	=='':continue
		line=line.upper()
		if line.startswith('>'):
			motif_id = line.split()[0].replace('>','')	
			continue
		else:
			sites[motif_id].append(line)
	#return sites
	for id in sites:
		iupac_dict[id] = motility.make_iupac_motif(sites[id])
	return iupac_dict
	
def pwm_score2prob(pwm,cutoff=0.001):
	'''For a given pwm, calculate pvalue for score. Stop if returned pvalue larger than cutoff'''
	max_score = round(pwm.max_score())
	score2prob={}
	while 1:
		p = pwm.weight_sites_over(max_score)
		score2prob[max_score] = p
		print >>sys.stderr, str(max_score) + '\t' + str(p)
		if p > cutoff:break
		max_score -=1
	return score2prob

def search_motif(seq,motif,mismatch=0):
	'''find iupac motif from seq'''
	mot = motility.find_iupac(seq,motif,mismatches=mismatch)
	return len(mot)
