#!/usr/bin/python
import os, sys, pickle, commands
import numpy as np

########################################

name 	= "g0.1_epsrp_100orb"
binary	= "nbody"
N_mpi	= 200
g	= 0.1

########################################


try:
	os.mkdir(name)
except:
	print "Did not create directory/files in '%s' (already exists?)." % name

os.chdir(name)
try:
	os.symlink("../%s" % (binary),"nbody")
	os.symlink("../mpi_execute.bash","mpi_execute.bash")
	os.symlink("../run_queue.python","run_queue.python")
except:
	print "Cannot create symlinks (already exist?)"

########################################
print "Constructing job queue."
queue	= []
for eps in np.arange(0.0,0.99,0.015):
	for rp in np.arange(0.1,1.3,0.04):
		command	= "./nbody %e %e %e >/dev/null" % (g,rp,eps)
		ident	= "%e\t%e\t%e" % (g,rp,eps)
		simulation = [command, ident]
		queue.append(simulation);


N = len(queue)
N_permpi = N/N_mpi
print "Computing %d jobs on %d MPI jobs. That's about %d jobs per MPI job." % (N,N_mpi,N_permpi)
if N<N_mpi:
	print "More MPI jobs than real jobs. Exiting."
	sys.exit(1)

print "Creating job files."
for i in range(0,N_mpi):
	f = open("jobs_%09d.pkl" % (i),"wb")
	
	if i<N_mpi-1:
		output = queue[i*N_permpi:(i+1)*N_permpi]
	else:
		output = queue[i*N_permpi:]
	pickle.dump(output,f)
	f.close()

print "Submitting jobs."
curdir = commands.getoutput("pwd")
for i in range(0,N_mpi):
	sys.stdout.flush()
	os.system("qsub -N python%09d -d %s mpi_execute.bash" % (i,curdir))

print "\n\nDone."



		
