#!/usr/bin/env python

# This Python script demonstrates the use of a Models@Home cluster by
# calculating the products 1*1 to 10*10...
# Written by Elmar Krieger, 15.1.2003
# License: Public Domain

# Import the cluster interface
import cluster,os

# ======================================================================
#                      E R R O R   H A N D L I N G
# ======================================================================

# DISPLAY ERROR MESSAGE AND STOP SCRIPT
# =====================================
def error(err):
  print "ERROR - "+err+". Script has been stopped."
  raise SystemExit

# ======================================================================
#                      M A I N   P R O G R A M
# ======================================================================

print "Now calculating the products 1*1 till 10*10 in parallel!!"

# THE JOB QUEUE IS ASSUMED TO BE IN THE PARENT DIRECTORY, INSERT ANY OTHER PATH HERE
joblistname="../cluster.job"

# OPEN THE CLUSTER INTERFACE
job=cluster.job_list(joblistname,error)

# SPAWN 10 MULTIPLICATION JOBS
resultname=[]
for i in range(10):
  resultname.append("result%02d.txt"%(i+1))
  # CLEAR RESULT FILES FROM A PREVIOUS RUN
  if (os.path.exists(resultname[i])): os.remove(resultname[i])
  # ADD THE JOB
  # THE NUMBER TO BE MULTILIPIED IS GIVEN AS COMMAND LINE PARAMETER TO muldemo.c
  job.add(8,"MULDEM","%d |"%(i+1)+os.getcwd()+"|||"+resultname[i]+'|')
# SUBMIT TO MAIN QUEUE AND WAIT FOR RESULTS
job.submit()

# PRINT THE RESULTS
for i in range(10):
  result=int(open(resultname[i]).read())
  print "Cluster returned result for %d*%d: The product is %d." % (i+1,i+1,result)
