Exemplo n.º 1
0
def get_two_players(strat1, strat2):

    params1 = {'marker': 'red', 'strategy': strat1}
    params2 = {'marker': 'blue', 'strategy': strat2}
    pl1 = Interaction.Player(params1)
    pl2 = Interaction.Player(params2)

    return pl1, pl2
Exemplo n.º 2
0
def draw(canvas):
    global interactions, addedInteractions, numberOfPlatforms, madeGoat, framecount
    lv1background.update(canvas)
    platforms.draw(canvas)
    if not addedInteractions:
        for i in range(len(platforms.getCoords())):
            interaction = Interaction(player1, platforms.coords[i])
            interactions.append(interaction)
        addedInteractions = True

    for i in range(len(platforms.getCoords())):
        platforms.coords[i].p1 = Vector(
            platforms.coords[i].getp1().getP()[0],
            platforms.coords[i].getp1().getP()[1] + 1)
        platforms.coords[i].p2 = Vector(
            platforms.coords[i].getp2().getP()[0],
            platforms.coords[i].getp2().getP()[1] + 1)

        tempPlatform = Platform2(0)
        if platforms.coords[i].p1.y > 700:
            platforms.coords.pop(i)
            if i > 1:
                while not (abs(tempPlatform.getx1() -platforms.coords[i-1].getx1()) > platforms.DISTANCE*platforms.difficulty or \
                    abs(tempPlatform.getx2() - platforms.coords[i - 1].getx2()) > platforms.DISTANCE * platforms.difficulty):
                    tempPlatform = Platform2(0)
            platforms.coords.insert(i, tempPlatform)
            tempInteraction = Interaction(player1, tempPlatform)
        else:
            tempInteraction = Interaction(player1, platforms.coords[i])
        interactions.pop(i)
        interactions.insert(i, tempInteraction)
        numberOfPlatforms += 1
        if numberOfPlatforms % 5 == 0 and not madeGoat:  #numberOfPlatforms % 5 == 0 and not madeGoat
            makeGoat(platforms.coords[len(platforms.coords) - 1])
            madeGoat = True
        for j in range(len(monsters)):
            if platforms.coords[i] == monsters[j].platform:
                monsters[j].pos = Vector(
                    monsters[j].pos.x,
                    platforms.coords[i].p1.y - platforms.coords[i].thickness -
                    monsters[j].frameHeight / 2)
                monsters[j].update(canvas)
            if monsters[j].pos.y > 630:

                monsters.pop(j)

                madeGoat = False
    framecount += 1

    for i in range(len(interactions)):

        if platforms.coords[i].covers(player1.pos):
            interactions[i].update()

    platforms.draw(canvas)

    player1.update(canvas)
Exemplo n.º 3
0
 def start(mode):
     if mode == 0:
         print('Create mode feture')
         tname = input('Table name:')
         source = input('Source file name:')
         cfg.initTable(tname, source)
     else:
         tname = cfg.modules[mode - 1]
         action.go(tname)
Exemplo n.º 4
0
	def makeChild(self,parentconf,frame=1,usetype='all',makeCellList = True, redobox=False):
		self.debug = parentconf.debug
		self.param = parentconf.param
		# Single frame for the child
		self.multiopt = "single"
		# And we have already narrowed down to the types we are looking for
		self.usetype = "all"
		self.sigma = parentconf.sigma
		self.monodisperse = parentconf.monodisperse
		
		if parentconf.multiopt=="single":
			useparts = parentconf.getUseparts(usetype)
			self.N = len(useparts)
			self.rval = parentconf.rval[useparts,:]
			self.vval = parentconf.vval[useparts,:]
			self.nval = parentconf.nval[useparts,:]
			self.radius = parentconf.radius[useparts]
			self.ptype = parentconf.ptype[useparts]
			self.flag = parentconf.flag[useparts]
		else:
			useparts = parentconf.getUseparts(usetype,frame)
			self.N = len(useparts)
			self.rval = parentconf.rval[frame,useparts,:]
			self.vval = parentconf.vval[frame,useparts,:]
			self.nval = parentconf.nval[frame,useparts,:]
			self.radius = parentconf.radius[frame,useparts]
			self.ptype = parentconf.ptype[frame,useparts]
			self.flag = parentconf.flag[frame,useparts]
			
		# For defect tracking
		vnorm = np.sqrt(self.vval[:,0]**2 + self.vval[:,1]**2+self.vval[:,2]**2)
		self.vhat = self.vval / np.outer(vnorm,np.ones((3,)))
		
		# Generating new interaction assuming that it's not monodisperse and contains a single k
		#def __init__(self,param,sigma,ignore=False,debug=False):
		self.inter=Interaction(self.param,self.sigma,False,True)
		#self.geom=geometries[param.constraint](param)
		#self.inter = parentconf.inter
		self.geom = parentconf.geom
		
		if makeCellList:
			if redobox:
				rmin = np.zeros((3,))
				rmax = np.zeros((3,))
				rmin[0] = np.amin(self.rval[:,0])-self.sigma
				rmin[1] = np.amin(self.rval[:,1])-self.sigma
				rmin[2] = np.amin(self.rval[:,2])-self.sigma
				rmax[0] = np.amax(self.rval[:,0])+self.sigma
				rmax[1] = np.amax(self.rval[:,1])+self.sigma
				rmax[2] = np.amax(self.rval[:,2])+self.sigma
				self.makeCellList(1,rmin,rmax)
				# def makeCellList(self,frame=1,rmin='default',rmax='default'):
				
			else:
				self.makeCellList(1)
Exemplo n.º 5
0
def draw(canvas):
    global interactions , addedInteractions, numberOfPlatforms , framecount,numberOfGoats,goats
    lv1background.update(canvas)
    platforms.draw(canvas)
    if not addedInteractions:
        for i in range(len(platforms.getCoords()) ):
            interaction = Interaction(player1, platforms.coords[i])
            interactions.append(interaction)
        addedInteractions = True
    for i in range(len(platforms.getCoords())):
        platforms.coords[i].p1 = Vector(platforms.coords[i].getp1().getP()[0],platforms.coords[i].getp1().getP()[1] + 1)
        platforms.coords[i].p2 = Vector(platforms.coords[i].getp2().getP()[0],platforms.coords[i].getp2().getP()[1] + 1)
        tempPlatform = Platform2(0)
        if platforms.coords[i].p1.y > 700:
            platforms.coords.pop(i)
            if i > 1:
                while not (abs(tempPlatform.getx1() -platforms.coords[i-1].getx1()) > platforms.DISTANCE*platforms.difficulty or \
                    abs(tempPlatform.getx2() - platforms.coords[i - 1].getx2()) > platforms.DISTANCE * platforms.difficulty):
                        tempPlatform = Platform2(0)
            platforms.coords.insert(i,tempPlatform)
            tempInteraction = Interaction(player1, tempPlatform)
        else:
            tempInteraction = Interaction(player1, platforms.coords[i])
        interactions.pop(i)
        interactions.insert(i,tempInteraction)
        if random.randint(0,1) > 0.5 and numberOfGoats<3 and platforms.coords[i].p1.y < player1.pos.y: #numberOfPlatforms % 5 == 0 and not madeGoat
            makeGoat(platforms.coords[i])
            numberOfGoats+=1
            madeGoat = True
        #print("len monsters:",len(monsters))
        monstersToPop = []
        for j in range(len(goats)):
            print("len monsters:",len(goats))
            if platforms.coords[i] ==goats[j].platform:
                goats[j].pos = Vector(goats[j].pos.x,platforms.coords[i].p1.y-platforms.coords[i].thickness-goats[j].frameHeight/2)
                goats[j].update(canvas)
            #print("pos y:",monsters[j].pos.y)
            if goats[j].pos.y > 630:
                monstersToPop.append(goats[j])
                numberOfGoats-=1
        print("monsters to pop:",monstersToPop)
        for j in range(len(monstersToPop)):
            goats.remove(monstersToPop[j])
    framecount += 1


    for i in range(len(interactions)):
        if platforms.coords[i].covers(player1.pos):
            interactions[i].update()

    platforms.draw(canvas)

    player1.update(canvas)
Exemplo n.º 6
0
def draw(canvas):
    global interactions, addedInteractions
    platforms.draw(canvas)
    if not addedInteractions:
        for i in range(len(platforms.getCoords())):
            interaction = Interaction(player1, platforms.coords[i])
            interactions.append(interaction)
        addedInteractions = True
    #platform2.draw(canvas)
    for i in range(len(platforms.getCoords())):
        platforms.coords[i].p1 = Vector(
            platforms.coords[i].getp1().getP()[0],
            platforms.coords[i].getp1().getP()[1] + 1)
        platforms.coords[i].p2 = Vector(
            platforms.coords[i].getp2().getP()[0],
            platforms.coords[i].getp2().getP()[1] + 1)
        #print("platform: ",platforms.coords[i])
        tempPlatform = Platform2(0)
        if platforms.coords[i].p1.getP()[1] > 700:
            platforms.coords.pop(i)
            if i > 1:
                while not (abs(tempPlatform.getx1() -platforms.coords[i-1].getx1()) > platforms.DISTANCE*platforms.difficulty or \
                    abs(tempPlatform.getx2() - platforms.coords[i - 1].getx2()) > platforms.DISTANCE * platforms.difficulty):
                    tempPlatform = Platform2(0)
            platforms.coords.insert(i, tempPlatform)
            tempInteraction = Interaction(player1, tempPlatform)
        else:
            tempInteraction = Interaction(player1, platforms.coords[i])
        interactions.pop(i)
        interactions.insert(i, tempInteraction)
        #print("inserted new interaction:",platforms.coords[i])

    for i in range(len(interactions)):
        # print(len(interactions))
        # print("coords: ",len(platforms.coords))
        #print(platforms.coords[i].covers(player1.pos))
        #print(player1.pos.getP()[1]-player1.frameHeight/2<platforms.coords[i].p1.getP()[1])   and pos.getP()[1]<self.yCoord    //and player1.pos.getP()[1]-player1.frameHeight<platforms.coords[i].p1.getP()[1]
        #distPlayerPlat = platforms.coords[i].p1.getP()[1] - player1.pos.getP()[1]-player1.frameHeight
        if platforms.coords[i].covers(
                player1.pos
        ):  #and player1.pos.getP()[1]-player1.frameHeight<platforms.coords[i].p1.getP()[1]:
            interactions[i].update()
            #print("i: ",i)

    #canvas.draw_line(player1.getCoordinates().getP(),platform2.p1.getP(),3,"blue")
    #canvas.draw_line(player1.getCoordinates().getP(),platform2.p2.getP(),3,"blue")
    platforms.draw(canvas)
    #canvas.draw_line((player1.getCoordinates() + Vector(0,player1.frameHeight/2)).getP(),(abs(platform2.p2.x - platform2.p1.x),platform2.p1.y),3,"yellow")
    #platform1.draw(canvas)
    #player2.update(canvas)
    player1.update(canvas)
Exemplo n.º 7
0
	def fromPython(self,param,rval,vval,nval,radius,ptype,flag,makeCellList=True,redobox=False):
		self.debug = False
		self.param = param
		self.multiopt = "single"
		self.usetype = "all"
		
		self.rval = rval
		self.vval = vval
		self.nval = nval
		self.radius = radius
		self.ptype = ptype
		self.flag = flag
		
		# For defect tracking
		vnorm = np.sqrt(self.vval[:,0]**2 + self.vval[:,1]**2+self.vval[:,2]**2)
		self.vhat = self.vval / np.outer(vnorm,np.ones((3,)))
		
		self.N = len(radius)
		self.sigma = np.mean(radius)
		print("New sigma is " + str(self.sigma))
		self.monodisperse = False
		
		
		# Generating new interaction assuming that it's not monodisperse and contains a single k
		#def __init__(self,param,sigma,ignore=False,debug=False):
		self.inter=Interaction(self.param,self.sigma,True,False)
		print (param.box)
		self.geom=geometries[param.constraint](param)
		
		if makeCellList:
			# Cut off the boxes. Curently only on  minimal z, for cornea. Others is less of a problem
			#if self.geom.manifold == 'sphere':
			#	zmin = np.amin(self.rval[:,2])-self.sigma
			#else:
			#	zmin = 'all'
			if redobox:
				rmin = np.zeros((3,))
				rmax = np.zeros((3,))
				rmin[0] = np.amin(self.rval[:,0])-self.sigma
				rmin[1] = np.amin(self.rval[:,1])-self.sigma
				rmin[2] = np.amin(self.rval[:,2])-self.sigma
				rmax[0] = np.amax(self.rval[:,0])+self.sigma
				rmax[1] = np.amax(self.rval[:,1])+self.sigma
				rmax[2] = np.amax(self.rval[:,2])+self.sigma
				# def makeCellList(self,frame=1,rmin='default',rmax='default'):
				self.makeCellList(1,rmin,rmax)
			else:
				self.makeCellList(1)
Exemplo n.º 8
0
    def test_manager(self):

        pl1, pl2 = get_two_players({
            'red': 0,
            'blue': 1
        }, {
            'red': 1,
            'blue': 1
        })
        interact = Interaction.Interaction(self.table)
        interact.interact(pl1, pl2)

        players = [pl1, pl2]
        Uni = Interaction.Universe(players, interact)
        manag = manager.Manager(Uni)
        manag.plot_and_update()
Exemplo n.º 9
0
 def __init__(self, fn='Text/nhk_easy.txt'):
     self.articles = SimpleUI.read_articles(fn)
     self.all_wordlist = []
     self.all_uniq_wordlist = []
     for a in self.articles.values():
         self.all_wordlist += a.wordlist
     self.all_wordlist = sorted(self.all_wordlist)
     self.all_uniq_wordlist = list(set(self.all_wordlist))
     self.word_index = {self.all_uniq_wordlist[i]:i for i in xrange(len(self.all_uniq_wordlist))}
     #zipf = {w:self.all_wordlist.count(w) for w in self.all_uniq_wordlist}
     #print sorted(zipf.values())
     #print sum([len(a.wordlist) for a in self.articles]), len(self.all_wordlist)
     self.recommender = MasteryRecommender()
     self.hci = Interaction(self)
     print 'Edge Density:', self.hci.knowledge.EdgeDensity()
     self.display_article = 0
Exemplo n.º 10
0
def grafic_average(a, s):
    file = 'account_results.csv'
    # cria listas para os resultados
    ag_list = []
    sh_list = []
    fun_list = []
    if os.path.exists(file):
        os.remove(file)
    with open(file, 'a') as f:
        f.write('n_agentes; n_lojas; satisfacao media; custo medio das lojas, media das contas das lojas e a media'
                'das contas dos agentes\n')
        for i in range(len(a)) and range(len(s)):
            # cria lista de resultados para o gráfico
            agent, shop = Interaction.main(a[i], s[i])
            avg_fun = sum([i.fun for i in agent]) / len(agent)
            avg_cost = sum([i.cost for i in shop]) / len(shop)
            avg_shop = sum([i.account.balance for i in shop]) / len(shop)
            avg_agent = sum([i.account.balance for i in agent]) / len(agent)
            f.write('{}; {}; {:.2f}; {:.2f}; {:.2f}; {:.2f}'.format(a[i], s[i], avg_fun, avg_cost, avg_shop, avg_agent))
            f.write('\n')
            fun_list.append(avg_fun)
            ag_list.append(avg_agent)
            sh_list.append(avg_shop)
    # cria o gráfico
    plt.plot(a, fun_list, color='#17a589', label='satisfação média')
    plt.plot(a, ag_list, color='red', label='Saldo médio das contas dos agente')
    plt.plot(a, sh_list, color='#f4d03f', label='Saldo médio das contas das lojas')
    plt.legend(loc='right', shadow=True)
    plt.xlabel('número de agentes')
    plt.show()
Exemplo n.º 11
0
def draw(canvas):
    global interactions, addedInteractions
    lv1.update(canvas)
    platforms.draw(canvas)

    if not addedInteractions:
        for i in range(len(platforms.getCoords())):
            interaction = Interaction(player1, platforms.coords[i])
            interactions.append(interaction)
        addedInteractions = True

    for i in range(len(platforms.getCoords())):
        platforms.coords[i].p1 = Vector(
            platforms.coords[i].getp1().getP()[0],
            platforms.coords[i].getp1().getP()[1] + 0.5)
        platforms.coords[i].p2 = Vector(
            platforms.coords[i].getp2().getP()[0],
            platforms.coords[i].getp2().getP()[1] + 0.5)

        tempPlatform = Platform2(0)
        if platforms.coords[i].p1.getP()[1] > 700:
            platforms.coords.pop(i)
            if i > 1:
                while not (abs(tempPlatform.getx1() - platforms.coords[
                        i - 1].getx1()) > platforms.DISTANCE * platforms.difficulty or \
                                       abs(tempPlatform.getx2() - platforms.coords[
                                               i - 1].getx2()) > platforms.DISTANCE * platforms.difficulty):
                    tempPlatform = Platform2(0)
            platforms.coords.insert(i, tempPlatform)
            tempInteraction = Interaction(player1, tempPlatform)
        else:
            tempInteraction = Interaction(player1, platforms.coords[i])
        interactions.pop(i)
        interactions.insert(i, tempInteraction)

    for i in range(len(interactions)):

        if platforms.coords[i].covers(player1.pos):
            interactions[i].update()
            # print("i: ",i)

    platforms.draw(canvas)
    player1.update(canvas)
Exemplo n.º 12
0
    def __init__(self,
                 globalWorkingDir,
                 localWorkingDir,
                 pilotJob=None,
                 rank=None,
                 nonMPIMode=False,
                 outputDir=None,
                 dumpEventOutputs=False):
        threading.Thread.__init__(self)
        self.globalWorkingDir = globalWorkingDir
        self.localWorkingDir = localWorkingDir
        self.currentDir = None
        # communication channel
        self.comm = Interaction.Receiver(rank=rank, nonMPIMode=nonMPIMode)
        self.rank = self.comm.getRank()
        # database backend
        self.db = Database.Backend(self.globalWorkingDir)
        # logger
        self.tmpLog = Logger.Logger(filename='Yoda.log')
        self.tmpLog.info("Global working dir: %s" % self.globalWorkingDir)
        self.initWorkingDir()
        self.tmpLog.info("Current working dir: %s" % self.currentDir)
        self.failed_updates = []
        self.outputDir = outputDir
        self.dumpEventOutputs = dumpEventOutputs

        self.pilotJob = pilotJob

        self.cores = 10
        self.jobs = []
        self.jobRanks = []
        self.readyEventRanges = []
        self.runningEventRanges = {}
        self.finishedEventRanges = []

        self.readyJobsEventRanges = {}
        self.runningJobsEventRanges = {}
        self.finishedJobsEventRanges = {}
        self.stagedOutJobsEventRanges = {}

        self.updateEventRangesToDBTime = None

        self.jobMetrics = {}
        self.jobsTimestamp = {}
        self.jobsRuningRanks = {}

        signal.signal(signal.SIGTERM, self.stop)
        signal.signal(signal.SIGQUIT, self.stop)
        signal.signal(signal.SIGSEGV, self.stop)
        signal.signal(signal.SIGXCPU, self.stop)
        signal.signal(signal.SIGUSR1, self.stop)
        signal.signal(signal.SIGBUS, self.stop)
Exemplo n.º 13
0
 def attack(self, gameStateObj):
     if self.target_to_interact_with:
         if self.item_to_use:
             if self.item_to_use in self.unit.items:
                 self.unit.equip(self.item_to_use)
                 if self.item_to_use.weapon or self.item_to_use.spell:
                     self.unit.displaySingleAttack(gameStateObj, self.target_to_interact_with, self.item_to_use)
                 defender, splash = Interaction.convert_positions(gameStateObj, self.unit, self.unit.position, self.target_to_interact_with, self.item_to_use)
                 # print('AI', self.unit, defender, self.unit.position, defender.position)
                 gameStateObj.combatInstance = Interaction.start_combat(gameStateObj, self.unit, defender, self.target_to_interact_with, splash, self.item_to_use, ai_combat=True)
                 gameStateObj.stateMachine.changeState('combat')
                 if isinstance(defender, UnitObject.UnitObject) and self.unit.checkIfEnemy(defender):
                     self.unit.handle_fight_quote(defender, gameStateObj)
             elif 'steal' in self.unit.status_bundle:
                 unit = gameStateObj.get_unit_from_pos(self.target_to_interact_with)
                 unit.remove_item(self.item_to_use)
                 self.unit.add_item(self.item_to_use)
                 # Make most recently acquired item droppable
                 if self.unit.team != 'player':
                     for item in self.unit.items:
                         item.droppable = False
                     self.item_to_use.droppable = True
                 self.unit.handle_steal_banner(self.item_to_use, gameStateObj)
         else:
             tile_info = gameStateObj.map.tile_info_dict[self.target_to_interact_with]
             tile = gameStateObj.map.tiles[self.target_to_interact_with]
             if 'Enemy_Seize' in tile_info:
                 if self.unit.position != self.target_to_interact_with:
                     return # Didn't actually reach Seize point
                 self.unit.seize(gameStateObj)
             elif 'Destructible' in tile_info:
                 gameStateObj.map.destroy(tile, gameStateObj)
             elif 'Locked' in tile_info:
                 self.unit.unlock(self.target_to_interact_with, gameStateObj)
             elif 'Escape' or 'Thief_Escape' in tile_info:
                 if self.unit.position != self.target_to_interact_with:
                     return # Didn't actually reach ThiefEscape point
                 self.unit.escape(gameStateObj)
Exemplo n.º 14
0
    def test_wealth_growth_nd(self):

        pl1, pl2 = get_two_players({
            'red': 0,
            'blue': 0
        }, {
            'red': 1,
            'blue': 1
        })
        interact = Interaction.Interaction(self.table)
        interact.interact(pl1, pl2)
        new_wealth_pl1 = pl1.wealth
        new_wealth_pl2 = pl2.wealth
        self.assertEqual(new_wealth_pl1, self.table[0, 1])
        self.assertEqual(new_wealth_pl2, self.table[1, 0])
Exemplo n.º 15
0
    def __init__(self, globalWorkingDir, localWorkingDir):
        self.globalWorkingDir = globalWorkingDir
        self.localWorkingDir = localWorkingDir
        self.currentDir = None
        # communication channel
        self.comm = Interaction.Receiver()
        self.rank = self.comm.getRank()
        # database backend
        self.db = Database.Backend(self.globalWorkingDir)
        # logger
        self.tmpLog = Logger.Logger()
        self.tmpLog.info("Global working dir: %s" % self.globalWorkingDir)
        self.initWorkingDir()
        self.tmpLog.info("Current working dir: %s" % self.currentDir)
        self.failed_updates = []

        signal.signal(signal.SIGTERM, self.stop)
Exemplo n.º 16
0
    def __init__(self, gameStateObj, upkeep=True):
        # Initial setup
        self.upkeep = upkeep  # Whether I'm running this on upkeep or on endstep
        self.current_phase = gameStateObj.phase.get_current_phase()
        self.previous_phase = gameStateObj.phase.get_previous_phase()
        affected_units = [
            unit for unit in gameStateObj.allunits
            if unit.position and unit.status_effects
        ]
        if self.upkeep:
            self.units = [
                unit for unit in affected_units
                if unit.team == self.current_phase
            ]
        else:
            self.units = [
                unit for unit in affected_units
                if unit.team == self.previous_phase
            ]
        logger.info('Building Status_Processor: %s %s %s', self.upkeep,
                    self.current_phase, self.previous_phase)

        # State control
        self.current_unit = None
        self.current_unit_statuses = []
        self.current_status = None
        self.status_index = 0
        self.state = CustomObjects.StateMachine('begin')
        self.state_buffer = False

        # Animation properties
        self.time_spent_on_each_status = 1200  # Only if it has a onetime animation
        self.start_time_for_this_status = Engine.get_time()

        # Health bar
        self.health_bar = Interaction.HealthBar('splash', None, None)

        # Waiting timer
        self.wait_time = 200
        self.started_waiting = Engine.get_time()
Exemplo n.º 17
0
 def determine_utility(self, move, target, item, gameStateObj):
     defender, splash = Interaction.convert_positions(gameStateObj, self.unit, move, target, item)
     if defender or splash:
         # if QUICK_MOVE and self.unit.position != move: # Just in case... This is needed!
         #     self.quick_move(move, gameStateObj, test=True)
         if item.spell:
             tp = self.compute_priority_spell(defender, splash, move, item, gameStateObj)
         elif item.weapon:
             tp = self.compute_priority_weapon(defender, splash, move, item, gameStateObj)
         else:
             tp = self.compute_priority_item(defender, splash, move, item, gameStateObj)
         unit = gameStateObj.get_unit_from_pos(target)
         if unit:
             name = unit.name
         else:
             name = '--'
         logger.debug("Choice %s - Weapon: %s, Position: %s, Target: %s, Target's Position: %s", tp, item.name, move, name, target)
         if tp > self.max_tp:
             self.target_to_interact_with = target
             self.position_to_move_to = move
             self.item_to_use = item
             self.max_tp = tp
Exemplo n.º 18
0
from Interaction import *

hci = Interaction("Genki12")

while True:
    response = hci.request()
    if response.end_of_assessment:
        print 'end'
        break
    else:
        print hci.num_assessment_answered + 1, '.', response.mastery_iter.sentence, response.message
        ans = input()
        if ans == 1:
            hci.response(StudentResponse.UNDERSTOOD)
        elif ans == 0:
            hci.response(StudentResponse.NOT_UNDERSTOOD)
Exemplo n.º 19
0
def GetFile(subtitle_file_io, path, file_name):
    """ 
        Get subtitle file from BytesIO object. subtitle_file_io is file like
        object that contains either a single subtitle file or a zip file. 
        path specify the directory in whice the subtitle will be saved. The 
        file_name specify the name for the subtitle. If the subtitle_file_io is 
        a zip file, will extract all the subtitles under it, otherwise, will 
        save the file in the given location.

        Note: will use the original name if: 
            a. file_name is empty 
            b. there is more then one file in the archive

        In case of success, returns true, else false
    """
    from Logs import INFO as INFO_LOGS
    from Logs import WARN as WARN_LOGS
    from Logs import DIRECTION as DIRC_LOGS

    import Interaction

    writeLog = Interaction.getInteractor().writeLog

    is_success = False
    subtitle_directory = os.path.abspath(path)
    subtitle_full_path = os.path.join(subtitle_directory, file_name)

    writeLog(INFO_LOGS.STARTING_SUBTITLE_DOWNLOAD_PROCEDURE)
    writeLog(INFO_LOGS.DESTINATION_DIRECTORY_FOR_SUBTITLE % subtitle_directory)

    file_is_zip = zipfile.is_zipfile(subtitle_file_io)

    if file_is_zip:
        try:
            with zipfile.ZipFile(subtitle_file_io, "r") as zfile:
                # Get the file names of the subtitles in the archive.
                # Filtering out any other file types
                filter_func = lambda x: x.lower().endswith(tuple(GetSubtitlesExtensions()))
                sub_filenames = myfilter(filter_func, zfile.namelist())
                if not sub_filenames:
                    writeLog(WARN_LOGS.NO_SUBTITLE_FILES_IN_THE_ARCHIVE)
                else:
                    # If we have more than one subtitle file in the archive, we
                    # keep the original filenames that comes with the archive)
                    if len(sub_filenames) > 1:
                        writeLog(INFO_LOGS.GOT_SEVERAL_FILES_IN_THE_ARCHIVE)
                        for file_name in sub_filenames:
                            # Write the file with the original filename
                            file_path = os.path.join(subtitle_directory, file_name)
                            open(file_path, "wb").write(zfile.open(file_name).read())
                            writeLog(INFO_LOGS.EXTRACTED_SUBTITLE_FILE % file_name)
                    else:
                        # If the file_name was empty, we keep the original also
                        if not file_name:
                            subtitle_full_path = os.path.join(subtitle_directory, sub_filenames[0])
                        sub_content = zfile.open(sub_filenames[0]).read()
                        open(subtitle_full_path, "wb").write(sub_content)
                        writeLog(INFO_LOGS.EXTRACTED_SUBTITLE_FILE % subtitle_full_path)
            # Notify successful extraction
            writeLog(INFO_LOGS.SUCCESSFULL_EXTRACTION_FROM_ARCHIVE)
            is_success = True
        except Exception as eX:
            WriteDebug("Failed constructing ZipFile object: %s" % eX)
            writeLog(WARN_LOGS.FAILED_EXTRACTING_SUBTITLE_FILE_FROM_ARCHIVE)
    # If the file is simple subtitle text file
    else:
        try:
            with open(subtitle_full_path, "wb") as sub_file:
                subtitle_file_io.seek(0)
                content = subtitle_file_io.getvalue()
                sub_file.write(content)
        except Exception as eX:
            WriteDebug("Failed saving subtitle as simple text file: %s" % eX)
            writeLog(WARN_LOGS.FAILED_SAVING_SUBTITLE_SIMPLE_FILE)
        is_success = True
    return is_success
Exemplo n.º 20
0
#!/usr/bin/env python
import roslib
roslib.load_manifest('pr2_pbd_interaction');

import sys
import signal
import rospy
from Interaction import *

def signal_handler(signal, frame):
    # The following makes sure the state of a user study is saved, so that it can be recovered
    global interaction
    interaction.save_experiment_state()
    print 'Program Terminated!!'
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGQUIT, signal_handler)

if __name__ == "__main__":
    global interaction
    rospy.init_node('pr2_pbd_interaction', anonymous=True)
    interaction = Interaction()
    #rospy.spin()
    while(not rospy.is_shutdown()):
        interaction.update()
Exemplo n.º 21
0
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 22 10:41:10 2016

@author: Lina492375qW1188
"""

import Create, Deform, Interaction, Construct
#----------------- Number of atom ------------------#
xmax = 150 # num of atoms in x-dir = (2*xmax+1, 2*xmax)
ymax = 50 # num of atoms in y-dir = ymax*4

#----------------- Initialization ------------------#
create = Create.Create(xmax,ymax)
deform = Deform.Deform()
interaction = Interaction.Interaction(create.ymax)
infile='data.unknown'
construct = Construct.Construct(infile)

#---------- Rolling, Set bond and angle ------------#
# action choices: (a)create plane (b)create paper roll.
action = '(b)'

if action == '(a)':
    coord1 = create.trigonal()
elif action == '(b)':
    coord1 = deform.rolling(create.trigonal())
    
bond1 = interaction.bond(coord1)

angle1 = interaction.angle(coord1)
Exemplo n.º 22
0
def Game(x, y):
    os.system("cls")
    varRand = randint(1, 4)

    print(' ')
    print(x, y)
    Description(x, y, descriptionMap)
    print(' ')
    print("1 = Intéragir")
    print("2 = Se déplacer")
    print("3 = Ouvrir son inventaire")
    print("4 = Ouvrir la MAP")
    print("5 = Voir la quête en cours")
    print("6 = Vos stats")
    print("7 = Sauvegarder")

    joueur = int(input())
    if joueur == 1:
        if str(x) + "," + str(y) in interaction:
            if interaction[str(x) + "," + str(y)][4] == "oui":
                Interaction(x, y, backpack)
                Game(x, y)
            else:
                print("Il n'y a pas d'interaction possible ici")
                Game(x, y)
        else:
            print("Il n'y a pas d'interaction possible ici")
            Game(x, y)

    elif joueur == 2:
        print("Vous vous déplacez.")
        m = Mouvement(x, y)
        if varRand == 3:
            c = Combat(OrdreDePassage(PickAMonster()))
            if c == "perdu":
                quit()
            AjouterInventaire(backpack, "300", "argent")
        Game(m[0], m[1])

    elif joueur == 3:
        test = False
        while test == False:
            print(
                "Vous êtes dans votre sac magique, veuillez choisir l'une des sacoches :"
            )
            print("1 = La sacoche à potions")
            print("2 = La sacoche à équipements")
            print("3 = La sacoche d'objets de quête")
            print("4 = Votre bourse d'argent")
            print("5 = Retour")
            b = int(input())
            test = ParcourirInventaire(backpack, b)

        Game(x, y)
    elif joueur == 4:
        fenetre = tk.Tk()
        photo = tk.PhotoImage(file='MapPrologue.png')
        label = tk.Label(fenetre, image=photo)
        label.pack()
        print("FERMER LA MAP AVANT TOUTE AUTRE ACTION OU LE JEU CRASHERA")
        Game(x, y)
        fenetre.mainloop()

    elif joueur == 5:
        print(dicoQueteActive["g"])
        Game(x, y)

    elif joueur == 6:
        VoirStat()
        attendre = input()
        Game(x, y)

    elif joueur == 7:
        Save(x, y, backpack)
        Game(x, y)

    else:
        print("Vous avez mal tapé ! Veuillez recommencer.")
        Game(
            x,
            y,
        )
Exemplo n.º 23
0
def home_data():
    action = request.form['submit']

    if action == "infer":
        info = {}
        info['weather'] = request.form.get("weather")
        info['temperature'] = request.form.get("temperature")
        info['humidity'] = request.form.get("humidity")
        info['wind'] = request.form.get("wind")
        info['gender'] = request.form.get("gender")
        info['cold'] = request.form.get("cold")
        info['style'] = request.form.get("style")

        ret = Interaction.GetRet(info)

        return render_template('index.html',
                               Suggestion=ret[0],
                               Rules=ret[1],
                               Description=ret[2])

    elif action == "all_check":
        with open("rules/rules.txt") as f:
            rules = f.read()
        return render_template('index.html', all=rules.decode('utf-8'))

    elif action == "add":
        rule = {}
        rule["condition"] = request.form.get("add_condition")
        rule["result"] = request.form.get("add_result")
        rule["description"] = request.form.get("add_description")
        ret = Interaction.AddRule(rule)

        with open("rules/rules.txt") as f:
            rules = f.read()

        if ret == True:
            flash(u"添加规则成功", 'success')
        else:
            flash(u"添加规则失败", 'error')

        return render_template('index.html', all=rules.decode('utf-8'))

    elif action == "delete":
        id = request.form.get("delete_id")
        ret = Interaction.DeleteRule(int(id))

        with open("rules/rules.txt") as f:
            rules = f.read()

        if ret == True:
            flash(u"删除规则成功", 'success')
        else:
            flash(u"删除规则失败", 'error')

        return render_template('index.html', all=rules.decode('utf-8'))

    elif action == "modify":
        rule = {}
        rule["id"] = int(request.form.get("modify_id"))
        rule["condition"] = request.form.get("modify_condition")
        rule["result"] = request.form.get("modify_result")
        rule["description"] = request.form.get("modify_description")
        ret = Interaction.ModifyRule(rule)

        with open("rules/rules.txt") as f:
            rules = f.read()

        if ret == True:
            flash(u"修改规则成功", 'success')
        else:
            flash(u"修改规则失败", 'error')

        return render_template('index.html', all=rules.decode('utf-8'))

    elif action == "reset":
        Interaction.Reset()
        with open("rules/rules.txt") as f:
            rules = f.read()
        return render_template('index.html', all=rules.decode('utf-8'))

    else:
        return render_template('index.html')
Exemplo n.º 24
0
def draw(canvas):
    global interactions, addedInteractions, numberOfPlatforms, framecount, timer,numberOfGoats,goats
    time = Timer()
    lv1background.update(canvas)
    platforms.draw(canvas)
    time.draw(canvas)
    scoreCount.update(canvas)
    lifeBar.update(canvas)
    flood.draw(canvas)

    if not addedInteractions:
        for i in range(len(platforms.getCoords())):
            interaction = Interaction(player1, platforms.coords[i])
            interactions.append(interaction)
        addedInteractions = True

    for i in range(len(platforms.getCoords())):
        platforms.coords[i].p1 = Vector(platforms.coords[i].getp1().getP()[0],
                                        platforms.coords[i].getp1().getP()[1] + 1)
        platforms.coords[i].p2 = Vector(platforms.coords[i].getp2().getP()[0],
                                        platforms.coords[i].getp2().getP()[1] + 1)

        tempPlatform = Platform2(0)
        if platforms.coords[i].p1.y > 700:
            platforms.coords.pop(i)
            if i > 1:
                while not (abs(tempPlatform.getx1() - platforms.coords[
                        i - 1].getx1()) > platforms.DISTANCE * platforms.difficulty or \
                                       abs(tempPlatform.getx2() - platforms.coords[
                                               i - 1].getx2()) > platforms.DISTANCE * platforms.difficulty):
                    tempPlatform = Platform2(0)
            platforms.coords.insert(i, tempPlatform)
            tempInteraction = Interaction(player1, tempPlatform)
        else:
            tempInteraction = Interaction(player1, platforms.coords[i])
        interactions.pop(i)
        interactions.insert(i, tempInteraction)
        if random.randint(0,1) > 0.5 and framecount % 360 == 0 and numberOfGoats <3 and platforms.coords[i].p1.y < player1.pos.y :  # numberOfPlatforms % 5 == 0 and not madeGoat
            makeGoat(platforms.coords[i])
            numberOfGoats+=1
        goatsToPop = []
        for j in range(len(goats)):
            if platforms.coords[i] == goats[j].platform:
                goats[j].pos = Vector(goats[j].pos.x,platforms.coords[i].p1.y-platforms.coords[i].thickness-goats[j].frameHeight/2)
                goats[j].update(canvas)
                if goats[j].isColliding(player1):
                    if goats[j].harmsPlayer(player1):
                        player1.lifePoints -=1
                        print("rekt")
                        goatsToPop.append(goats[j])
                        numberOfGoats -= 1
            if goats[j].pos.y > 630:
                goatsToPop.append(goats[j])
                numberOfGoats-=1
        for j in range(len(goatsToPop)):
            goats.remove(goatsToPop[j])

    framecount += 1

    for i in range(len(interactions)):

        if platforms.coords[i].covers(player1.pos):
            interactions[i].update()

    platforms.draw(canvas)

    player1.update(canvas)
Exemplo n.º 25
0
    def __init__(self, param, filename, ignore=False, debug=False):
        self.param = param
        # Outdated list of geometries
        #geometries={'sphere':GeometrySphere,'plane':GeometryPeriodicPlane,'none':Geometry,'tube':GeometryTube,'peanut':GeometryPeanut,'hourglass':GeometryHourglass}
        geometries = {
            'sphere': GeometrySphere,
            'plane': GeometryPlane,
            'plane_periodic': GeometryPeriodicPlane,
            'none': Geometry,
            'tube': GeometryTube,
            'peanut': GeometryPeanut,
            'hourglass': GeometryHourglass
        }
        print "Processing file : ", filename
        data = ReadData(filename)
        x, y, z = np.array(data.data[data.keys['x']]), np.array(
            data.data[data.keys['y']]), np.array(data.data[data.keys['z']])
        vx, vy, vz = np.array(data.data[data.keys['vx']]), np.array(
            data.data[data.keys['vy']]), np.array(data.data[data.keys['vz']])
        try:
            nx, ny, nz = np.array(data.data[data.keys['nx']]), np.array(
                data.data[data.keys['ny']]), np.array(
                    data.data[data.keys['nz']])
        except KeyError:
            nx, ny, nz = np.zeros(np.shape(x)), np.zeros(
                np.shape(y)), np.zeros(np.shape(z))
        self.monodisperse = False
        self.N = len(x)
        if not data.keys.has_key('radius'):
            # MISSING: read them in from the initial configuration
            self.radius = np.array([1.0 for i in range(self.N)])
            self.monodisperse = True
            #self.sigma=1.0
        else:
            self.radius = np.array(data.data[data.keys['radius']])
            #self.sigma = np.mean(self.radius)
        if data.keys.has_key('type'):
            self.ptype = data.data[data.keys['type']]
        else:
            self.ptype = np.ones((self.N, ))
        if data.keys.has_key('flag'):
            self.flag = data.data[data.keys['flag']]
        self.rval = np.column_stack((x, y, z))
        self.vval = np.column_stack((vx, vy, vz))
        self.nval = np.column_stack((nx, ny, nz))
        # Create the right geometry environment (TBC):
        self.geom = geometries[param.constraint](param)
        print self.geom
        # Create the Interaction class
        self.inter = Interaction(self.param, self.radius, ignore)

        if self.geom.periodic:
            # Apply periodic geomtry conditions just in case (there seem to be some rounding errors floating around)
            self.rval = self.geom.ApplyPeriodic2d(self.rval)
            self.rval = self.geom.ApplyPeriodic12(np.array([0.0, 0.0, 0.0]),
                                                  self.rval)
        # unit normal to the surface (only sphere so far)
        vel = np.sqrt(self.vval[:, 0]**2 + self.vval[:, 1]**2 +
                      self.vval[:, 2]**2)
        self.vhat = ((self.vval).transpose() / (vel).transpose()).transpose()

        # Create the cell list
        cellsize = param.nlist_rcut
        if cellsize > 5 * self.inter.sigma:
            cellsize = 5 * self.inter.sigma
            print "Warning! Reduced the cell size to manageable proportions (5 times mean radius). Re-check if simulating very long objects!"
        self.clist = CellList(self.geom, cellsize)
        # Populate it with all the particles:
        for k in range(self.N):
            self.clist.add_particle(self.rval[k, :], k)
        #self.clist.printMe()

        if debug:
            fig = plt.figure()
            ax = fig.add_subplot(111, projection='3d')
            ax.scatter(self.rval[:, 0],
                       self.rval[:, 1],
                       self.rval[:, 2],
                       zdir='z',
                       c='b')
Exemplo n.º 26
0
class Configuration:
    def __init__(self, param, filename, ignore=False, debug=False):
        self.param = param
        # Outdated list of geometries
        #geometries={'sphere':GeometrySphere,'plane':GeometryPeriodicPlane,'none':Geometry,'tube':GeometryTube,'peanut':GeometryPeanut,'hourglass':GeometryHourglass}
        geometries = {
            'sphere': GeometrySphere,
            'plane': GeometryPlane,
            'plane_periodic': GeometryPeriodicPlane,
            'none': Geometry,
            'tube': GeometryTube,
            'peanut': GeometryPeanut,
            'hourglass': GeometryHourglass
        }
        print "Processing file : ", filename
        data = ReadData(filename)
        x, y, z = np.array(data.data[data.keys['x']]), np.array(
            data.data[data.keys['y']]), np.array(data.data[data.keys['z']])
        vx, vy, vz = np.array(data.data[data.keys['vx']]), np.array(
            data.data[data.keys['vy']]), np.array(data.data[data.keys['vz']])
        try:
            nx, ny, nz = np.array(data.data[data.keys['nx']]), np.array(
                data.data[data.keys['ny']]), np.array(
                    data.data[data.keys['nz']])
        except KeyError:
            nx, ny, nz = np.zeros(np.shape(x)), np.zeros(
                np.shape(y)), np.zeros(np.shape(z))
        self.monodisperse = False
        self.N = len(x)
        if not data.keys.has_key('radius'):
            # MISSING: read them in from the initial configuration
            self.radius = np.array([1.0 for i in range(self.N)])
            self.monodisperse = True
            #self.sigma=1.0
        else:
            self.radius = np.array(data.data[data.keys['radius']])
            #self.sigma = np.mean(self.radius)
        if data.keys.has_key('type'):
            self.ptype = data.data[data.keys['type']]
        else:
            self.ptype = np.ones((self.N, ))
        if data.keys.has_key('flag'):
            self.flag = data.data[data.keys['flag']]
        self.rval = np.column_stack((x, y, z))
        self.vval = np.column_stack((vx, vy, vz))
        self.nval = np.column_stack((nx, ny, nz))
        # Create the right geometry environment (TBC):
        self.geom = geometries[param.constraint](param)
        print self.geom
        # Create the Interaction class
        self.inter = Interaction(self.param, self.radius, ignore)

        if self.geom.periodic:
            # Apply periodic geomtry conditions just in case (there seem to be some rounding errors floating around)
            self.rval = self.geom.ApplyPeriodic2d(self.rval)
            self.rval = self.geom.ApplyPeriodic12(np.array([0.0, 0.0, 0.0]),
                                                  self.rval)
        # unit normal to the surface (only sphere so far)
        vel = np.sqrt(self.vval[:, 0]**2 + self.vval[:, 1]**2 +
                      self.vval[:, 2]**2)
        self.vhat = ((self.vval).transpose() / (vel).transpose()).transpose()

        # Create the cell list
        cellsize = param.nlist_rcut
        if cellsize > 5 * self.inter.sigma:
            cellsize = 5 * self.inter.sigma
            print "Warning! Reduced the cell size to manageable proportions (5 times mean radius). Re-check if simulating very long objects!"
        self.clist = CellList(self.geom, cellsize)
        # Populate it with all the particles:
        for k in range(self.N):
            self.clist.add_particle(self.rval[k, :], k)
        #self.clist.printMe()

        if debug:
            fig = plt.figure()
            ax = fig.add_subplot(111, projection='3d')
            ax.scatter(self.rval[:, 0],
                       self.rval[:, 1],
                       self.rval[:, 2],
                       zdir='z',
                       c='b')

    # Tangent bundle: Coordinates in an appropriate coordinate system defined on the manifold
    # and the coordinate vectors themselves, for all the particles
    def getTangentBundle(self):
        self.x1, self.x2, self.e1, self.e2 = self.geom.TangentBundle(self.rval)
        return self.x1, self.x2, self.e1, self.e2

    def rotateFrame(self, axis, rot_angle):
        self.rval = self.geom.RotateVectorial(self.rval, axis, -rot_angle)
        self.vval = self.geom.RotateVectorial(self.vval, axis, -rot_angle)
        self.nval = self.geom.RotateVectorial(self.nval, axis, -rot_angle)
        self.nval = (
            (self.nval).transpose() /
            (np.sqrt(np.sum(self.nval**2, axis=1))).transpose()).transpose()
        self.vel = np.sqrt(self.vval[:, 0]**2 + self.vval[:, 1]**2 +
                           self.vval[:, 2]**2)

    # Need to redo boxes after something like that
    def redoCellList(self):
        del self.clist
        # Create the cell list
        cellsize = self.param.nlist_rcut
        if cellsize > 5 * self.inter.sigma:
            cellsize = 5 * self.inter.sigma
            print "Warning! Reduced the cell size to manageable proportions (5 times mean radius). Re-check if simulating very long objects!"
        self.clist = CellList(self.geom, cellsize)
        # Populate it with all the particles:
        for k in range(self.N):
            self.clist.add_particle(self.rval[k, :], k)
        #self.clist.printMe()

    def getNeighbours(self, i, mult, dmax):
        # Find potential neighbours from neighbour list first
        cneighbours = self.clist.get_neighbours(self.rval[i, :])
        #print "Cell list neighbours: " + str(len(cneighbours))
        drvec0 = self.geom.ApplyPeriodic2d(self.rval[cneighbours, :] -
                                           self.rval[i, :])
        dist = np.sqrt(drvec0[:, 0]**2 + drvec0[:, 1]**2 + drvec0[:, 2]**2)
        #dist=self.geom.GeodesicDistance12(self.rval[cneighbours,:],self.rval[i,:])
        #print "Mean cutoff: " + str(mult*dmax)
        if self.monodisperse:
            neighbours = [
                cneighbours[index] for index, value in enumerate(dist)
                if value < mult * dmax
            ]
        else:
            neighbours = [
                cneighbours[index] for index, value in enumerate(dist)
                if value < mult *
                (self.radius[i] + self.radius[cneighbours[index]])
            ]
        ## Stupid one for debugging purposes:
        #dist=self.geom.GeodesicDistance12(self.rval,self.rval[i,:])
        #neighbours = [index for index, value in enumerate(dist) if value < mult*(self.radius[i]+self.radius[index])]
        neighbours.remove(i)
        #print "Contact neighbours: " + str(len(neighbours))
        #print neighbours
        drvec = self.geom.ApplyPeriodic2d(self.rval[neighbours, :] -
                                          self.rval[i, :])
        dr = np.sqrt(drvec[:, 0]**2 + drvec[:, 1]**2 + drvec[:, 2]**2)
        return neighbours, drvec, dr

    def compute_energy_and_pressure(self):
        eng = np.zeros(self.N)
        press = np.zeros(self.N)
        ncon = np.zeros(self.N)
        stress = np.zeros((self.N, 3, 3))
        for i in range(self.N):
            neighbours, drvec, dr = self.getNeighbours(i, self.inter.getMult(),
                                                       self.inter.getDmax())
            ncon[i] = len(neighbours)
            eng[neighbours] += self.inter.getEnergy(i, neighbours, drvec, dr)
            press_val, stress_val = self.inter.getStresses(
                i, neighbours, drvec, dr)
            stress[neighbours, :, :] += stress_val
            press[neighbours] += press_val
        return [eng, press, ncon, stress]

    # Flat case statistics (or other geometry statistics, if desired)
    def getStatsBasic(self, debug=False):
        vel2 = self.vval[:, 0]**2 + self.vval[:, 1]**2 + self.vval[:, 2]**2
        vel2av = np.mean(vel2)
        phival = np.pi * np.sum(self.radius**2) / self.geom.area
        ndensity = self.N / self.geom.area
        eng, press, ncon, stress = self.compute_energy_and_pressure()
        pressure = np.sum(press) / self.geom.area
        fmoment = np.mean(press)
        energy = np.mean(eng)
        energytot = np.sum(eng)
        zav = np.mean(ncon)
        return vel2av, phival, ndensity, pressure, fmoment, energy, energytot, zav

    def getStatsBand(self, debug=False):
        ez = np.array([0, 0, 1])  # lab frame z-axis
        # The order parameter with v_0 still in it. Normalize in final polish
        orderparV = np.sum(vval, axis=0) / len(vval)
        orderpar = np.sum(nval, axis=0) / len(nval)
        print orderpar
        print orderparV
        direction = orderpar / np.linalg.norm(orderpar)
        directionV = orderparV / np.linalg.norm(orderparV)
        axisorth = np.cross(direction, directionV)
        axisval = np.linalg.norm(axisorth)
        alpha = np.arcsin(axisval)
        axisorth = axisorth / axisval
        axisnorm = np.cross(ez, directionV)
        axisnorm /= np.linalg.norm(axisnorm)

        print directionV
        print axisorth

        vel = np.sqrt(self.vval[:, 0]**2 + self.vval[:, 1]**2 +
                      self.vval[:, 2]**2)
        velnorm = ((self.vval).transpose() / (vel).transpose()).transpose()

        eng, press, stress = self.compute_energy_and_pressure()
        print np.shape(stress)
        # Project the stresses into the e,theta,phi components. The rr component hast to be 0, and the r cross components
        # belong to the projection. So they are not all that interesting.
        # We want the theta theta, theta phi, phi theta ant phi phi components (implicitly testing symmetries ...)
        # I give up on the notation. Stress is (N,3,3), the axes are (N,3). We want e_i sigma_ij e_j
        s_tt = np.sum(axisnorm * np.einsum('kij,j->ki', stress, axisnorm),
                      axis=1)
        s_tp = np.sum(axisnorm * np.einsum('kij,j->ki', stress, directionV),
                      axis=1)
        s_pt = np.sum(directionV * np.einsum('kij,j->ki', stress, axisnorm),
                      axis=1)
        s_pp = np.sum(directionV * np.einsum('kij,j->ki', stress, directionV),
                      axis=1)
        print np.shape(s_tt)
        # Mean density really makes no sense? Determined by the initial conditions in periodic boundary conditions.
        # I do not wish to set up artificial bins in a translationally invariant system
        vel_av = np.mean(vel)
        eng_av = np.mean(eng)
        press_av = np.mean(press)
        s_tt_av = np.mean(s_tt)
        s_tp_av = np.mean(s_tp)
        s_pt_av = np.mean(s_pt)
        s_pp_av = np.mean(s_pp)

        # Debugging output
        if debug == True:
            if HAS_MATPLOTLIB:
                fig = plt.figure()
                ax = fig.add_subplot(111, projection='3d')
                ax.scatter(rval[:, 0], rval[:, 1], rval[:, 2], zdir='z', c='b')
            else:
                print 'Error: Matplotlib does not exist on this machine, cannot plot system'

        return [
            vel_av, eng_av, press_av, s_tt_av, s_tp_av, s_pt_av, s_pp_av,
            alpha, direction, directionV, orderpar, orderparV
        ]
Exemplo n.º 27
0
 def Mpi_slave(self, result_out, buffer_size, compair):
     """
     Slave process
     @param compair: Comparison object
     """
     ar=Parse()
     status = MPI.Status()
     self.comm.send(1,dest=0, tag=1)
     root=Interaction()
     buffer=buffer_size
     flag_soft=True
     part=0
     while(status.tag!=0):
         #Mise en sommeil pour la reduction de consommation de ressource
         while not self.comm.Iprobe(source=0, tag=MPI.ANY_TAG):
             time.sleep(0.1)
         data = self.comm.recv(source=0, tag=MPI.ANY_TAG,status=status)
         if(status.tag==1):
             #Cree le noeud du soft
             if(flag_soft):
                 #compteur et nom du soft
                 root.setSoft(data[1],data[4])
                 flag_soft=False
             #Lancement de la comparaison
             result = compair.runComparison(data[0])
             #Parsing de la sortie
             ar.runParsing(data[1], data[2], data[3], data[5], data[6], result, root)                
             #Renvoyer le resultat de la ligne de commande
             self.comm.send(1,dest=status.source, tag=1)
             #Decrease the buffer
             buffer-=1
             #Vider le buffer
             if(buffer==0):
                 #Envoie des resultats
                 #self.comm.send(zlib.compress(root.getResult()), dest=1, tag=2)
                 self.Mpi_write_data(root, result_out, data[1], data[4], self.myrank, part)
                 #Vider le buffer
                 del(root)
                 #Remise a zero de l'arbre
                 root=Interaction()
                 #Reinitialisation du buffer
                 buffer=buffer_size
                 #Reinitialisation du flag soft
                 flag_soft=True
                 #Incrementation du numero de partie
                 part+=1
                 
         #Changement de soft
         elif(status.tag==2):
             #Envoie des resultats
             #self.comm.send(zlib.compress(root.getResult()), dest=1, tag=2)
             #Write data
             if(buffer!=buffer_size):
                 self.Mpi_write_data(root, result_out, data[0], data[1], self.myrank, part)
             #Reinitialisation du buffer
             buffer=buffer_size
             #Vider le buffer
             del(root)
             #Remise a zero de l'arbre
             root=Interaction()
             #Reinitialisation du flag soft
             flag_soft=True
             #Reinitialisation du numero de partie
             part=0
Exemplo n.º 28
0
import Neighbour
#import pexmd

# Inicializo parametros

# Particulas
part = Particles.PointParticles(8)
pos = np.array([.5, .5, .5]) + np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0],
                                         [0, 1, 1], [1, 0, 0], [1, 0, 1],
                                         [1, 1, 0], [1, 1, 1]])
part.x = pos
part.mass = np.zeros((8, 1), dtype=np.float32) + 1
# Caja
bx = Box.Box([0, 0, 0], [2, 2, 2], 'Fixed')
# Interaccion
LJ = Interaction.LennardJones(1.2, 1, 0.2)
# Integrador
verlet = Integrator.VelVerlet(0.01)
# Vecinos
vecinos = Neighbour.Neighbour()
pares = vecinos.build_list(part.x, "None")


def energia_cinetica(v):
    return 0.5 * sum(sum(v**2))


# Termalizamos
N = 2000
Epot = np.zeros((N, 1))
Ecin = np.zeros((N, 1))
Exemplo n.º 29
0
    for face in faces:
        print('anger: {}'.format(likelihood_name[face.anger_likelihood]))
        print('joy: {}'.format(likelihood_name[face.joy_likelihood]))
        print('surprise: {}'.format(likelihood_name[face.surprise_likelihood]))
        print(face.joy_likelihood)
        print("^-^")
        GlobalVariables.emotionJoy = face.joy_likelihood

        vertices = ([
            '({},{})'.format(vertex.x, vertex.y)
            for vertex in face.bounding_poly.vertices
        ])

        print('face bounds: {}'.format(','.join(vertices)))

    if response.error.message:
        raise Exception('{}\nFor more info on error messages, check: '
                        'https://cloud.google.com/apis/design/errors'.format(
                            response.error.message))


def run_local(args):
    if args.command == 'faces':
        detect_faces2(args.path)


if __name__ == '__main__':
    interact = Interaction.Webpage()
    startcycle()
Exemplo n.º 30
0
#!/usr/bin/env python
import roslib
roslib.load_manifest('pr2_pbd_interaction');

import sys
import signal
import rospy
from Interaction import *

def signal_handler(signal, frame):
    # The following makes sure the state of a user study is saved, so that it can be recovered
    global interaction
    interaction.saveExperimentState()
    print 'Program Terminated!!'
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGQUIT, signal_handler)

if __name__ == "__main__":
    global interaction
    rospy.init_node('pr2_pbd_interaction', anonymous=True)
    interaction = Interaction()
    #rospy.spin()
    while(not rospy.is_shutdown()):
        interaction.update()
Exemplo n.º 31
0
class SimpleUI:

    def __init__(self, fn='Text/nhk_easy.txt'):
        self.articles = SimpleUI.read_articles(fn)
        self.all_wordlist = []
        self.all_uniq_wordlist = []
        for a in self.articles.values():
            self.all_wordlist += a.wordlist
        self.all_wordlist = sorted(self.all_wordlist)
        self.all_uniq_wordlist = list(set(self.all_wordlist))
        self.word_index = {self.all_uniq_wordlist[i]:i for i in xrange(len(self.all_uniq_wordlist))}
        #zipf = {w:self.all_wordlist.count(w) for w in self.all_uniq_wordlist}
        #print sorted(zipf.values())
        #print sum([len(a.wordlist) for a in self.articles]), len(self.all_wordlist)
        self.recommender = MasteryRecommender()
        self.hci = Interaction(self)
        print 'Edge Density:', self.hci.knowledge.EdgeDensity()
        self.display_article = 0

    @staticmethod
    def read_articles(fn='Text/nhk_easy.txt', if_article=True, if_para=True, if_sentence=True):
        f = open(fn)
        articles ={}
        line_match = re.compile(r'(k\d{14})\s{4}(.*)\n')
        for line in f:
            match = line_match.match(line)
            if match:
                news_id = match.group(1)
                text = match.group(2)
                if if_article:
                    articles[news_id] = Article(news_id, text)
                if not if_para:
                    continue
                paras = re.split(' ',text)
                for pid in xrange(len(paras)):
                    news_para_id = news_id + '_para' + str(pid + 1)
                    if len(paras[pid].strip()) > 0:
                        articles[news_para_id] = Article(news_para_id, paras[pid].strip())
                        #print news_para_id, paras[pid]
                        if not if_sentence:
                            continue
                        sentences = re.split('。', paras[pid].strip())
                        for sid in xrange(len(sentences)):
                            news_para_sentence_id = news_para_id + '_s' + str(sid + 1)
                            if (len(sentences[sid].strip())) > 0:
                                articles[news_para_sentence_id] = Article(news_para_sentence_id, sentences[sid].strip() + '。')
                                #print news_para_sentence_id, sentences[sid].strip()
        return articles

    def mastery_iter(self, textbox, m, e):
        self.recommender.response(self.display_article, m, e)
        self.display_article = self.recommender.request(self.articles)

        textbox.delete('1.0', END)
        textbox.insert(END, self.display_article.text.replace(' ', '\n\n'))
        #textbox.insert(END, self.iter_news.next().replace(' ', '\n\n'))

    def kb_iter(self, textbox, m, e):
        if e > 0:
            self.hci.response(StudentResponse.UNDERSTOOD)
        else:
            self.hci.response(StudentResponse.NOT_UNDERSTOOD)
        res = self.hci.request()
        if res.process:
            self.display_article = self.articles[res.process.doc_id]
        else:
            return
        kb = self.hci.knowledge_boundary()
        print sum([kb.ProcessStatus[up.uniq_id] for up in kb.Knowledge.UniqueProcesses]),'/', len(kb.Knowledge.UniqueProcesses)
        textbox.delete('1.0', END)
        textbox.insert(END, self.display_article.text.replace(' ', '\n\n'))


    def build_graph(self):
        INTER_RATE = 0.6
        graph = [[False] * len(self.articles) for i in xrange(len(self.articles))]
        cnt = 0
        for i in xrange(len(self.articles)):
            for j in xrange(i+1, len(self.articles)):
                inter = self.articles.values()[i].inter(self.articles.values()[j])
                l1 = len(self.articles.values()[i].wordlist)
                l2 = len(self.articles.values()[j].wordlist)
                if l1 < l2 and inter >= l1 * INTER_RATE:
                    graph[i][j] = True
                    cnt += 1
                if l2 < l1 and inter >= l2 * INTER_RATE:
                    graph[j][i] = True
                    cnt += 1
        #print cnt, len(self.articles)
        return graph


    def main(self):

        #k = Knowledge(self)
        #return

        #self.build_graph()
        #return


        tk = Tk()
        tk.title('SimpleUI       NHK_easy     Sona Tithew')
        tk.resizable(0,0)
        textbox = Text(tk, font=tkFont.Font(size=12))
        self.display_article = self.recommender.request(self.articles)
        textbox.insert(END, self.display_article.text.replace(' ', '\n\n'))
        textbox.grid(row=0, column=0, columnspan=5)
        m = IntVar()
        m.set(2)
        Radiobutton(tk, text='0%', variable=m, value=4).grid(row=1, column=0, sticky=N + S + E + W)
        Radiobutton(tk, text='25%', variable=m, value=3).grid(row=1, column=1, sticky=N + S + E + W)
        Radiobutton(tk, text='50%', variable=m, value=2).grid(row=1, column=2, sticky=N + S + E + W)
        Radiobutton(tk, text='75%', variable=m, value=1).grid(row=1, column=3, sticky=N + S + E + W)
        Radiobutton(tk, text='100%', variable=m, value=0).grid(row=1, column=4, sticky=N + S + E + W)
        e = IntVar()
        e.set(1)
        #Radiobutton(tk, text='I prefer easier articles.', variable=e, value=0).grid(row=2, column=1, sticky=N + S + E + W)
        #Radiobutton(tk, text='I enjoy this article!', variable=e, value=1).grid(row=2, column=2, sticky=N + S + E + W)
        #Radiobutton(tk, text='I prefer harder articles.', variable=e, value=2).grid(row=2, column=3, sticky=N + S + E + W)
        #Button(tk, text='Submit', height=1, width=12, font=tkFont.Font(size=24), command = lambda: self.kb_iter(textbox, m.get(), e.get())).grid(row=3, column=1, columnspan=3)
        Button(tk, text='I prefer easier articles.', height=1, width=22, font=tkFont.Font(size=10),
               command=lambda: self.kb_iter(textbox, m.get(), 0)).grid(row=2, column=1, sticky=N + S + E + W)
        Button(tk, text='I enjoy this article.', height=1, width=18, font=tkFont.Font(size=10),
               command=lambda: self.kb_iter(textbox, m.get(), 1)).grid(row=2, column=2, sticky=N + S + E + W)
        Button(tk, text='I prefer harder articles.', height=1, width=22, font=tkFont.Font(size=10),
               command=lambda: self.kb_iter(textbox, m.get(), 2)).grid(row=2, column=3, sticky=N + S + E + W)
        tk.mainloop()
Exemplo n.º 32
0
    def __init__(self,
                 param,
                 filename_cells,
                 filename_faces,
                 ignore=False,
                 debug=False):
        self.param = param
        # Read the local data
        geometries = {
            'sphere': GeometrySphere,
            'plane': GeometryPlane,
            'plane_periodic': GeometryPeriodicPlane,
            'none': Geometry,
            'tube': GeometryTube,
            'peanut': GeometryPeanut,
            'hourglass': GeometryHourglass
        }
        print "Processing file : ", filename_cells
        data = ReadData(filename_cells)
        if data.keys.has_key('x'):
            x, y, z = np.array(data.data[data.keys['x']]), np.array(
                data.data[data.keys['y']]), np.array(data.data[data.keys['z']])
        else:
            print "Error: did not find positions in data file!"
            return 1
        self.N = len(x)
        if data.keys.has_key('vx'):
            vx, vy, vz = np.array(data.data[data.keys['vx']]), np.array(
                data.data[data.keys['vy']]), np.array(
                    data.data[data.keys['vz']])
        else:
            vx, vy, vz = np.zeros(np.shape(x)), np.zeros(
                np.shape(y)), np.zeros(np.shape(z))
        try:
            nx, ny, nz = np.array(data.data[data.keys['nx']]), np.array(
                data.data[data.keys['ny']]), np.array(
                    data.data[data.keys['nz']])
        except KeyError:
            nx, ny, nz = np.zeros(np.shape(x)), np.zeros(
                np.shape(y)), np.zeros(np.shape(z))
        if data.keys.has_key('fx'):
            fx, fy, fz = np.array(data.data[data.keys['fx']]), np.array(
                data.data[data.keys['fy']]), np.array(
                    data.data[data.keys['fz']])
        # Now some cell-specific things:
        # area  cell_area  cell_perim  cont_num  boundary
        if data.keys.has_key('area'):
            self.area_native = np.array(data.data[data.keys['area']])
        else:
            # Assume the default of pi
            self.area_native = 3.141592 * np.ones(np.shape(x))
        if data.keys.has_key('cell_area'):
            self.area = np.array(data.data[data.keys['cell_area']])
        if data.keys.has_key('cell_perim'):
            self.perim = np.array(data.data[data.keys['cell_perim']])
        if data.keys.has_key('cont_num'):
            self.ncon = np.array(data.data[data.keys['cont_num']])
        if data.keys.has_key('boundary'):
            self.boundary = np.array(data.data[data.keys['boundary']])
        if data.keys.has_key('type'):
            self.ptype = data.data[data.keys['type']]
        else:
            self.ptype = np.ones((self.N, ))
        if data.keys.has_key('flag'):
            self.flag = data.data[data.keys['flag']]
        self.rval = np.column_stack((x, y, z))
        self.vval = np.column_stack((vx, vy, vz))
        self.nval = np.column_stack((nx, ny, nz))
        self.fval = np.column_stack((fx, fy, fz))
        # Create the right geometry environment (TBC):
        self.geom = geometries[param.constraint](param)
        print self.geom
        # Create the Interaction class
        # Not yet created for the active vertex model
        #self.inter=Interaction(self.param,self.radius,ignore)

        # Again, not implemented yet. Keep it however, since this should eventually happen
        if self.geom.periodic:
            # Apply periodic geomtry conditions just in case (there seem to be some rounding errors floating around)
            self.rval = self.geom.ApplyPeriodic2d(self.rval)
            self.rval = self.geom.ApplyPeriodic12(np.array([0.0, 0.0, 0.0]),
                                                  self.rval)
        # unit normal to the surface (only sphere so far)
        vel = np.sqrt(self.vval[:, 0]**2 + self.vval[:, 1]**2 +
                      self.vval[:, 2]**2)
        self.vhat = ((self.vval).transpose() / (vel).transpose()).transpose()

        # Now get the connectivity here from the faces files
        #print "Processing file : ", filename_faces
        data_faces = ReadFaces(filename_faces)
        self.Faces = data_faces.Faces
        self.NFaces = data_faces.Nfaces

        # Create the Interaction class
        # This is essentially dummy for now
        self.radius = 1
        self.inter = Interaction(self.param, self.radius, True)

        # Create the cell list
        # This is provisional, again. Here a lot more info from the nlist / triangulation should come in
        cellsize = param.nlist_rcut
        if cellsize > 5 * self.inter.sigma:
            cellsize = 5 * self.inter.sigma
            print "Warning! Reduced the cell size to manageable proportions (5 times mean radius). Re-check if simulating very long objects!"
        self.clist = CellList(self.geom, cellsize)
        # Populate it with all the particles:
        for k in range(self.N):
            self.clist.add_particle(self.rval[k, :], k)
        #self.clist.printMe()

        if debug:
            fig = plt.figure()
            ax = fig.add_subplot(111, projection='3d')
            ax.scatter(self.rval[:, 0],
                       self.rval[:, 1],
                       self.rval[:, 2],
                       zdir='z',
                       c='b')
Exemplo n.º 33
0
    return_value = setNextSubProviderInModule()
    writeLog(INFO_LOGS.SETTING_PROVIDER % getSubProvider().PROVIDER_NAME)
    return return_value

from SubStages.QuerySubStage import QuerySubStage

from Settings.Config import SubiTConfig

from Logs import INFO as INFO_LOGS
from Logs import WARN as WARN_LOGS
from Logs import DIRECTION as DIRC_LOGS
from Logs import FINISH as FINISH_LOGS
from Logs import BuildLog

import Interaction
Interactor  = Interaction.getInteractor()
writeLog    = Interactor.writeLog

from Utils import WriteDebug
from Utils import SplitToFileAndDirectory


class SubFlow(object):
    """ SubFlow is the core of SubiT. That's where all the modules are joined 
        together in order to get the subtitles.
        
        The scope of a SubFlow instance is a single SingleInput instance. i.e.
        SubFlow is not responsible for retrieving movie files from directories
        or figure out whether the given file has a subtitle already downloaded
        or not (That's the job of whoever calling the instance).
Exemplo n.º 34
0
def GetSubtitleDownloadDirectory(dir_by_flow = None, interactive = False):
    """ Get the full path for the subtitle download directory. The argument
        dir_by_flow specify the directory in which the movie file exists.
        
        If dir_by_flow is missing, and interactive is false, the function will
        back-off to the path stored in default_directory param in the config, 
        even if the flag of always_use_default_directory is turned off.
    """
    from Settings import DEFAULT_DIRECTORY_DEFAULT_VAL
    from Settings.Config import SubiTConfig

    from Logs import WARN as WARN_LOGS
    from Logs import DIRECTION as DIRC_LOGS

    download_directory = None
    conf_default_directory = SubiTConfig.Singleton().getStr\
        ('Global', 'default_directory', DEFAULT_DIRECTORY_DEFAULT_VAL)
    conf_always_use_default_dir = SubiTConfig.Singleton().getBoolean\
        ('Global', 'always_use_default_directory', False)

    if conf_default_directory == DEFAULT_DIRECTORY_DEFAULT_VAL:
        WriteDebug('conf_default_directory is: [%s], giving os.getcwd() [%s]' % (conf_default_directory, os.getcwd()))
        conf_default_directory = os.getcwd()
    elif not os.path.exists(conf_default_directory):
        WriteDebug('conf_default_directory [%s] is missing, giving os.getcwd() [%s]' % (conf_default_directory, os.getcwd()))
        conf_default_directory = os.getcwd()

    # In order to avoid failure of the os.path.exists function (by calling them
    # with None object). we replace the None value with empty string.
    if dir_by_flow is None:
        dir_by_flow = ''


    # The result of these 4 lines is simple. If dir_by_flow exists, and the conf
    # of always_use_default_dir is False, we return the dir_by_flow, if it's True
    # we return the conf_default_directory. In any other case, we return None
    if os.path.exists(dir_by_flow):
        WriteDebug('Setting download_directory to be dir_by_flow [%s]' % dir_by_flow)
        download_directory = dir_by_flow
    if conf_always_use_default_dir:
        WriteDebug('Setting download_directory to be conf_default_directory [%s]' % conf_default_directory)
        download_directory = conf_default_directory

    if not download_directory and interactive:
        import Interaction
        Interactor  = Interaction.getInteractor()
        writeLog = Interactor.writeLog

        while not download_directory:
            user_dir_choice = Interactor.getDestinationDirectoryInput\
                (conf_default_directory, DIRC_LOGS.INSERT_LOCATION_FOR_SUBTITLE_DOWNLOAD)
            if os.path.exists(user_dir_choice):
                WriteDebug('User enter legit path, using it: %s' % user_dir_choice)
                download_directory = user_dir_choice
            else:
                WriteDebug('User enter non-legit path [%s], asking again!' % user_dir_choice)
                writeLog(WARN_LOGS.ERROR_DIRECTORY_DOESNT_EXISTS % user_dir_choice)
    elif not download_directory:
        WriteDebug('To avoid problems, setting download_directory to conf_default_directory: %s' % conf_default_directory)
        download_directory = conf_default_directory

    return download_directory
Exemplo n.º 35
0
    def __init__(self,
                 globalWorkingDir,
                 localWorkingDir,
                 pilotJob=None,
                 rank=None,
                 nonMPIMode=False,
                 outputDir=None,
                 dumpEventOutputs=False):
        threading.Thread.__init__(self)
        self.globalWorkingDir = globalWorkingDir
        self.localWorkingDir = localWorkingDir
        self.currentDir = None
        # database backend
        self.db = Database.Backend(self.globalWorkingDir)
        # logger
        self.tmpLog = Logger.Logger(filename='Yoda.log')

        # communication channel
        self.comm = Interaction.Receiver(rank=rank,
                                         nonMPIMode=nonMPIMode,
                                         logger=self.tmpLog)
        self.rank = self.comm.getRank()

        self.tmpLog.info("Global working dir: %s" % self.globalWorkingDir)
        self.initWorkingDir()
        self.tmpLog.info("Current working dir: %s" % self.currentDir)
        self.failed_updates = []
        self.outputDir = outputDir
        self.dumpEventOutputs = dumpEventOutputs

        self.pilotJob = pilotJob

        self.cores = 10
        self.jobs = []

        # jobs which needs more than one rank
        self.jobRanks = []
        self.totalJobRanks = 0
        # jobs which needs less than one rank
        self.jobRanksSmallPiece = []
        self.totalJobRanksSmallPiece = 0
        self.rankJobsTries = {}

        # scheduler policy:
        self.bigJobFirst = True
        self.lastRankForBigJobFirst = int(self.getTotalRanks() * 0.9)

        self.readyEventRanges = []
        self.runningEventRanges = {}
        self.finishedEventRanges = []

        self.readyJobsEventRanges = {}
        self.runningJobsEventRanges = {}
        self.finishedJobsEventRanges = {}
        self.stagedOutJobsEventRanges = {}

        self.updateEventRangesToDBTime = None

        self.jobMetrics = {}
        self.jobsTimestamp = {}
        self.jobsRuningRanks = {}

        self.originSigHandler = {}
        for sig in [
                signal.SIGTERM, signal.SIGQUIT, signal.SIGSEGV, signal.SIGXCPU,
                signal.SIGUSR1, signal.SIGBUS
        ]:
            self.originSigHandler[sig] = signal.getsignal(sig)
        signal.signal(signal.SIGTERM, self.stop)
        signal.signal(signal.SIGQUIT, self.stop)
        signal.signal(signal.SIGSEGV, self.stop)
        signal.signal(signal.SIGXCPU, self.stopYoda)
        signal.signal(signal.SIGUSR1, self.stopYoda)
        signal.signal(signal.SIGBUS, self.stopYoda)