Exemple #1
0
def Opt2(tour: List[Location.Location]):

    oldTour = tour.copy()
    newTour = tour.copy()
    shortestDist = Location.FindTourLength(tour)

    i = 0
    j = 0
    ij = len(tour)**2
    while (i < len(tour)):
        j = i + 1
        if miscGlobal.specialPrint == True:
            Funcs.PrintProgressBar(i * j, ij)
        while (j < len(tour)):
            if (time.process_time() - miscGlobal.start
                ) > miscGlobal.maxTime:  #A little bit spaghetti
                if miscGlobal.specialPrint == True:
                    print()
                return oldTour
            newTour = oldTour.copy()
            TwoOptSwap(i, j, oldTour, newTour)
            # print('Elements: ' + str(len(newTour)))
            newDist = Location.FindTourLength(newTour)
            # print('CurDist: ' + str(newDist))
            if (newDist < shortestDist):
                oldTour = newTour
                shortestDist = newDist
                yield oldTour
                # print("\tNew shorter dist: " + str(shortestDist))
            j += 1
        i += 1
    if miscGlobal.specialPrint == True:
        Funcs.PrintProgressBar(100, 100)
        print()
    return oldTour
def listen_shield(player, keys):
    if keys[pygame.K_c] and player.locks[3] == False:
        Funcs.shields(player)
    else:
        for x in player.shields:
            x.down()
            player.shields.remove(x)
Exemple #3
0
    def aim_locked(self):

        if self.locked != None:
            if self.aim(self.predict_pos) and not self.blocked:

                self.blocked = True
                Funcs.shot(self, self.look_dir, self.bolt_number)
Exemple #4
0
def NearestNeighbour(locations: List[Location.Location]):
    path = []

    #Greedy implementation
    if miscGlobal.specialPrint == True:
        print('Greedy results:')
    locationsLeft = locations.copy()
    path.append(locationsLeft[0])
    locationsLeft.remove(locationsLeft[0])

    #Find greedy path
    closest = None  #Initialize this once
    while len(locationsLeft) > 0:
        closest = Location.FindClosestCity(path[len(path) - 1], locationsLeft)
        path.append(closest)
        locationsLeft.remove(closest)
        if miscGlobal.specialPrint == True:
            Funcs.PrintProgressBar(len(path), len(locations))
        if (time.process_time() - miscGlobal.start) > miscGlobal.maxTime:
            path.extend(locationsLeft)
            locationsLeft.clear()
            if miscGlobal.specialPrint == True:
                print('\nCould not complete Nearest Neigbhour search')
        yield path
    if miscGlobal.specialPrint == True:
        print()
        Funcs.PrintTour(path)
    return path
Exemple #5
0
 def test_Moc_call(self, summ_mock):
     Funcs.summ(
         2, 3
     )  # dont't know why we need to call it here?? but fails if we don't.
     summ_mock.assert_called_with(
         2, 3)  # does not test for return value. Tests for the function
     #is called with the correct arguments
     summ_mock.reset_mock()
     result = Funcs.summ(2, 4)
     summ_mock.assert_not_called()
 def _suppressMonitoring(self):
     if self.getProp("UseTCK"):
         trans = {}
         trans['.*HltGlobalMonitor'] = {'Enable': {"^.*$": "False"}}
         trans['.*BeetleSyncMonitor.*'] = {'Enable': {"^.*$": "False"}}
         trans['HltL0GlobalMonitor'] = {'Enable': {"^.*$": "False"}}
         Funcs._mergeTransform(trans)
     else:
         hltConf = HltConf()
         hltConf.setProp("EnableMonitoring", False)
Exemple #7
0
def listen_shield(player, keys):

    if  keys[pygame.K_c] and player.locks[3] == False:

        Funcs.shields(player)
        print(len(all_objects))
        #special_lock = True
    else:
        for x in player.shields:
            x.down()
            player.shields.remove(x)
Exemple #8
0
def SimulatedAnneal(tour : List[Location.Location], temp : float = 1000000.0, coolRate : float = 0.0003, targetTmp : float = 0.001, maxIts : int = 10000000):
	bestTour = tour
	bestDist = Location.FindTourLength(tour)

	currentTour = bestTour
	currentDist = bestDist

	#Initialise these once
	tourIndex1 = 0
	tourIndex2 = 0

	totalIts = 0

	while temp > targetTmp and totalIts < maxIts:
		if (100 / maxIts * totalIts) % 1 == 0 and miscGlobal.specialPrint == True: #Only write to console when needed
			Funcs.PrintProgressBar(totalIts, maxIts)
			
		if (time.process_time() - miscGlobal.start) > miscGlobal.maxTime: #A little bit spaghetti 
			if miscGlobal.specialPrint == True:
				print()
			return bestTour
		totalIts += 1
		newTour = currentTour.copy()

		while tourIndex1 == tourIndex2: #Make sure that these aren't the same
			tourIndex1 = random.randint(0, len(newTour) - 1)
			tourIndex2 = random.randint(0, len(newTour) - 1)

		#Swap the locations
		Location.Swap(newTour, tourIndex1, tourIndex2)
		
		newDist = Location.FindTourLength(newTour)

		if AcceptProbs(currentDist, newDist, temp) : #Should we accept this new tour
			currentTour = newTour
			currentDist = newDist
			# print('New tour dist: ' + str(currentDist))

		if newDist < bestDist:
			bestTour = newTour
			bestDist = newDist
			yield newTour

		tourIndex1 = tourIndex2 #Makes them both equal so they will be recalculated
		
		temp *= 1 - coolRate
		# print(temp)
	
	if miscGlobal.specialPrint == True:
		Funcs.PrintProgressBar(100, 100)
		print()
	return bestTour
def listen_left(player, keys):

    if keys[pygame.K_LEFT]:
        player.rotate(-player.ROTATION)
        for x in player.turrets:
            x.rotate(-player.ROTATION)
            Funcs.orbit_rotate(player, x, player.ROTATION, x.distance,
                               x.orbit_ang)

        for x in player.shields:
            x.rotate(-player.ROTATION)

        for x in player.player_hull_group:
            Funcs.orbit_rotate(player, x, player.ROTATION, x.distance,
                               x.orbit_ang)
Exemple #10
0
    def destroy(self):

        self.kill()
        self.rotate(0)
        self.speed = [0,0]
        f.FX_explosion(self.rect.centerx, self.rect.centery)

        for x in self.shields:
            x.down()

        if self.player == True:

            for x in self.mounts:
                x.kill()
            for x in self.shields:
                x.kill()
            for x in self.player_hull_group:
                x.kill()
            self.lives += -1

            if self.lives > -1:
                #lol =0
                #lol = pygame.event.Event(pygame.USEREVENT)
                pygame.time.set_timer(pygame.USEREVENT+2, 500)

            else:
                Menus.death_menu()
                s = open('C:/vova/scores.txt', 'r')
                if int(s.read()) < score:
                    s.close()
                    s = open('C:/vova/scores.txt', 'w')
                    s.write(str(score))
                s.close()
Exemple #11
0
def listen_acceleration(player, keys):

    if keys[pygame.K_UP]:

        player.accelerate(player.ACCELERATION)
        #x.speed[1] += -0.25
        Funcs.FX_engine_mark(player)
Exemple #12
0
    def action(self):
        State.level = 0

        realGuy = Funcs.ship_assign(State.picked_ship,
                                    State.start_lives,
                                    player=True)

        Scripts.main_loop(realGuy)
Exemple #13
0
def listen_right(player, keys):

    if keys[pygame.K_RIGHT]:

        player.rotate(player.ROTATION)

        for x in player.turrets:
            x.rotate(player.ROTATION)
            Funcs.orbit_rotate(player, x, -player.ROTATION,
                               x.distance, x.orbit_ang)
            #x.speed[0] += 0.25
        for x in player.shields:
            x.rotate(player.ROTATION)

        for x in player.player_hull_group:
            Funcs.orbit_rotate(player, x, -player.ROTATION,
                               x.distance, x.orbit_ang)
Exemple #14
0
def StartSolveThread(any):
    timeStr = 'Something that won\'t format'
    while not Funcs.Isfloat(timeStr):
        timeStr = GetStrInput("Max computation time: ")
    miscGlobal.start = time.process_time()
    miscGlobal.maxTime = float(timeStr)

    # try:
    _thread.start_new_thread(SolveLoadedPath, ("", ""))
Exemple #15
0
    def blow_up(self):

        x = Object(blanc, self.rect.x, self.rect.y)
        x.radius = self.hit_range
        x.hp = self.hp
        x.timer = 2
        f.FX_explosion(self.rect.centerx, self.rect.centery,
                       xpl=expN, radius=(60,60))
        hit_waves.add(x)
        time_dependent.add(x)
        self.kill()
Exemple #16
0
    def action(self):
        global realGuy
        # global t
        State.t = False

        for object in State.player_group:

            object.speed = [0, 0]
            object.kill()
        for object in State.movable:
            object.kill()
        for object in State.interface:
            object.kill()

        realGuy = Funcs.ship_assign(State.picked_ship,
                                    State.start_lives,
                                    player=True)

        State.save['level'] = 0

        Funcs.spawn_wave(realGuy)
        Scripts.main_loop(realGuy)
 def _configureDQTags(self):
     from Configurables import CondDB
     tag = None
     toset = MooreExpert().getProp("DQFLAGStag")
     if not len(toset) or toset == "latest" or toset == "default":
         from CondDBUI.Admin.TagsFilter import last_gt_lts
         dqtags = last_gt_lts('DQFLAGS', self.getProp("DataType"))
         if dqtags:
             tag = dqtags[0]
     else:
         tag = toset
     if CondDB().isPropertySet("Tags") and 'DQFLAGS' in CondDB().getProp(
             "Tags") and len(CondDB().getProp("Tags")["DQFLAGS"]):
         #don't set anything if it has already been set elsewhere
         pass
     elif tag:
         CondDB().Tags = Funcs._zipdict(CondDB().Tags, {"DQFLAGS": tag})
Exemple #18
0
def P5p_SM(X, HP, WC, FF, M, Ex):
    """
    Input:
        X: engery [GeV]
        HP: hyper-paramets
        WC: Wilson coeff.
        FF: form factor
        M: masses
        CO: corrections
        Ex: extra params.
    """
    Dicts = {'HP': HP, 'WC': WC, 'FF': FF, 'M': M, 'Ex': Ex}

    J5_bin = integrate.quad(p5f.J_5_, X[0], X[1], args=(Dicts))
    c0_bin = integrate.quad(p5f.c_0, X[0], X[1], args=(Dicts))
    c4_bin = integrate.quad(p5f.c_4, X[0], X[1], args=(Dicts))
    P5p = p5f.P5p(J5_bin, c0_bin, c4_bin)
    return P5p
Exemple #19
0
def SolveProblem(problemText: str, problemName: str, maxTime: float):
    miscGlobal.maxTime = float(maxTime)

    path = []

    # print(Parse(problemText))
    path = Parse(problemText)
    path = NearestNeighbour(path)
    path = TwoOpt(path)
    path = SimulatedAnnealing(path)

    if miscGlobal.specialPrint == True:
        print('\nComputation time: ' +
              str(time.process_time() - miscGlobal.start))
        print('Total path length: ' + str(Location.FindTourLength(path)))
    else:
        Funcs.PrintData(problemName, Location.FindTourLength(path), path)

    return path
Exemple #20
0
def SimulatedAnnealing(path: List[Location.Location]):
    # Simulated annealing
    if (time.process_time() - miscGlobal.start) < miscGlobal.maxTime:
        if miscGlobal.specialPrint == True:
            print('Simulated annealing results:')
        iterations = 1000000
        initTemp = 1000000
        targetTemp = 0.000000001
        coolingRate = SimAnnealing.FindCoolingVal(iterations, initTemp,
                                                  targetTemp)
        for stepPath in SimAnnealing.SimulatedAnneal(path,
                                                     temp=initTemp,
                                                     targetTmp=targetTemp,
                                                     maxIts=iterations,
                                                     coolRate=coolingRate):
            path = stepPath
            yield stepPath
        if miscGlobal.specialPrint == True:
            Funcs.PrintTour(path)
    return path
Exemple #21
0
    def crash(self):
        global asteroids

        f.FX_explosion(self.rect.centerx, self.rect.centery)

        if self.type > 1:
            arr = []
            for i in range(random.choice(self.density)):

                i = Asteroid(self.image,
                    self.rect.centerx, self.rect.centery, self.type-1, self.speed)

                arr.append(i)

                if random.choice((1,0)):
                    i.speed[0] = -self.speed[0]
                else:
                    i.speed[1] = -self.speed[1]

            return arr
        self.kill()
Exemple #22
0
def TwoOpt(path: List[Location.Location]):
    #2Opt
    if miscGlobal.specialPrint == True:
        print('Opt2 Results:')
    pathLenDiff = 10
    pathLenDiffThreshold = 0.001
    lastLength = Location.FindTourLength(path)
    #If the path_delta < 1, it's not worth calculating anymore
    while pathLenDiff >= pathLenDiffThreshold and (
            time.process_time() - miscGlobal.start) < miscGlobal.maxTime:
        for newPath in Opt2.Opt2(path):
            yield newPath
            path = newPath
        newLength = Location.FindTourLength(path)
        pathLenDiff = lastLength - newLength  #Calculate this once
        if miscGlobal.specialPrint == True:
            print('Made path shorter by: ' + str(lastLength - newLength))
        lastLength = newLength

    if miscGlobal.specialPrint == True:
        Funcs.PrintTour(path)
    return path
Exemple #23
0
def P5p_NP():
    # central values
    res = np.zeros(len(bins))
    res_max = np.zeros(len(bins))
    res_min = np.zeros(len(bins))
    for b in range(len(bins)):
        min = bins[b][0]
        max = bins[b][1]
        J5_bin = integrate.quad(p5f.J_5_,
                                min,
                                max,
                                args=(FormFac, NP_WC, Mass, Param))
        c0_bin = integrate.quad(p5f.c_0,
                                min,
                                max,
                                args=(FormFac, NP_WC, Mass, Param))
        c4_bin = integrate.quad(p5f.c_4,
                                min,
                                max,
                                args=(FormFac, NP_WC, Mass, Param))
        P5p_bin = p5f.P5p(J5_bin, c0_bin, c4_bin)
        res[b] = P5p_bin
    return res_sm
Exemple #24
0
def Parse(lines: str):
    locations = []
    lines = lines.splitlines()
    #Parse all lines with only numbers and '.'s to instances of 'Location'
    for line in lines:
        if line.replace('\n', '', 1000).replace(' ', '', 1000) == '':
            continue
        #If all the characters in this line, are contained within 'validLocationChars'
        # if all(validLocationChars.__contains__(char) for char in line):
        if all(
                Funcs.Isfloat(word) for word in line.split()
        ):  #If everything on this line can be converted into a float, then it is a location
            #All characters in this line are contained within 'validLocationChars'
            #This is a location
            locations.append(Location.ParseStringToLocation(line))
        else:
            #Atleast one character in this line are not contained within 'validLocationChars'
            #This is not a location
            if miscGlobal.specialPrint == True:
                print(line.strip())  #This might be useful information
    if miscGlobal.specialPrint == True:
        print()
    return locations
Exemple #25
0
    def crash(self):
        global asteroids

        f.FX_explosion(self.rect.centerx, self.rect.centery)

        if self.type > 1:
            arr = []
            for i in range(random.choice(self.density)):

                x = Adv_Asteroid(self.level, self.rect.centerx,
                                 self.rect.centery, self.type-1, self.speed)
                arr.append(i)

                if random.choice((1,0)):
                    x.speed[0] = -self.speed[0]
                else:
                    x.speed[1] = -self.speed[1]

                if random.choice((0,0,0,0,0,0,0,0,1)):
                    c = Agressor(bad_thing, self.rect.centerx, self.rect.centery)
                    c.remove(player_group)
                    c.rush()

        self.kill()
Exemple #26
0
import os
import Funcs as f
import Parser_Csv as csv
import Parser__kml as kml

i=f.read_directory ("C:\\Users\\Dror\\Desktop\\Benchmark")
print (i)
for n in range (1,i+1):
    csv.create_csv(n)
    kml.create_kml(n)
    
Exemple #27
0
import Objetcs
import Funcs
from random import choices

temp_lista = Funcs.LerLista()
print(temp_lista)
palavra = Objetcs.Palavra(choices(temp_lista))

while (Funcs.gameOver(palavra)):
    Funcs.Desenha(getattr(palavra, "erros"), palavra)
    try:
        letra = str(input("Digite uma letra: "))
    except:
        print("Entrada errada!!!")
        continue
    palavra.process(letra)
print("A palavra era ", getattr(palavra, "palavra")[0])
Exemple #28
0
        awaiting = False
        import StdAry as method
    elif genmethod == "2":
        print("Point Buy Selected!")
        awaiting = False
        import PtBy as method
    elif genmethod == "3":
        print("Rolled Stats Selected!")
        awaiting = False
        import Rolld as method
    else:
        print("Didn\'t understand input. Please try again:")

user = method.character()  #creates character object

user = Funcs.GetAttrPref(user)  #Asks user for attribute preferences
HasntManuallyAlloc = True  #if the user has chosen point buy, they might allocate all their scores manually. This checks that.

if genmethod == "2":

    #Choice in point-buy: all 3 preferences = 15, or 1st, 2nd, 3rd = 15, 15, 13, or completely manual
    print("Seeing as you've chosen Point Buy...")
    print(
        "How Min-Max-y are we? Or would you like to allocate your attributes manually?"
    )
    print("Sensible, MAD, or manual?")

    awaiting = True
    while awaiting:
        sillyness = input(":")
        sillyness = sillyness.lower(
Exemple #29
0
"""
wanted a fixed weight data, so at first I created random weightdata with shape (2 , 650),
the I saved it into a weightData.txt file and saved it in the project folder, beccause I don't want the weightdata to be changing
every run
"""
weightDataLoad = np.loadtxt('weightData.txt')
weightData = np.array(weightDataLoad)
print('weight data shape  :', weightData.shape)

#---------- set initial Parameters ---------------------------------
iteration = 30
learningRate = 0.6
#-------------------------------------------------------------------

#--------------------------Training---------------------------------
weightDataEnd = F.trainData(weightData, trainData, iteration, learningRate)
#np.savetxt('weightDataend.txt',weightDataEnd , fmt='%s')

#-------------Plot Results -----------------------------------------
fig = plt.figure(constrained_layout=True, figsize=(20, 10))
gs = grid.GridSpec(2, 2, width_ratios=[2, 2])
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])
ax3 = plt.subplot(gs[2])
ax4 = plt.subplot(gs[3])
ax1.set_title('training data(patient from 0-10 rows, control from 10-20 rows)')
ax1.imshow(trainData[:, 100:150])
ax2.set_title('testing data: ')
ax2.imshow(testData[:, 100:150])
ax3.set_title('weightData before training: ')
ax3.imshow(weightData[:, 100:150])
Exemple #30
0
import Funcs as scraper

#programs scrapes date information for chosen times on rankings.the-elite.net

#change the value of high_points for upper bound, low_points for lower bound of points to scrape,
#set select_* false to ignore times from that difficulty
#change game and level for game and level to scrape from
#change filename to desired .csv file

high_points, low_points = 100, 95
select_a, select_sa, select_00a = True, True, True
game, level = "goldeneye", "aztec"
filename = "test.csv"

f = scraper.openfile("\\out\\" + filename)

#open chrome browser at 'url'
driver = scraper.openbrowser("https://rankings.the-elite.net/" + game +
                             "/stage/" + level)

#parse xml on rankspage and timespage to get personal best and date info
scraper.parse_xml(f, driver, high_points, low_points, select_a, select_sa,
                  select_00a)

driver.quit()
f.close()
Exemple #31
0
        2] == 'ADD':  #> python3 TSP_db.py problemName ADD problemDir.tsp
    if not DataBaseInterface.DoesProblemExist(problemName):
        print(DataBaseInterface.AddProblem(sys.argv[3], problemName))
    else:
        print("PROBLEM ALREADY EXISTS")
elif len(sys.argv) >= 4 and sys.argv[
        2] == 'SOLVE':  #> python TSP_db.py problemName SOLVE maxSolveTime
    if DataBaseInterface.DoesProblemExist(problemName):
        solution = tsp.SolveProblem(
         DataBaseInterface.GetProblem(problemName), \
         problemName,
         sys.argv[3]
         )
        DataBaseInterface.AddSolution(
         problemName, \
         Funcs.TourToIDText(solution), \
         Location.FindTourLength(solution), \
         "Test algorithm" \
        )
    else:
        print(f"Problem '{problemName}' does not exist")
    # print(DataBaseInterface.RetrieveProblemInfo(sys.argv[1]))
elif len(sys.argv) >= 3 and sys.argv[
        2] == 'FETCH':  #> python TSP_db.py problemName FETCH
    if DataBaseInterface.DoesSolutionExist(problemName):
        print(DataBaseInterface.GetSolution(problemName))
    else:
        print(f"Solution for problem '{problemName}' does not yet exist")
elif len(sys.argv) >= 3 and sys.argv[2] == 'PROBLEMEXISTS':
    print(
        'TRUE' if DataBaseInterface.DoesProblemExist(problemName) else 'FALSE')
Exemple #32
0
    def __init__( self ):
        self.world = World.World( Map.Map( 512, 512 ) )
        self.score = 0
        self.shouldRestart = False
        self.autoSleep = False
        World.curTurn = 0

        root = RoomBuilder.build( self.world._map )
        self.root = root

        POINT_11 = Math2D.Point( 1, 1 )

        Funcs.buildMap( self.world._map, root )

        self.renderer = Systems.Renderer( self.world, Init.SCREEN_WIDTH, Init.SCREEN_HEIGHT )
        self.renderer.setMap( self.world._map )
        self.world._map.buildTcodMap()

        playerRoom = self.root.pickRandomRoom( lambda: random.random() < 0.5 )
        pos = Math2D.IntPoint( playerRoom.rect.center )

        self.actionSystem = ActionSystem( self.world, actionMap )

        self.playerAction = None
        def playerAction( __, _, wasBlocked ):
            ret = self.playerAction
            self.playerAction = None
            return ret

        player = Entity()
        player.addComponent( Position( pos.x, pos.y ) )
        player.addComponent( TurnTaker( ai = playerAction ) )
        player.addComponent( CharacterComponent( playerCharacter ) )
        player.addComponent( Renderable( chr(2) ) )
        player.addComponent( SpellCaster() )
        player.onRemove.append( self.playerDeath )
        self.world.addEntity( player )
        self.player = player

        self.renderer.player = player
        self.renderer.playerChar = player.getComponent( CharacterComponent )

        def addEnemy( room ):
            if room.isLeaf == False:
                return
            if room == playerRoom:
                return

            prob = 1.4

            while random.random() < prob:
                rect = room.rect
                while True:
                    pos = rect.p1 + ( rect.dim * Math2D.Point( random.uniform( 0.2, 0.8 ), random.uniform( 0.2, 0.8 ) ) )
                    pos = Math2D.IntPoint( pos )

                    if not self.world._map.isBlocked( pos.x, pos.y ):
                        break

                enemy = Entity()
                enemy.target = player
                enemy.onRemove.append( self.addScore )
                enemy.addComponent( Position( pos.x, pos.y ) )
                enemy.addComponent( TurnTaker( ai = TurnTakerAi() ) )
                enemy.addComponent( Renderable( chr(1) ) )
                enemy.addComponent( CharacterComponent( random.choice( enemyCharacter ) ) )
                self.world.addEntity( enemy )

                prob *= 0.7

        #t = playerRoom
        #playerRoom = None
        #addEnemy( t )
        self.root.iterateTree( addEnemy, None )
        self.curTurn = 0

        self.render()