def cleanUp():
    # Delete any input/output files from a last run because if these are still hanging around from
    # last time they can really screw things up
    goToSandbox()
    # Remove the input files
    tempfiles = glob.glob("*input")
    for tempfile in tempfiles:
        os.remove(tempfile)
    # Remove the output files
    tempfiles = glob.glob("*output")
    for tempfile in tempfiles:
        os.remove(tempfile)
    tempfiles = glob.glob("*temp")
    for tempfile in tempfiles:
        try:
            os.remove(tempfile)
        except:
            pass
    # Remove the sandbox PDBs
    tempfiles = glob.glob("*.pdb")
    for tempfile in tempfiles:
        os.remove(tempfile)
    # Remove the progress files
    tempfiles = glob.glob("*progress")
    for tempfile in tempfiles:
        os.remove(tempfile)
    # Remove the sandbox archives
    tempfiles = glob.glob("*.ensb")
    for tempfile in tempfiles:
        os.remove(tempfile)
def cleanUp():
    # Delete any input/output files from a last run because if these are still hanging around from
    # last time they can really screw things up
    goToSandbox()
    # Remove the input files
    tempfiles = glob.glob("*input")
    for tempfile in tempfiles:
        os.remove(tempfile)
        # Remove the output files
    tempfiles = glob.glob("*output")
    for tempfile in tempfiles:
        os.remove(tempfile)
    tempfiles = glob.glob("*temp")
    for tempfile in tempfiles:
        try:
            os.remove(tempfile)
        except:
            pass
        # Remove the sandbox PDBs
    tempfiles = glob.glob("*.pdb")
    for tempfile in tempfiles:
        os.remove(tempfile)
        # Remove the progress files
    tempfiles = glob.glob("*progress")
    for tempfile in tempfiles:
        os.remove(tempfile)
        # Remove the sandbox archives
    tempfiles = glob.glob("*.ensb")
    for tempfile in tempfiles:
        os.remove(tempfile)
def importModules(wxpython=False):
    # This is a function for finding and importing modules
    # Sometimes the extra Python packages get installed in weird places, most especially on OSX
    # For Windows, everything is packaged into that Python install so we shouldn't have problems on Windows
    # First let's find out if PYROSETTA_DATABASE is set, and figure out what it should be if not
    if (not (wxpython)):
        try:
            # Is PYROSETTA_DATABASE defined?
            # If not, then we don't know where PyRosetta is and have to look for it
            s = os.environ["PYROSETTA_DATABASE"]
            if (len(s) == 0):
                raise Exception
        except:
            # Let's find it
            # Did we find it already and save it?
            if (platform.system() == "Windows"):
                cfgfile = os.path.expanduser(
                    "~") + "/InteractiveROSETTA/seqwindow.cfg"
            else:
                cfgfile = os.path.expanduser(
                    "~") + "/.InteractiveROSETTA/seqwindow.cfg"
            try:
                f = open(cfgfile.strip(), "r")
                rosettadir = "Not Found"
                rosettadb = "Not Found"
                for aline in f:
                    if ("[ROSETTAPATH]" in aline):
                        rosettapath = aline.split("\t")[1].strip()
                    if ("[ROSETTADB]" in aline):
                        rosettadb = aline.split("\t")[1].strip()
                f.close()
                if (rosettapath == "Not Found"):
                    # It wasn't saved there
                    raise Exception
                else:
                    # Let's try this saved path
                    # On Windows you have to cd to where the folder is to import, because appending to the
                    # path does not appear to work
                    sys.path.append(rosettapath)
                    if (platform.system() == "Windows"):
                        olddir = os.getcwd()
                        os.chdir(rosettapath)
                    os.environ["PYROSETTA_DATABASE"] = rosettadb
                    if (platform.system() == "Windows"):
                        olddir = os.getcwd()
                        os.chdir(olddir)
            except:
                # We didn't save it or the saved location was bad
                # The error may have been the Rosetta import, which means the file needs to be closed
                try:
                    f.close()
                except:
                    pass
                # Tell the user we're busy looking for PyRosetta
                import wx
                busyDlg = wx.BusyInfo(
                    "Searching for PyRosetta installation, please be patient..."
                )
                # Okay, we still didn't get it, so let's traverse the filesystem looking for it...
                foundIt = False
                if (platform.system() == "Windows"):
                    roots = ["C:\\"]
                elif (platform.system() == "Darwin"):
                    # To avoid long searches on Mac
                    roots = ["/Users", "/Applications", "/"]
                else:
                    roots = ["/"]
                for root in roots:
                    for dpath, dnames, fnames in os.walk(root):
                        try:
                            if (platform.system() == "Windows"):
                                # On Windows, we expect the PyRosetta folder to have either rosetta.pyd
                                # or rosetta.dll in the folder
                                try:
                                    indx = fnames.index("rosetta.pyd")  # 64bit
                                except:
                                    indx = fnames.index("rosetta.dll")  # 32bit
                            else:
                                # On Mac/Linux, there should be a libmini file in the folder
                                # On Mac, it's libmini.dylib, on Linux it's libmini.so
                                indx = dnames.index("rosetta")
                                files = glob.glob(dpath + "/rosetta/*libmini*")
                                if (len(files) == 0):
                                    raise Exception
                        except:
                            continue
                        # If we got this far, then we found a candidate PyRosetta folder
                        # Is the database in this folder also?
                        # It is either called "database" or "rosetta_database"
                        foundIt = True
                        rosettapath = dpath
                        for dname in dnames:
                            if ("database" in dname):
                                rosettadb = dpath + "/" + dname
                                break
                        break
                    if (foundIt):
                        break
                busyDlg = None
                if (foundIt):
                    # Let's try to import what we found
                    # Remember on Windows we have to cd
                    sys.path.append(rosettapath)
                    if (platform.system() == "Windows"):
                        olddir = os.getcwd()
                        os.chdir(rosettapath)
                    os.environ["PYROSETTA_DATABASE"] = rosettadb
                    try:
                        # Now let's save these paths so the next time this gets started we don't have to traverse the filesystem again
                        data = []
                        f = open(cfgfile, "r")
                        for aline in f:
                            if (not ("[ROSETTAPATH]" in aline)
                                    and not ("[ROSETTADB]") in aline):
                                data.append(aline.strip())
                        f.close()
                        f = open(cfgfile, "w")
                        for aline in data:
                            f.write(aline + "\n")
                        f.write("[ROSETTAPATH]\t" + rosettapath.strip() + "\n")
                        f.write("[ROSETTADB]\t" + rosettadb.strip() + "\n")
                        f.close()
                        if (platform.system() == "Windows"):
                            olddir = os.getcwd()
                            os.chdir(olddir)
                    except:
                        # Can't find it, it's probably not installed or it's in a hidden location
                        print "PyRosetta cannot be found on your system!"
                        print "Until you install PyRosetta, you may only use InteractiveROSETTA to visualize structures in PyMOL"
                        exit()
    # Attempt to locate other packages that may not be on the PYTHONPATH
    if (platform.system() == "Windows"):
        # We want to import wxPython a bit earlier than the others, to display graphics for the license agreement
        # On Windows, everything should already be in the Python package, so don't try to find anything
        # If there are issues, the user should reinstall InteractiveROSETTA
        if (wxpython):
            import wx
        else:
            import numpy
            import pymol
            import psutil
            #import requests
            import poster
            import Bio
            import openbabel
    else:
        if (platform.system() == "Darwin"):
            # These are the standard locations for some of these things, hopefully we'll get these right away
            # These are the paths that are used in the bash installer
            sys.path.append(
                "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages"
            )
            sys.path.append(
                "/usr/local/Cellar/open-babel/HEAD/lib/python2.7/site-packages"
            )
        # Again, here's the option for either importing wx only, or all the modules
        if (wxpython):
            modules = ["wx"]
        else:
            modules = [
                "numpy", "pymol", "psutil", "poster", "Bio", "openbabel"
            ]
        notfound = []
        # Try to import each of the modules and keep track of which ones throw an error
        for module in modules:
            try:
                mod = __import__(module)
            except:
                notfound.append(module)
        # For everything that is not found, let's first see if we've saved a location and try to import from there
        cwd = os.getcwd()
        goToSandbox()
        for module in notfound:
            keyword = "[" + module.upper() + "PATH]"
            f = open("seqwindow.cfg", "r")
            path = "N/A"
            for aline in f:
                if (keyword in aline):
                    path = aline.split("\t")[1].strip()
                    break
            f.close()
            # Add the saved location to the path
            sys.path.append(path)
            # Try to import again
            try:
                if (path == "N/A"):
                    raise Exception
                mod = __import__(module)
            except:
                # This still didn't work, so now we have to search for it
                print "Could not import " + module + "...  Searching for it..."
                root = "/usr/local"
                foundIt = False
                for dpath, dnames, fnames in os.walk(root):
                    # We're looking for a directory that is the name of the module, on some path that
                    # includes python
                    for dname in dnames:
                        if ((module in dname
                             and os.path.isfile(dpath + "/" + dname +
                                                "/__init__.py"))
                                or module + ".py" in fnames):
                            if ("python3" in dpath):
                                # Sometimes there are duplicates for python3, and trying to import them ruins everything
                                break
                            sys.path.append(dpath)
                            print "Trying " + dpath.strip() + "..."
                            try:
                                # Try to import it again
                                mod = __import__(str(module))
                                # Now let's save these paths so the next time this gets started we don't have to traverse the filesystem again
                                data = []
                                f = open("seqwindow.cfg", "r")
                                for aline in f:
                                    if (not (keyword in aline)):
                                        data.append(aline.strip())
                                f.close()
                                f = open("seqwindow.cfg", "w")
                                for aline in data:
                                    f.write(aline + "\n")
                                f.write(keyword + "\t" + dpath.strip() + "\n")
                                f.close()
                                print "Found " + module + " at " + dpath.strip(
                                ) + "!"
                                foundIt = True
                            except:
                                pass
                            break
                    if (foundIt):
                        break
                if (not (foundIt)):
                    # Explain how to install the packages that are missing
                    print module + " cannot be found on your system!"
                    if (module == "Bio"):
                        print "Install it by executing \"sudo easy_install biopython\" in a terminal."
                    elif (module == "openbabel"
                          and platform.system() == "Darwin"):
                        print "Install it by executing \"brew install mcs07/cheminformatics/open-babel --HEAD --with-python\" in a terminal."
                    elif (module == "openbabel"
                          and platform.system() == "Linux"):
                        print "Install it by executing either \"sudo apt-get install python-openbabel\" or \"sudo yum install openbabel python-openbabel\" in a terminal."
                    elif (module == "wx" and platform.system() == "Darwin"):
                        print "Download and install wxPython from here: http://www.wxpython.org/download.php, wxPython3.0-osx-cocoa-py2.7"
                    elif (module == "wx" and platform.system() == "Linux"):
                        print "Install it by executing either \"sudo apt-get install python-wxgtk2.8\" or \"sudo yum install wxPython\" in a terminal."
                    else:
                        print "Install it by executing \"sudo easy_install " + module + "\" in a terminal."
                    exit()
        if (wxpython):
            import wx
        else:
            import numpy
            import pymol
            import psutil
            #import requests
            import poster
            import Bio
            import openbabel
        os.chdir(cwd)
def cleanUp():
    # Delete any input/output files from a last run because if these are still hanging around from
    # last time they can really screw things up
    goToSandbox()
    if (os.path.isfile("minimizeinput")):
	os.remove("minimizeinput")
    if (os.path.isfile("minimizeoutput")):
	os.remove("minimizeoutput")
    if (os.path.isfile("designinput")):
	os.remove("designinput")
    if (os.path.isfile("designoutput")):
	os.remove("designoutput")
    if (os.path.isfile("scoreinput")):
	os.remove("scoreinput")
    if (os.path.isfile("scoreoutput")):
	os.remove("scoreoutput")
    if (os.path.isfile("scaninput")):
	os.remove("scaninput")
    if (os.path.isfile("scanoutput")):
	os.remove("scanoutput")
    if (os.path.isfile("relaxinput")):
	os.remove("relaxinput")
    if (os.path.isfile("relaxoutput")):
	os.remove("relaxoutput")
    if (os.path.isfile("backrubinput")):
	os.remove("backrubinput")
    if (os.path.isfile("backruboutput")):
	os.remove("backruboutput")
    if (os.path.isfile("rotamerinput")):
	os.remove("rotamerinput")
    if (os.path.isfile("rotameroutput")):
	os.remove("rotameroutput")
    if (os.path.isfile("coarsekicinput")):
	os.remove("coarsekicinput")
    if (os.path.isfile("coarsekicoutput")):
	os.remove("coarsekicoutput")
    if (os.path.isfile("kicoutput")):
	os.remove("kicoutput")
    if (os.path.isfile("repackme.pdb")):
	os.remove("repackme.pdb")
    if (os.path.isfile("finekicinput")):
	os.remove("finekicinput")
    if (os.path.isfile("errreport")):
	os.remove("errreport")
    if (os.path.isfile("coarsedockinput")):
	os.remove("coarsedockinput")
    if (os.path.isfile("finedockinput")):
	os.remove("finedockinput")
    if (os.path.isfile("dockoutput")):
	os.remove("dockoutput")
    if (os.path.isfile("dock_progress")):
	os.remove("dock_progress")
    if (os.path.isfile("threadinput")):
	os.remove("threadinput")
    if (os.path.isfile("threadoutput")):
	os.remove("threadoutput")
    tempfiles = glob.glob("*temp")
    for tempfile in tempfiles:
	try:
	    os.remove(tempfile)
	except:
	    pass
    # Remove the sandbox PDBs
    tempfiles = glob.glob("*.pdb")
    for tempfile in tempfiles:
	os.remove(tempfile)
    # Remove the progress files
    tempfiles = glob.glob("*progress")
    for tempfile in tempfiles:
	os.remove(tempfile)
    # Remove the sandbox archives
    tempfiles = glob.glob("*.ensb")
    for tempfile in tempfiles:
	os.remove(tempfile)
def importModules(wxpython=False):
    # This is a function for finding and importing modules
    # Sometimes the extra Python packages get installed in weird places, most especially on OSX
    # For Windows, everything is packaged into that Python install so we shouldn't have problems on Windows
    # First let's find out if PYROSETTA_DATABASE is set, and figure out what it should be if not
    if (not(wxpython)):
	try:
	    # Is PYROSETTA_DATABASE defined?
	    # If not, then we don't know where PyRosetta is and have to look for it
	    s = os.environ["PYROSETTA_DATABASE"]
	    if (len(s) == 0):
		raise Exception
	except:
	    # Let's find it
	    # Did we find it already and save it?
	    cfgfile = os.path.expanduser("~") + "/InteractiveROSETTA/seqwindow.cfg"
	    try:
		f = open(cfgfile.strip(), "r")
		rosettadir = "Not Found"
		rosettadb = "Not Found"
		for aline in f:
		    if ("[ROSETTAPATH]" in aline):
			rosettapath = aline.split("\t")[1].strip()
		    if ("[ROSETTADB]" in aline):
			rosettadb = aline.split("\t")[1].strip()
		f.close()
		if (rosettapath == "Not Found"):
		    # It wasn't saved there
		    raise Exception
		else:
		    # Let's try this saved path
		    # On Windows you have to cd to where the folder is to import, because appending to the
		    # path does not appear to work
		    sys.path.append(rosettapath)
		    if (platform.system() == "Windows"):
			olddir = os.getcwd()
			os.chdir(rosettapath)
		    os.environ["PYROSETTA_DATABASE"] = rosettadb
		    if (platform.system() == "Windows"):
			olddir = os.getcwd()
			os.chdir(olddir)
	    except:
		# We didn't save it or the saved location was bad
		# The error may have been the Rosetta import, which means the file needs to be closed
		try:
		    f.close()
		except:
		    pass
		# Tell the user we're busy looking for PyRosetta
		import wx
		busyDlg = wx.BusyInfo("Searching for PyRosetta installation, please be patient...")
		# Okay, we still didn't get it, so let's traverse the filesystem looking for it...
		foundIt = False
		if (platform.system() == "Windows"):
		    roots = ["C:\\"]
		elif (platform.system() == "Darwin"):
		    # To avoid long searches on Mac
		    roots = ["/Users", "/Applications", "/"]
		else:
		    roots = ["/"]
		for root in roots:
		    for dpath, dnames, fnames in os.walk(root):
			try:
			    if (platform.system() == "Windows"):
				# On Windows, we expect the PyRosetta folder to have either rosetta.pyd
				# or rosetta.dll in the folder
				try:
				    indx = fnames.index("rosetta.pyd") # 64bit
				except:
				    indx = fnames.index("rosetta.dll") # 32bit
			    else:
				# On Mac/Linux, there should be a libmini file in the folder
				# On Mac, it's libmini.dylib, on Linux it's libmini.so
				indx = dnames.index("rosetta")
				files = glob.glob(dpath + "/rosetta/*libmini*")
				if (len(files) == 0):
				    raise Exception
			except:
			    continue
			# If we got this far, then we found a candidate PyRosetta folder
			# Is the database in this folder also?
			# It is either called "database" or "rosetta_database"
			foundIt = True
			rosettapath = dpath
			for dname in dnames:
			    if ("database" in dname):
				rosettadb = dpath + "/" + dname
				break
			break
		    if (foundIt):
			break
		busyDlg = None
		if (foundIt):
		    # Let's try to import what we found
		    # Remember on Windows we have to cd
		    sys.path.append(rosettapath)
		    if (platform.system() == "Windows"):
			olddir = os.getcwd()
			os.chdir(rosettapath)
		    os.environ["PYROSETTA_DATABASE"] = rosettadb
		    try:
			# Now let's save these paths so the next time this gets started we don't have to traverse the filesystem again
			data = []
			f = open(cfgfile, "r")
			for aline in f:
			    if (not("[ROSETTAPATH]" in aline) and not("[ROSETTADB]") in aline):
				data.append(aline.strip())
			f.close()
			f = open(cfgfile, "w")
			for aline in data:
			    f.write(aline + "\n")
			f.write("[ROSETTAPATH]\t" + rosettapath.strip() + "\n")
			f.write("[ROSETTADB]\t" + rosettadb.strip() + "\n")
			f.close()
			if (platform.system() == "Windows"):
			    olddir = os.getcwd()
			    os.chdir(olddir)
		    except:
			# Can't find it, it's probably not installed or it's in a hidden location
			print "PyRosetta cannot be found on your system!"
			print "Until you install PyRosetta, you may only use InteractiveROSETTA to visualize structures in PyMOL"
			exit()
    # Attempt to locate other packages that may not be on the PYTHONPATH
    if (platform.system() == "Windows"):
	# We want to import wxPython a bit earlier than the others, to display graphics for the license agreement
	# On Windows, everything should already be in the Python package, so don't try to find anything
	# If there are issues, the user should reinstall InteractiveROSETTA
	if (wxpython):
	    import wx
	else:
	    import numpy
	    import pymol
	    import psutil
	    import requests
	    import poster
	    import Bio
	    import openbabel
    else:
	if (platform.system() == "Darwin"):
	    # These are the standard locations for some of these things, hopefully we'll get these right away
	    # These are the paths that are used in the bash installer
	    sys.path.append("/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages")
	    sys.path.append("/usr/local/Cellar/open-babel/HEAD/lib/python2.7/site-packages")
	# Again, here's the option for either importing wx only, or all the modules
	if (wxpython):
	    modules = ["wx"]
	else:
	    modules = ["numpy", "pymol", "psutil", "requests", "poster", "Bio", "openbabel"]
	notfound = []
	# Try to import each of the modules and keep track of which ones throw an error
	for module in modules:
	    try:
		mod = __import__(module)
	    except:
		notfound.append(module)
	# For everything that is not found, let's first see if we've saved a location and try to import from there
	cwd = os.getcwd()
	goToSandbox()
	for module in notfound:
	    keyword = "[" + module.upper() + "PATH]"
	    f = open("seqwindow.cfg", "r")
	    path = "N/A"
	    for aline in f:
		if (keyword in aline):
		    path = aline.split("\t")[1].strip()
		    break
	    f.close()
	    # Add the saved location to the path
	    sys.path.append(path)
	    # Try to import again
	    try:
		if (path == "N/A"):
		    raise Exception
		mod = __import__(module)
	    except:
		# This still didn't work, so now we have to search for it
		print "Could not import " + module + "...  Searching for it..."
		root = "/usr/local"
		foundIt = False
		for dpath, dnames, fnames in os.walk(root):
		    # We're looking for a directory that is the name of the module, on some path that
		    # includes python
		    for dname in dnames:
			if ((module in dname and os.path.isfile(dpath + "/" + dname + "/__init__.py")) or module + ".py" in fnames):
			    if ("python3" in dpath):
				# Sometimes there are duplicates for python3, and trying to import them ruins everything
				break
			    sys.path.append(dpath)
			    print "Trying " + dpath.strip() + "..."
			    try:
				# Try to import it again
				mod = __import__(str(module))
				# Now let's save these paths so the next time this gets started we don't have to traverse the filesystem again
				data = []
				f = open("seqwindow.cfg", "r")
				for aline in f:
				    if (not(keyword in aline)):
					data.append(aline.strip())
				f.close()
				f = open("seqwindow.cfg", "w")
				for aline in data:
				    f.write(aline + "\n")
				f.write(keyword + "\t" + dpath.strip() + "\n")
				f.close()
				print "Found " + module + " at " + dpath.strip() + "!"
				foundIt = True
			    except:
				pass
			    break
		    if (foundIt):
			break
		if (not(foundIt)):
		    # Explain how to install the packages that are missing
		    print module + " cannot be found on your system!"
		    if (module == "Bio"):
			print "Install it by executing \"sudo easy_install biopython\" in a terminal."
		    elif (module == "openbabel" and platform.system() == "Darwin"):
			print "Install it by executing \"brew install mcs07/cheminformatics/open-babel --HEAD --with-python\" in a terminal."
		    elif (module == "openbabel" and platform.system() == "Linux"):
			print "Install it by executing either \"sudo apt-get install python-openbabel\" or \"sudo yum install openbabel python-openbabel\" in a terminal."
		    elif (module == "wx" and platform.system() == "Darwin"):
			print "Download and install wxPython from here: http://www.wxpython.org/download.php, wxPython3.0-osx-cocoa-py2.7"
		    elif (module == "wx" and platform.system() == "Linux"):
			print "Install it by executing either \"sudo apt-get install python-wxgtk2.8\" or \"sudo yum install wxPython\" in a terminal."
		    else:
			print "Install it by executing \"sudo easy_install " + module + "\" in a terminal."
		    exit()
	if (wxpython):
	    import wx
	else:
	    import numpy
	    import pymol
	    import psutil
	    import requests
	    import poster
	    import Bio
	    import openbabel
	os.chdir(cwd)