Exemple #1
0
def command():
    id = hashlib.md5(get_remote_addr()).hexdigest()
    if (request.json['cmd'] == 'SURRENDER'):
        Go.restart(id)
        return jsonify({'res': 'OK'})
    elif (request.json['cmd'] == 'GETBOARD'):
        return jsonify({'res': Go.get_board(id)})
    elif (request.json['cmd'] == 'GETBOARDASLIST'):
        return jsonify({'res': Go.get_board_as_list(id)})
    elif (request.json['cmd'] == 'GETSCORE'):
        return jsonify({'res': Go.estimate_score(id, 'white')})
    elif (request.json['cmd'] == 'PLAY'):
        #check
        if Go.isWhiteTurn(id) and type(request.json['pos']) is list:
            Go.play(id, 'white', request.json['pos'])
            msg = AI.play(id, request.json['pos'])
            if 'Congratz' in msg:
                win(id)
                Go.soft_reset(id)
            return jsonify({'res': msg})
        else:
            return jsonify({'res': 'Invalid play'})
    elif (request.json['cmd'] == 'PASS'):
        #you can't pass :), so you should make AI surrender.
        return
    else:
        return
Exemple #2
0
def admin_clear():
    global Win, WinLock
    if (request.args.get('key') == Go.key):
        Go.clear_all()
        with WinLock:
            Win = {}
        return 'OK'
    return 'Fail'
 def read_Data_Method3(self):
     myGo = Go.Go()
     response = "/home/launch/Desktop/Share/response.csv"
     real_art = "/home/launch/Desktop/Share/real_art.csv"
     data = "/home/launch/Desktop/Share/data.zip"
     processedFiles = myGo.processFiles(response, real_art, data)
     self.X = processedFiles["data"]
     self.y = processedFiles["response"]
 def SFS(self,classifiers):
     features=np.asarray(self.X)
     print(len(self.realArt))
     print(features.shape)
     myGo=Go.Go()
     fs=myGo.runUSFS(self.y, self.realArt, features,classifiers)
     print('fs###################',fs)
     return fs
Exemple #5
0
def randomWalk(t):  # random Walk
    for i in range(1,t+1):
        a = random.uniform(1,5)
        a = min(4,math.floor(a))
        if a == 1:
            Go.goUp(1)
        if a == 2:
            Go.goDown(1)
        if a == 3:
            Go.goRight(1)
        if a == 4:
            Go.goLeft(1)
def main():
    f = open('AST', 'r')

    data = Data()
    data.Handler.setAST(f.read()) # Give string to handler

    parse(data)

    #data.Logger.printAllLog()
    #print("")
    #print("Result:")
    #for instr in data.GlobalBlock.instr_list:
        #print(instr.__str__())
    #print("")
    #print("Go:")
    
    print("package main\nimport \"fmt\"\n");
    Go.init()
    for instr in data.GlobalBlock.instr_list:
        print(instr.__go__())
Exemple #7
0
def play(id, pos):
    try:
        p = Popen('../src/AI', stdin=PIPE, stdout=PIPE)
        res = ''
        while p.poll() is None:
            output = get_output(p)
            if 'ERROR' in output:
                raise Exception
            if 'CMD' not in output:
                continue
            if 'SURRENDER' in output:
                res = 'Congratz! AI surrendered.'
            if 'PLAY' in output:
                #[%d,%d] -> python list
                a = get_output(p)
                choice = map(int, a[a.find('[') + 1:a.find(']')].split(','))
                Go.play(id, 'black', choice)
                res = str(choice)
            if 'GETINPUT' in output:
                p.stdin.write(str(pos) + '\n')
            if 'GETBOARD' in output:
                p.stdin.write(str(Go.get_board_as_list(id)) + '\n')
            if 'GETSCORE' in output:
                p.stdin.write(Go.estimate_score(id, 'black') + '\n')
            if 'PASS' in output:
                Go.ai_pass(id)
                res = 'AI passed'
        return res
    except Exception as e:
        print e
        return 'Error ... (ToT)'
    finally:
        if p.poll() is None:
            p.kill()
            p.wait()
Exemple #8
0
    def GoClick(self, csvResponse, csvRealArt, datazip):
        Application.printToWindow(self, "Starting Application")
        if csvResponse != 0 and csvRealArt != 0 and datazip != 0:
            myGo = Go.Go()
            processedFiles = myGo.processFiles(csvResponse, csvRealArt, datazip)
            varKept = 0
            if self.PCVar.get() == 1:
                self.printToWindow("Dimensionality Reduction Enabled")
                self.printToWindow("Beginning Dimensionality Reduction")
                varKept = myGo.DimReduction(float(self.PCVarToKeep.get()), processedFiles["response"],
                                            processedFiles["dataList"])
                self.printToWindow(varKept)
            else:
                self.printToWindow("Dimensionality Reduction Disabled")

            #get classifiers
            classifiers = []
            if self.LDAVar.get() == 1:
                classifiers.append("lda")
            if self.QDAVar.get() == 1:
                classifiers.append("qda")
            if self.SVMVar.get() == 1:
                classifiers.append("svm")

            #feature selection
            fs = 0
            if self.FSVar.get() == "USFS":
                if self.PCVar.get() == 1:
                    fs = myGo.runUSFS(processedFiles["response"], processedFiles["realArt"], varKept["scoreTotal"],
                                 classifiers)
                else:
                    fs = myGo.runUSFS(processedFiles["response"], processedFiles["realArt"], processedFiles["data"],
                                 classifiers)
            elif self.FSVar.get() == "LASSO":
                if self.PCVar.get() == 1:
                    fs = myGo.runLASSO(varKept["scoreTotal"], processedFiles["response"])
                else:
                    print("running with data")
                    fs = myGo.runLASSO(processedFiles["data"], processedFiles["response"])
            elif self.FSVar.get() == "Elastic Net":
                if self.PCVar.get() == 1:
                    fs = myGo.runElasticNet(varKept["scoreTotal"], processedFiles["response"])
                else:
                    fs = myGo.runElasticNet(processedFiles["data"], processedFiles["response"])
            print('fs is',fs)
            self.FSOutput(fs["bestFeatureSummary"], classifiers)

            #myUSFS.run(csvResponse, csvRealArt, datazip)
            self.printToWindow("Application Complete")
Exemple #9
0
def start_skill():
    """
    Resets CNN for new game.

    Returns
    -------
    question
    """
    global cnn
    global state
    print("Skill started")
    state = None
    root = Node(Go.GameState(size=SIZE, komi=4))
    cnn = Go_CNN(root)
    return question("I'll begin. Let me know when you are ready.")
Exemple #10
0
def create_game(init_time=120, filepath="mc.txt"):
    """
    Creates Monte Carlo and plays through for init_time seconds. Saves to txt file.

    Parameters
    ----------
    init_time: int
        seconds for which initialization will occur
    filepath: String
        path to txt file

    Returns
    -------
    None
    """
    root = Node(Go.GameState())
    monte = MonteCarlo(root, initial_time=init_time)
    with open(filepath, "wb") as f:
            pickle.dump(monte, f)
Exemple #11
0
def generate_game(board_size, rounds, max_moves, temperature):
    boards, moves = [], []
    encoder = OnePlaneEncoder(board_size)
    game = Go(board_size)
    bot = myPlayerUCTS.myPlayer(board_size)
    num_moves = 0
    while not game.is_game_over():
        print(game)
        move = bot.getPlayerMove()
        (x, y) = move
        nextplayercolor = game._nextPlayer
        if game.is_valid_move(nextplayercolor, [x, y]):
            boards.append(encoder.encode(game))
            move_on_hot = np.zeros(encoder.num_token())
            move_on_hot[encoder.encode(move)]
            moves.append(move_on_hot)
        print(move)
        game.push([nextplayercolor, x, y])
        num_moves += 1
        if num_moves > max_moves:
            break
    return np.array(boards), np.array(moves)
def runExperiment():
    import Go
    PdbName = sys.argv[2]
    FFType = sys.argv[3]
    OutDir = os.path.abspath(sys.argv[4])
    NReplica = int(sys.argv[5]) if len(sys.argv) > 5 else 8

    # parse paths etc
    OutDir = os.path.join(OutDir, PdbName)
    if not os.path.isdir(OutDir): os.system('mkdir -p %s' % OutDir)
    NativePdb = utils.parseNative(PdbName, MasterDir = os.path.expanduser('~/Go/native_struct/mapped'))
    try:
        AATopClustPdb = utils.parseNative(PdbName, MasterDir = os.path.expanduser('~/Go/native_struct/ff96_igb5_glghs_topclust_mapped'))
    except IOError:
        print 'Utils Error: Requested Top clust pdb does not exist'
        AATopClustPdb = None
    Prefix = 'prot_' + PdbName

    # parse forcefield parameters
    GoFF_File, FFMetadata = utils.parseGoFF(FFType)
    
    # backbone 
    BBType = FFMetadata['BBType']
    BBFF_File = utils.parseBBFF(BBType)[0]
    MinBondOrd = FFMetadata['MinBondOrd']
    NKnot = FFMetadata['NKnot']
    Cut = FFMetadata['Cut']
    
    # sidechain
    NCOSType = FFMetadata['NCOSType']
    GoType = FFMetadata['GoType']
    NonNativeType = FFMetadata['NonNativeType']
    
    # get LJ / spline params
    # Note: NonNative params are recorded from the given
    # forcefield file but not used currently, as these vary
    # depending on the sequence
    if not os.path.isfile(GoFF_File):
        print 'I/O Error: forcefield file does not exist'
        exit()
    # single LJ/Sigma for all native interactions
    if GoType == 1:
        NativeSigma = FFMetadata['NativeSigma']
        NativeEpsilon = FFMetadata['NativeEpsilon']
        NativeCut = FFMetadata['NativeCut']
    # LJ matrix for native interactions
    if GoType == 2:
        print 'Error: Not implemented yet'
        exit()
    # splined potential for all native interactions
    if GoType == 3:
        NativeKnots = FFMetadata['NativeKnots']
        NativeNKnot = len(NativeKnots)
        NativeCut = FFMetadata['NativeCut']
    if NonNativeType == 0:
        print 'Error: Will generate too much repulsion'
        exit()
    if NonNativeType == 1:
        NonNativeSigma = FFMetadata['NonNativeSigma']
        NonNativeEpsilon = FFMetadata['NonNativeEpsilon']
        NonNativeCut = FFMetadata['NonNativeCut']
    if NonNativeType == 2:
        NonNativeKnots = FFMetadata['NonNativeKnots']
        NonNativeNKnot = len(NonNativeKnots)
        NonNativeCut = FFMetadata['NonNativeCut']
    
    # temp schedule
    TLow = 270.
    THigh = 500.
    Temps = np.logspace(np.log10(TLow), np.log10(THigh), NReplica)
    TempInd = np.argmin(abs(Temps - RoomTemp))
    TempSet = Temps[TempInd]

    # time-step
    Delta_T = FFMetadata['TimeStep'] # femto-seconds

    # MD iterations
    NStepsMin = int(10000 / Delta_T)            # 10 ps
    NStepsEquil = int(50000000 / Delta_T)       # 50 ns
    NStepsProd  = int(20000000 / Delta_T)       # 20 ns
    NStepsSwap = int(1000 / Delta_T)            # 1 ps
    StepFreq = int(NStepsProd / 10000)          # need 10000 frames, 2 ps

    # REMD setup template
    mdstr_setup = '''
#!/usr/bin/env python
import os, sys, numpy as np, time
import Go, utils

# check if only analysis needs to be done
FullPrefix = os.path.join(os.getcwd(), "%(PREFIX)s")
isDone = utils.checkGoREMD(FullPrefix, [%(TEMPSET)3.2f])
if isDone: exit()

#### REMD ####
# basic settings
Go.Prefix = "%(PREFIX)s"
Go.InPdb ="%(NATIVEPDB)s"
Go.Temps = np.logspace(np.log10(%(TLOW)3.2f), np.log10(%(THIGH)3.2f), %(NREPLICA)d)
Go.TempSet = %(TEMPSET)3.2f
    
# backbone settings
Go.MinBondOrd = %(MINBONDORD)d
Go.NKnot = %(NKNOT)d
Go.SPCut = %(CUT)g
Go.BB_forcefield_file = "%(BBFF_FILE)s"
Go.NCOSType = %(NCOSTYPE)d

# md iterations
Go.NStepsMin = %(NSTEPSMIN)d
Go.NStepsEquil = %(NSTEPSEQUIL)d
Go.NStepsProd = %(NSTEPSPROD)d
Go.NStepsSwap = %(NSTEPSSWAP)d
Go.StepFreq = %(STEPFREQ)d
    '''
    
    # side-chain interactions template
    mdstr_sidechain = {
    'native_LJ': '''
# native contacts
Go.GoType = 1
Go.NativeSigma = None if %(AUTOSIGMA)d else %(NATIVESIGMA)g
Go.NativeEpsilon = %(NATIVEEPSILON)g
Go.NativeCut = %(NATIVECUT)g
    ''',
    
    'native_Spline': '''
# native contacts
Go.GoType = 3
Go.NativeNKnot = %(NATIVENKNOT)d
Go.NativeKnots = %(NATIVEKNOTS)s
Go.NativeCut = %(NATIVECUT)g
    ''',

    'nonnative_LJ': '''
# non-native contacts
Go.NonNativeType = 1
Go.NonNativeSigma = %(NONNATIVESIGMA)g
Go.NonNativeEpsilon = %(NONNATIVEEPSILON)g
Go.NonNativeCut = %(NONNATIVECUT)g
    ''',

    'nonnative_Spline': '''
# non-native contacts
Go.NonNativeType = 2
Go.NonNativeNKnot = %(NONNATIVENKNOT)d
Go.NonNativeKnots = %(NONNATIVEKNOTS)s
Go.NonNativeCut = %(NONNATIVECUT)g
    '''}


    # run template
    mdstr_run = '''
# compile Sys object
Sys = Go.makeGoSys()
for m in Sys.Int.Methods: m.TimeStep *= %(TIMESTEP)g
    
# run REMD
t1 = time.time()
TrajFile, LogFile = Go.runREMD(Sys)
t2 = time.time()
    
# reorder by temperature only at room temp
Go.reorderTraj(ReorderTemps = [%(TEMPSET)3.2f] )
t3 = time.time()
    
# print stats
print "REMD time: ", (t2-t1), " seconds"
print "Reordering time: ", (t3-t2), " seconds"
'''

    # job script template
    jobstr = '''
#!/bin/bash
#
#$ -V
#$ -cwd
#$ -j y
#$ -S /bin/bash
#$ -N %(JOBNAME)s

export PYTHONPATH=$PYTHONPATH:~/Go
date
python remd.py
mkdir -p ./NativeAnalysis
mkdir -p ./AATopClustAnalysis
python ~/Go/analyze_go.py %(NATIVEPDB)s %(PREFIX)s ./ ./NativeAnalysis
python ~/Go/analyze_go.py %(AATOPCLUSTPDB)s %(PREFIX)s ./ ./AATopClustAnalysis
date
'''
    # dict for filling md script template
    d_setup_run = {
        'PREFIX'        : Prefix,
        'NATIVEPDB'     : NativePdb,
 
        'TLOW'          : TLow,
        'THIGH'         : THigh,
        'NREPLICA'      : NReplica,
        'TEMPSET'       : TempSet,
        'TEMPIND'       : TempInd,
     
        'BBFF_FILE'     : BBFF_File,
        'MINBONDORD'    : MinBondOrd,
        'NKNOT'         : NKnot,
        'CUT'           : Cut,
        'NCOSTYPE'      : NCOSType,

         'TIMESTEP'     : Delta_T,
        'NSTEPSMIN'     : NStepsMin,
        'NSTEPSEQUIL'   : NStepsEquil,
        'NSTEPSPROD'    : NStepsProd,
        'NSTEPSSWAP'    : NStepsSwap,
        'STEPFREQ'      : StepFreq
        }
    
    if GoType == 1:
        d_native = {
        'AUTOSIGMA'     : int(AutoSigma),
        'NATIVESIGMA'   : NativeSigma,
        'NATIVEEPSILON' : NativeEpsilon,
        'NATIVECUT'     : NativeCut, 
       }
    
    if GoType == 2:
        print 'Error: Not yet implemented'
        exit()

    if GoType == 3:
        d_native = {
        'NATIVENKNOT'   : NativeNKnot,
        'NATIVEKNOTS'   : str(NativeKnots),
        'NATIVECUT'     : NativeCut
        }

    if NonNativeType == 0:
        # verified this with simulations of protein-G
        print 'Error: Will generate too much non-native repulsion'
        exit()

    if NonNativeType == 1:
        d_nonnative = {
        'NONNATIVESIGMA'    : NativeSigma,
        'NONNATIVEEPSILON'  : NativeEpsilon,
        'NONNATIVECUT'      : NonNativeCut,
        }

    if NonNativeType == 2:
        d_nonnative = {
        'NONNATIVENKNOT'    : NonNativeNKnot,
        'NONNATIVEKNOTS'    : NonNativeKnots,
        'NONNATIVECUT'      : NonNativeCut
        }

    # extract complete dic
    d1 = {}
    for x in [d_setup_run, d_native, d_nonnative]:
        for k, v in x.iteritems(): d1[k] = v

    # dict for filling job script template
    d2 = {'JOBNAME': Prefix, 'NATIVEPDB': NativePdb, 'AATOPCLUSTPDB': AATopClustPdb, 'PREFIX': Prefix}

    # extract complete template
    s = mdstr_setup
    if GoType == 1:
        s += mdstr_sidechain['native_LJ']
    if GoType == 2:
        print 'Error: Not implemented yet'
        exit()
    if GoType == 3:
        s += mdstr_sidechain['native_Spline']
    if NonNativeType == 0:
        print 'Error: Will generate too much non-native repulsion'
        exit()
    if NonNativeType == 1:
        s += mdstr_sidechain['nonnative_LJ']
    if NonNativeType == 2:
        s += mdstr_sidechain['nonnative_Spline']
    s += mdstr_run

    # fill template and submit job
    print 'Using backbone type:' , BBType
    print 'Using GoType: ', GoType
    print 'Using Non-Native Type: ', NonNativeType
    mdscript = os.path.join(OutDir, 'remd.py')
    jobscript = os.path.join(OutDir, 'remdjob.sh')
    if not os.path.isfile(mdscript): file(mdscript, 'w').write(s % d1)
    file(jobscript, 'w').write(jobstr % d2)
    os.chdir(OutDir)
    os.system('qsub remdjob.sh')
    os.chdir(CURRDIR)
    return
Exemple #13
0
def start_game(reset=False, size=5, init_time=240):
    """
    Starts single player game, with computer going first, using python console.

    <<< USED FOR DEBUGGING PURPOSES, MAY NOT BE FULLY FUNCTIONAL >>>

    Parameters
    ----------
    reset: Boolean
        True: Create and train new Monte Carlo
        False: Load Monte Carlo from txt
    size: int
        size of board
    init_time: int
        seconds for which initialization will occur

    Returns
    -------
    int: winner
    """
    filepath = "mc_" + str(size) + "x" + str(size) + ".txt"
    sys.setrecursionlimit(3000)
    if reset:
        root = Node(Go.GameState(size))
        monte = MonteCarlo(root, initial_time=init_time)
        with open(filepath, "wb") as f:
            pickle.dump(monte, f)
    else:
        t0 = time.time()
        with open(filepath, "rb") as f:
            monte = pickle.load(f)
        print(time.time() - t0)
    print("Computer: I'll start.")
    root = monte.root
    root.content.captures = 0
    state = root.content
    while state.winner() == 0:
        state = monte.get_play()[0].content
        state.paint()
        if state.winner() != 0:
            break
        result = False
        while result is False:
            r = ""
            c = ""
            while not (len(r) > 0 and (r.isdigit() or r.upper() == "P")):
                r = input("Enter row or P to pass: "******"P":
                result = "P"
            else:
                while not (len(c) > 0 and c.isdigit()):
                    c = input("Enter column: ")
                result = (int(r), int(c))
            result = monte.update(result)
            if result is False:
                continue
            state = result.content
            state.paint()

    scores = state.score()
    winner = state.winner()
    if winner < 0:
        print("Tie reached.")
    elif winner == 1:
        print("Computer wins.")
    else:
        print("Player wins.")
    print("The score was " + str(scores[0]) + "-" + str(scores[1]) + ".")
    return winner
Exemple #14
0
def win(id):
    global Win, WinLock
    with WinLock:
        l = 19 * 19 - Go.get_board_as_list(id).count(0)
        Win[id] = l
def runExperiment():
    import Go
    PdbName = sys.argv[2]
    BBType = sys.argv[3]
    OutDir = os.path.abspath(sys.argv[4])
    NReplica = int(sys.argv[5]) if len(sys.argv) > 5 else 8

    # parse paths etc
    OutDir = os.path.join(OutDir, PdbName)
    if not os.path.isdir(OutDir): os.system('mkdir -p %s' % OutDir)
    NativePdb = utils.parseNative(PdbName, MasterDir = os.path.expanduser('~/Go/native_struct/mapped'))
    try:
        AATopClustPdb = utils.parseNative(PdbName, MasterDir = os.path.expanduser('~/Go/native_struct/ff96_igb5_glghs_topclust_mapped'))
    except IOError:
        print 'Utils Error: Requested Top clust pdb does not exist'
        AATopClustPdb = None
    FF_File, FFMetadata = utils.parseBBFF(BBType)
    Prefix = 'prot_' + PdbName

    # parse forcefield parameters
    MinBondOrd = FFMetadata['MinBondOrd']
    NKnot = FFMetadata['NKnot']
    Cut = FFMetadata['Cut']
    # Go parameters
    HarmonicFluct = np.sqrt(2.) # used to tune the force constant in s-s bias

    # temp schedule
    TLow = 270.
    THigh = 500.
    Temps = np.logspace(np.log10(TLow), np.log10(THigh), NReplica)
    TempInd = np.argmin(abs(Temps - RoomTemp))
    TempSet = Temps[TempInd]

    # time-step
    Delta_T = FFMetadata['TimeStep'] # femto-seconds

    # MD iterations
    NStepsMin = int(10000 / Delta_T)            # 10 ps
    NStepsEquil = int(50000000 / Delta_T)       # 50 ns
    NStepsProd  = int(20000000 / Delta_T)       # 20 ns
    NStepsSwap = int(1000 / Delta_T)            # 1 ps
    StepFreq = int(NStepsProd / 10000)          # need 10000 frames, 2 ps

    # REMD script template
    mdstr = '''
#!/usr/bin/env python
import os, sys, numpy as np, time
import Go, utils

# check if only analysis needs to be done
FullPrefix = os.path.join(os.getcwd(), "%(PREFIX)s")
isDone = utils.checkGoREMD(FullPrefix, [%(TEMPSET)3.2f])
if isDone: exit()

#### REMD ####
# basic settings
Go.Prefix = "%(PREFIX)s"
Go.InPdb ="%(NATIVEPDB)s"
Go.Temps = np.logspace(np.log10(%(TLOW)3.2f), np.log10(%(THIGH)3.2f), %(NREPLICA)d)
Go.TempSet = %(TEMPSET)3.2f
    
# forcefield settings
Go.MinBondOrd = %(MINBONDORD)d
Go.NKnot = %(NKNOT)d
Go.SPCut = %(CUT)g
Go.BB_forcefield_file = "%(FF_FILE)s"

# native harmonic restraints
Go.GoType = 4
Go.HarmonicFluct = %(HARMONICFLUCT)g

# no non-native interactions
Go.NonNativeType = -1

# md iterations
Go.NStepsMin = %(NSTEPSMIN)d
Go.NStepsEquil = %(NSTEPSEQUIL)d
Go.NStepsProd = %(NSTEPSPROD)d
Go.NStepsSwap = %(NSTEPSSWAP)d
Go.StepFreq = %(STEPFREQ)d

# compile Sys object
Sys = Go.makeGoSys()
for m in Sys.Int.Methods: m.TimeStep *= %(TIMESTEP)g
    
# run REMD
t1 = time.time()
TrajFile, LogFile = Go.runREMD(Sys)
t2 = time.time()
    
# reorder by temperature only at room temp
Go.reorderTraj(ReorderTemps = [%(TEMPSET)3.2f] )
t3 = time.time()
    
# print stats
print "REMD time: ", (t2-t1), " seconds"
print "Reordering time: ", (t3-t2), " seconds"
'''
    # job script template
    jobstr = '''
#!/bin/bash
#
#$ -V
#$ -cwd
#$ -j y
#$ -S /bin/bash
#$ -N %(JOBNAME)s

export PYTHONPATH=$PYTHONPATH:~/Go
date
python remd.py
mkdir -p ./NativeAnalysis
mkdir -p ./AATopClustAnalysis
python ~/Go/analyze_go.py %(NATIVEPDB)s %(PREFIX)s ./ ./NativeAnalysis
python ~/Go/analyze_go.py %(AATOPCLUSTPDB)s %(PREFIX)s ./ ./AATopClustAnalysis
date
'''
    # dict for filling md script template
    d1 = {
        'PREFIX': Prefix,
        'NATIVEPDB': NativePdb,
     
        'FF_FILE': FF_File,
        'MINBONDORD': MinBondOrd,
        'NKNOT' : NKnot,
        'CUT' : Cut,
        'HARMONICFLUCT': HarmonicFluct,
     
        'TLOW'    : TLow,
        'THIGH'   : THigh,
        'NREPLICA': NReplica,
        'TEMPSET' : TempSet,
        'TEMPIND' : TempInd,
     
        'TIMESTEP' : Delta_T,
        'NSTEPSMIN': NStepsMin,
        'NSTEPSEQUIL': NStepsEquil,
        'NSTEPSPROD' : NStepsProd,
        'NSTEPSSWAP' : NStepsSwap,
        'STEPFREQ': StepFreq
        }

    # dict for filling job script template
    d2 = {'JOBNAME': Prefix, 'NATIVEPDB': NativePdb, 'AATOPCLUSTPDB': AATopClustPdb, 'PREFIX': Prefix}

    # run REMD job
    print 'Using backbone type:' , BBType
    print 'Using harmonic restraints on side chains of native contacts'
    mdscript = os.path.join(OutDir, 'remd.py')
    jobscript = os.path.join(OutDir, 'remdjob.sh')
    if not os.path.isfile(mdscript): file(mdscript, 'w').write(mdstr % d1)
    file(jobscript, 'w').write(jobstr % d2)
    os.chdir(OutDir)
    os.system('qsub remdjob.sh')
    os.chdir(CURRDIR)
    return
Exemple #16
0
def start_game(param):
    """
    Starts single player game, with computer going first, using python console.

    CNN IMPLEMENTATION

    <<< USED FOR DEBUGGING PURPOSES, MAY NOT BE FULLY FUNCTIONAL >>>

    Parameters
    ----------
    reset: Boolean
        True: Create and train new Monte Carlo
        False: Load Monte Carlo from txt
    size: int
        size of board
    init_time: int
        seconds for which initialization will occur

    Returns
    -------
    int: winner
    """
    print("Computer: I'll start.")
    root = Node(Go.GameState(size=9, komi=0))
    cnn = Go_CNN(root, param)
    state = root.content
    while state.winner() == 0:
        state = cnn.get_play()[0].content
        state.paint(False)
        if state.winner() != 0:
            break
        result = False
        while result is False:
            r = ""
            c = ""
            while not (len(r) > 0 and (r.isdigit() or r.upper() == "P")):
                r = input("Enter row or P to pass: "******"q":
                return
            if r.upper() == "P":
                result = "P"
            else:
                while not (len(c) > 0 and c.isdigit()):
                    c = input("Enter column: ")
                result = (int(r), int(c))
            result = cnn.update(result)
            if result is False:
                continue
            state = result.content
            state.paint(False)

    scores = state.score()
    winner = state.winner()
    if winner < 0:
        print("Tie reached.")
    elif winner == 1:
        print("Computer wins.")
    else:
        print("Player wins.")
    print("The score was " + str(scores[0]) + "-" + str(scores[1]) + ".")
    return winner