Example #1
0
File: u.py Project: 4thguy/trelby
def init():
    global initDone

    if not initDone:
        misc.init(False)
        util.init(False)

        initDone = True
Example #2
0
def init():
    global initDone

    if not initDone:
        misc.init(False)
        util.init(False)

        initDone = True
Example #3
0
#!/usr/bin/env python

"""
Autoinitialize CUDA tools.
"""

import misc
try:
    import cula
    _has_cula = True
except (ImportError, OSError):
    _has_cula = False

misc.init()
if _has_cula:
    cula.culaInitialize()
Example #4
0
def run(move_type,
        n_moves,
        length_poly,
        generate_gif=False,
        lamellar=False,
        temp=None,
        field=1,
        output_directory=None):
    """
    Runs a simulation with specified move type and number of moves

    Arguments:
    move_type -- pivot or reptation
    n_moves -- number of moves in simulation
    length_poly -- number of monomers in the polymer
    generate_gif -- generate images of each step and make a gif at the end of execution (takes a while)
    lamellar -- boolean, lamellar field on or off
    temp -- temperature, only if lamellar is on
    field -- field strength, if lamellar is turned on
    output_directory -- where you would like to output the run
    """

    #Declaring global variables for multi-runs:
    global avg_energy
    global avg_gyradius
    global avg_gyradius_x
    global avg_gyradius_y
    global avg_end2end
    global avg_end2end_x
    global avg_end2end_y

    ######################
    ### Initialization ###
    ######################

    if output_directory == None:
        print("Error! Output directory not specified. Exiting...")
        exit(1)

    #Check if move type is valid
    if move_type not in ['reptation', 'pivot']:
        print("Move type is not reptation or pivot... exiting")
        exit(1)

    if lamellar == True:
        if temp == None:
            print(
                "lamellar field requires a temperature. Please specify (temp = ...). Exiting..."
            )
            exit(1)

    #Prepare gif process
    if generate_gif == True:
        prepare_gif_process()

    #Initialize polymer and grid
    poly = init(length_poly)

    if generate_gif == True:
        grid = imaging.grid(poly)

    #Initialize arrays to store energy, gyradius and end2end distance
    energies = np.empty(0)

    gyradii = np.empty(0)
    gyradii_x = np.empty(0)
    gyradii_y = np.empty(0)

    end2ends = np.empty(0)
    end2ends_x = np.empty(0)
    end2ends_y = np.empty(0)

    if lamellar == True:
        charges = generate_coblock_charges(poly.shape[0])

    ########################
    #### Run Simulation ####
    ########################

    #Run algorithm:
    for i in range(0, n_moves + 1):

        #Write original polymer to memory if lamellar is on:
        if lamellar == True:
            poly1 = poly

        #Make a move:
        if move_type == 'reptation':
            poly = reptation(poly)
        else:
            poly = pivot(poly)

        #If lamellar is on, compare energies of original and moved polymers:
        if lamellar == True:
            poly2 = poly
            poly, energy = lamellar_test(poly1,
                                         poly2,
                                         charges,
                                         temp,
                                         field=field)

        #Calculate observables
        if lamellar != True:
            energy = 0

        gyradius, gyradius_x, gyradius_y = radius_of_gyration(poly)
        end2end, end2end_x, end2end_y = end_to_end(poly)

        #Append observables to arrays
        energies = np.append(energies, np.array([energy]))

        gyradii = np.append(gyradii, np.array([gyradius]))
        gyradii_x = np.append(gyradii_x, np.array([gyradius_x]))
        gyradii_y = np.append(gyradii_y, np.array([gyradius_y]))

        end2ends = np.append(end2ends, np.array([end2end]))
        end2ends_x = np.append(end2ends_x, np.array([end2end_x]))
        end2ends_y = np.append(end2ends_y, np.array([end2end_y]))

        #Save images for gif upon request
        if generate_gif == True:
            if lamellar == True:
                img = grid.plot_poly(poly,
                                     energy=energy,
                                     gyradius=np.round(gyradius, 2),
                                     end2end=np.round(end2end, 2),
                                     lamellar=True,
                                     charges=charges)
            else:
                img = grid.plot_poly(poly,
                                     energy=energy,
                                     gyradius=np.round(gyradius, 2),
                                     end2end=np.round(end2end, 2))
            save_img(img)

    #########################################
    #### Plot and Calculate Observables  ####
    #########################################

    #Generate plots of observables over the algorithm
    plot(energies, "Energy", output_directory)

    plot(gyradii, "Radius of Gyration", output_directory)
    plot(gyradii_x, "Radius of Gyration x", output_directory)
    plot(gyradii_y, "Radius of Gyration y", output_directory)

    plot(end2ends, "End to End Length", output_directory)
    plot(end2ends_x, "End to End Length x", output_directory)
    plot(end2ends_y, "End to End Length y", output_directory)

    #Calculate avg, std. dev., and sem of observables over the last n/2 points
    points_sampled = n_moves // 2
    avg_energy, std_energy, sem_energy = avg_std(energies, points_sampled)

    avg_gyradius, std_gyradius, sem_gyradius = avg_std(gyradii, points_sampled)
    avg_gyradius_x, std_gyradius_x, sem_gyradius_x = avg_std(
        gyradii_x, points_sampled)
    avg_gyradius_y, std_gyradius_y, sem_gyradius_y = avg_std(
        gyradii_y, points_sampled)

    avg_end2end, std_end2end, sem_end2end = avg_std(end2ends, points_sampled)
    avg_end2end_x, std_end2end_x, sem_end2end_x = avg_std(
        end2ends_x, points_sampled)
    avg_end2end_y, std_end2end_y, sem_end2end_y = avg_std(
        end2ends_y, points_sampled)

    ###########################
    #### Write Output File ####
    ###########################

    output_name = output_directory + "/output.txt"

    #Remove previous output if it exists
    try:
        os.remove(output_name)
    except FileNotFoundError:
        pass

    #Write output file:
    with open(output_directory + "/output.txt", 'w+') as file:
        file.write("POLYSIM" + "\n")
        file.write("A Software by Abhishek, Daniel, Yogev, Peter, and Caini" +
                   "\n")
        file.write("\n")

        file.write("SIMULATION ACHIEVED" + "\n")
        file.write("########################" + "\n")
        file.write("SETTINGS:" + "\n")
        file.write("Move type: " + move_type + "\n")
        file.write("Lamellar field: ")
        if lamellar == True:
            file.write("ON" + "\n")
            file.write("Field Strength: " + str(field) + "\n")
        else:
            file.write("OFF" + "\n")
        if lamellar == True:
            file.write("Temperature: " + str(temp) + "\n")

        file.write("Length of Polymer: " + str(length_poly) + "\n")
        file.write("Moves in Simualation: " + str(n_moves) + "\n")
        file.write("Points Sampled: " + str(points_sampled) + "\n")

        file.write("########################" + "\n")
        file.write("Average energy: " + str(avg_energy) + "\n")
        file.write("\n")
        file.write("Average radius of gyration: " + str(avg_gyradius) + "\n")
        file.write("Average radius of gyration x: " + str(avg_gyradius_x) +
                   "\n")
        file.write("Average radius of gyration y: " + str(avg_gyradius_y) +
                   "\n")
        file.write("\n")
        file.write("Average end to end: " + str(avg_end2end) + "\n")
        file.write("Average end to end x: " + str(avg_end2end_x) + "\n")
        file.write("Average end to end y: " + str(avg_end2end_y) + "\n")

        file.write("########################" + "\n")
        file.write("Std deviation of energy: " + str(std_energy) + "\n")
        file.write("\n")
        file.write("Std deviation of radius of gyration: " +
                   str(std_gyradius) + "\n")
        file.write("Std deviation of radius of gyration x: " +
                   str(std_gyradius_x) + "\n")
        file.write("Std deviation of radius of gyration y: " +
                   str(std_gyradius_y) + "\n")
        file.write("\n")
        file.write("Std deviation of end to end distance: " +
                   str(std_end2end) + "\n")
        file.write("Std deviation of end to end distance x: " +
                   str(std_end2end_x) + "\n")
        file.write("Std deviation of end to end distance y: " +
                   str(std_end2end_y) + "\n")

        file.write("########################" + "\n")
        file.write("Std error of energy: " + str(sem_energy) + "\n")
        file.write("\n")

        file.write("Std error of radius of gyration: " + str(sem_gyradius) +
                   "\n")
        file.write("Std error of radius of gyration x: " +
                   str(sem_gyradius_x) + "\n")
        file.write("Std error of radius of gyration y: " +
                   str(sem_gyradius_y) + "\n")

        file.write("\n")
        file.write("Std error of end to end distance: " + str(sem_end2end) +
                   "\n")
        file.write("Std error of end to end distance x: " +
                   str(sem_end2end_x) + "\n")
        file.write("Std error of end to end distance y: " +
                   str(sem_end2end_y) + "\n")
        file.write("########################" + "\n")
        file.write("\n")

        file.write("NORMAL TERMINATION" + "\n")
        file.write("THANK YOU FOR USING OUR SOFTWARE" + "\n")
        file.write("\n")
        file.write("\n")
        file.write("\n")

    #######################
    #### Generate Gif  ####
    #######################

    if generate_gif:
        print(
            "Simulation done! Generating gif (this might take a while (2-3 minutes))..."
        )
        make_gif(n_moves, output_directory)
Example #5
0
#!/usr/bin/env python
# add words to ../dict_en.dat in the correct place

import sys

if len(sys.argv) < 2:
    raise Exception("add_word.py word1 word2...")

sys.path.insert(0, "../src")

import misc
import util

util.init(False)
misc.init(False)

s = util.loadFile("../dict_en.dat", None)
if s == None:
    raise Exception("error")

words = {}
lines = s.splitlines()

for it in lines:
    words[util.lower(it)] = None

for arg in sys.argv[1:]:
    words[util.lower(arg)] = None

words = list(words.keys())
words.sort()
Example #6
0
#!/usr/bin/env python
# add words to ../dict_en.dat in the correct place

import sys

if len(sys.argv) < 2:
    raise Exception("add_word.py word1 word2...")

sys.path.insert(0, "../src")

import misc
import util

util.init(False)
misc.init(False)

s = util.loadFile("../dict_en.dat", None)
if s == None:
    raise Exception("error")

words = {}
lines = s.splitlines()

for it in lines:
    words[util.lower(it)] = None

for arg in sys.argv[1:]:
    words[util.lower(arg)] = None

words = words.keys()
words.sort()
def main():
    if os.name == "nt":
        full = 0
        double = 0
    else:
        full = 0
        double = 1

    displayFlags = HWSURFACE

    # Get commandline options
    if len(sys.argv) != 1:
        for i in range(1, len(sys.argv)):
            if sys.argv[i].upper() == "--RESOLUTION":
                # Get the resolution
                if i != len(sys.argv) - 1 and sys.argv[i +
                                                       1].upper() == "640X480":
                    misc.zoom = 0.625
                elif i != len(sys.argv) - 1 and sys.argv[
                        i + 1].upper() == "320X240":
                    misc.zoom = 0.3125
            if sys.argv[i].upper() == "--FULLSCREEN":
                full = 1
            if sys.argv[i].upper() == "--DOUBLEBUF":
                double = 1
            if sys.argv[i].upper() == "--NODOUBLEBUF":
                double = 0
            if sys.argv[i].upper() == "--NOSOUND":
                misc.music = 0
            if sys.argv[i].upper() == "--HELP" or sys.argv[i].upper() == "-H":
                print(
                    "USAGE: Speedlust.py [--resolution 640x480|320x240] [--fullscreen] [--doublebuf|--nodoublebuf] [--nosound] [--help|-h] [--version]"
                )
                print()
                print(
                    "  --resolution   Change resolution (default is 1024x768)")
                print("  --fullscreen   Enable fullscreen display")
                print(
                    "  --doublebuf    Enable double buffering display (DEFAULT on other platform than Windows)"
                )
                print(
                    "  --nodoublebuf  Disable double buffering display (DEFAULT on Windows)"
                )
                print("  --nosound      Disable Sound")
                print("  --help|-h      Display this help and exit")
                print("  --version      Output version information and exit")
                sys.exit(0)
            if sys.argv[i].upper() == "--VERSION":
                print("Speedlust version " + misc.VERSION +
                      ", Copyright (C) 2018 Ritu <*****@*****.**>")
                print()
                print("Speedlust comes with ABSOLUTELY NO WARRANTY.")
                print(
                    "This is free software, and you are welcome to redistribute it"
                )
                print(
                    "under certain conditions; see the COPYING file for details."
                )
                sys.exit(0)

    if full == 1 and double == 1:
        displayFlags = displayFlags | DOUBLEBUF | FULLSCREEN
    elif full == 1 and double == 0:
        displayFlags = displayFlags | FULLSCREEN
    elif full == 0 and double == 1:
        displayFlags = displayFlags | DOUBLEBUF
    elif full == 0 and double == 0:
        displayFlags = displayFlags

    try:
        pygame.init()
    except:
        print("Cannot initialize pyGame:")
        sys.exit(-1)

    if pygame.display.mode_ok((int(1024 * misc.zoom), int(768 * misc.zoom)),
                              displayFlags, 24) == 0:
        print("Speedlust cannot initialize display...")
        sys.exit(-1)
    else:
        misc.screen = pygame.display.set_mode(
            (int(1024 * misc.zoom), int(768 * misc.zoom)), displayFlags, 24)

    pygame.display.set_caption("Speedlust v" + misc.VERSION)
    pygame.display.set_icon(
        pygame.image.load(os.path.join("sprites", "SpeedlustIcon.bmp")))

    if misc.music == 1:
        pygame.mixer.music.load(os.path.join("sounds", "start.ogg"))
        pygame.mixer.music.play()

    try:
        import psyco
        psyco.full()
    except:
        print("Cannot use psyCo...")
        pass

    pygame.mouse.set_visible(0)

    misc.init()

    select1 = 1

    while select1 != -1:
        menu1 = menu.SimpleMenu(
            misc.titleFont, "Speedlust v" + misc.VERSION, 20 * misc.zoom,
            misc.itemFont,
            ["Single Race", "Tournament", "Hi Scores", "Credits", "License"])
        select1 = menu1.getInput()

        # Single Race
        if select1 == 1:
            race = game.Game("singleRace")

            menu2 = menu.ChooseTrackMenu(misc.titleFont, "singleRace: Track",
                                         2 * misc.zoom, misc.itemFont)
            select2 = menu2.getInput()
            if select2 != -1:
                race.listTrackName = [[select2[0], select2[1]]]

                menu3 = menu.ChooseValueMenu(misc.titleFont,
                                             "singleRace: Laps", 0,
                                             misc.itemFont, 1, 10)
                select3 = menu3.getInput()
                if select3 != -1:
                    race.maxLapNb = select3

                    menu4 = menu.ChooseValueMenu(misc.titleFont,
                                                 "singleRace: HumanPlayers", 0,
                                                 misc.itemFont, 0, 4)
                    select4 = menu4.getInput()
                    if select4 != -1:

                        isExit = 0
                        race.listPlayer = []
                        for i in range(1, select4 + 1):
                            menu5 = menu.ChooseHumanPlayerMenu(
                                misc.titleFont,
                                "singleRace: HumanPlayer" + str(i),
                                5 * misc.zoom, misc.itemFont)
                            thePlayer = menu5.getInput()
                            if thePlayer == -1:
                                isExit = 1
                                break
                            race.listPlayer.append(thePlayer)

                        # If there's no exit during enter of player
                        if isExit == 0:
                            # If there's no Human player, there should exist at least a Bot player
                            if select4 == 0:
                                minBot = 1
                            else:
                                minBot = 0
                            menu6 = menu.ChooseValueMenu(
                                misc.titleFont, "singleRace: RobotPlayers", 0,
                                misc.itemFont, minBot, 4)
                            select6 = menu6.getInput()
                            if select6 != -1:
                                isExit = 0
                                for i in range(1, select6 + 1):
                                    menu7 = menu.ChooseRobotPlayerMenu(
                                        misc.titleFont,
                                        "singleRace: RobotPlayer" + str(i),
                                        5 * misc.zoom, misc.itemFont)
                                    thePlayer = menu7.getInput()
                                    if thePlayer == -1:
                                        isExit = 1
                                        break
                                    race.listPlayer.append(thePlayer)

                                # If there's no exit during enter of player
                                if isExit == 0:
                                    race.play()

        # Tournament
        elif select1 == 2:
            tournament = game.Game("tournament")

            tournament.listTrackName = []

            # Get all tracks to put in the tournament
            listAvailableTrackNames = track.getAvailableTrackNames()

            for trackName in listAvailableTrackNames:
                tournament.listTrackName.append([trackName, 0])

            # Also Reverse tracks
            for trackName in listAvailableTrackNames:
                tournament.listTrackName.append([trackName, 1])

            menu2 = menu.ChooseValueMenu(misc.titleFont, "tournament: Laps", 0,
                                         misc.itemFont, 1, 10)
            select2 = menu2.getInput()
            if select2 != -1:
                tournament.maxLapNb = select2

                menu3 = menu.ChooseValueMenu(misc.titleFont,
                                             "tournament: HumanPlayers", 0,
                                             misc.itemFont, 0, 4)
                select3 = menu3.getInput()
                if select3 != -1:

                    isExit = 0
                    tournament.listPlayer = []
                    for i in range(1, select3 + 1):
                        menu4 = menu.ChooseHumanPlayerMenu(
                            misc.titleFont, "tournament: HumanPlayer" + str(i),
                            5 * misc.zoom, misc.itemFont)
                        thePlayer = menu4.getInput()
                        if thePlayer == -1:
                            isExit = 1
                            break
                        tournament.listPlayer.append(thePlayer)

                    # If there's no exit during enter of player
                    if isExit == 0:
                        # If there's no Human player, there should exist at least a Bot player
                        if select3 == 0:
                            minBot = 1
                        else:
                            minBot = 0
                        menu6 = menu.ChooseValueMenu(
                            misc.titleFont, "tournament: RobotPlayers", 0,
                            misc.itemFont, minBot, 4)
                        select6 = menu6.getInput()
                        if select6 != -1:
                            isExit = 0
                            for i in range(1, select6 + 1):
                                menu7 = menu.ChooseRobotPlayerMenu(
                                    misc.titleFont,
                                    "tournament: RobotPlayer" + str(i),
                                    5 * misc.zoom, misc.itemFont)
                                thePlayer = menu7.getInput()
                                if thePlayer == -1:
                                    isExit = 1
                                    break
                                tournament.listPlayer.append(thePlayer)

                    # If there's no exit during enter of player
                    if isExit == 0:
                        tournament.play()

        elif select1 == 3:
            hiscoresMenu = menu.MenuHiscores(misc.titleFont, "hiscores",
                                             10 * misc.zoom,
                                             misc.smallItemFont)
            hiscoresMenu.getInput()
        elif select1 == 4:
            creditsMenu = menu.MenuCredits(misc.titleFont, "credits",
                                           10 * misc.zoom, misc.itemFont)
            misc.wait4Key()
        elif select1 == 5:
            licenseMenu = menu.MenuLicense(misc.titleFont, "license",
                                           10 * misc.zoom, misc.smallItemFont)
            misc.wait4Key()