def getInform(self, belief):
        '''
        '''
        act = "null()"
        done = False
        global_summary = SummaryMapping.globalSummary(belief, self.domainUtil)
        inform_summary = []
        for num_accepted in range(1, MAX_NUM_ACCEPTED + 1):
            inform_summary.append(
                SummaryMapping.actionSpecificInformSummary(
                    belief, num_accepted, self.domainUtil))
        count80 = global_summary['GLOBAL_COUNT80']
        offer_happened = global_summary['GLOBAL_OFFERHAPPENED']

        if count80 >= MAX_NUM_ACCEPTED:
            count80 = MAX_NUM_ACCEPTED - 1

        arr = inform_summary[count80]
        first = arr[0]  # True if there is no matching entities
        second = arr[1]  # True if there is one matching entities
        #third = arr[2]  # True if there is two~four matching entities
        discr = arr[4]  # True if we can discriminate more

        requested_slots = DMUtils.getRequestedSlots(belief)
        #if (first or second or not discr or count80 >= len(Settings.ontology['system_requestable'])) and len(requested_slots)==0:
        act = DMUtils.getInformAction(count80, belief, self.domainUtil)
        if act != "null()":
            done = True
        return [done, act]
    def getInform(self, belief):
        """
        """
        act = "null()"
        done = False
        global_summary = SummaryMapping.globalSummary(belief, self.domainUtil)
        inform_summary = []
        for num_accepted in range(1, MAX_NUM_ACCEPTED + 1):
            inform_summary.append(SummaryMapping.actionSpecificInformSummary(belief, num_accepted, self.domainUtil))
        count80 = global_summary["GLOBAL_COUNT80"]
        offer_happened = global_summary["GLOBAL_OFFERHAPPENED"]

        if count80 >= MAX_NUM_ACCEPTED:
            count80 = MAX_NUM_ACCEPTED - 1

        arr = inform_summary[count80]
        first = arr[0]  # True if there is no matching entities
        second = arr[1]  # True if there is one matching entities
        # third = arr[2]  # True if there is two~four matching entities
        discr = arr[4]  # True if we can discriminate more

        requested_slots = DMUtils.getRequestedSlots(belief)
        # if (first or second or not discr or count80 >= len(Settings.ontology['system_requestable'])) and len(requested_slots)==0:
        act = DMUtils.getInformAction(count80, belief, self.domainUtil)
        if act != "null()":
            done = True
        return [done, act]
    def _getGlobal(self, belief, global_summary):
        act = 'null()'

        if global_summary['GLOBAL_BYCONSTRAINTS'] > 0.5 and\
            global_summary['GLOBAL_COUNT80'] > 3:
            act = DMUtils.getGlobalAction(belief, 'INFORM_BYNAME', domainUtil=self.domainUtil)
        elif global_summary['GLOBAL_BYALTERNATIVES'] > 0.5:
            act = DMUtils.getGlobalAction(belief, 'INFORM_ALTERNATIVES', domainUtil=self.domainUtil)
        elif global_summary['GLOBAL_BYNAME'] > 0.5:
            act = DMUtils.getGlobalAction(belief, 'INFORM_REQUESTED', domainUtil=self.domainUtil )
        elif global_summary['GLOBAL_FINISHED'] > 0.5:
            act = DMUtils.getGlobalAction(belief, 'BYE', domainUtil=self.domainUtil)
        elif global_summary['GLOBAL_REPEAT'] > 0.5:
            act = DMUtils.getGlobalAction(belief, 'INFORM_REPEAT', domainUtil=self.domainUtil)
        elif global_summary['GLOBAL_REQMORE'] > 0.5:
            act = DMUtils.getGlobalAction(belief, 'INFORM_BYNAME', domainUtil=self.domainUtil)
        elif global_summary['GLOBAL_THANKYOU'] > 0.5:
            act = DMUtils.getGlobalAction(belief, 'REQMORE', domainUtil=self.domainUtil)
        elif global_summary['GLOBAL_ACK'] > 0.5:
            act = DMUtils.getGlobalAction(belief, 'REQMORE', domainUtil=self.domainUtil)
        elif global_summary['GLOBAL_RESTART'] > 0.5:
            act = DMUtils.getGlobalAction(belief, 'RESTART', domainUtil=self.domainUtil)

        if act != 'null()':
            return True, act
        return False, act
Пример #4
0
    def work(self, belief):
        '''
        This base Policy class performs pre- and post-processing of system action selection.
        1. Preprocessing: It converts all summary actions to master actions and checks whether they are executable.
        2. Action selection: This is done in overridden "select" method of a child class,
                             which returns an index of selected action.
        3. Postprocessing: Converts selected action index to master action and adds count=.
        If the policy doesn't need these pre- and post-processing, It can override this work method.
        :return: system action in string
        '''
        # 1. Preprocessing: Get executable actions.
        executable = []
        all_action_list = []
        for a in range(self.numActions):
            summary, sys_act = self.to_master_action(a, belief, self.last_act)
            all_action_list.append(sys_act)
            if not sys_act.startswith('null'):
                executable.append(a)

        # 2. Action selection.
        self.last_belief = self.belief
        self.last_act = self.act
        act_index = self.select(belief, executable)
        self.belief = belief
        self.act = act_index

        # 3. Postprocessing.
        output = all_action_list[act_index]
        if self.use_confreq:
            output = DMUtils.add_venue_count(output, belief, self.domainUtil)
        return output
Пример #5
0
    def work(self, belief):
        '''
        This base Policy class performs pre- and post-processing of system action selection.
        1. Preprocessing: It converts all summary actions to master actions and checks whether they are executable.
        2. Action selection: This is done in overridden "select" method of a child class,
                             which returns an index of selected action.
        3. Postprocessing: Converts selected action index to master action and adds count=.
        If the policy doesn't need these pre- and post-processing, It can override this work method.
        :return: system action in string
        '''
        # 1. Preprocessing: Get executable actions.
        executable = []
        all_action_list = []
        for a in range(self.numActions):
            summary, sys_act = self.to_master_action(a, belief, self.last_act)
            all_action_list.append(sys_act)
            if not sys_act.startswith('null'):
                executable.append(a)

        # 2. Action selection.
        self.last_belief = self.belief
        self.last_act = self.act
        act_index = self.select(belief, executable)
        self.belief = belief
        self.act = act_index

        # 3. Postprocessing.
        output = all_action_list[act_index]
        if self.use_confreq:
            output = DMUtils.add_venue_count(output, belief, self.domainUtil)
        return output
    def _getRequest(self, belief, array_slot_summary):
        #slots = Settings.ontology['system_requestable']

        # This is added for confreq.
        need_grounding = DMUtils.getTopBeliefs(belief, 0.8, domainUtil=self.domainUtil)

        for slot in self.domainUtil.sorted_system_requestable_slots:  #slots:
            summary = array_slot_summary[slot]
            (_, topprob) = summary['TOPTWO'][0]
            (_, secprob) = summary['TOPTWO'][1]

            if topprob < 0.8:
                # Add implicit confirmation (for confreq.)
                grounding_slots = copy.deepcopy(need_grounding)
                if slot in grounding_slots:
                    del grounding_slots[slot]

                grounding_result = []
                for grounding_slot in grounding_slots:
                    if len(grounding_result) < 3:
                        (value, prob) = grounding_slots[grounding_slot]
                        grounding_result.append('%s="%s"' % (grounding_slot, value))

                if not grounding_result or not self.use_confreq:
                    return True, 'request(%s)' % slot
                else:
                    return True, 'confreq(' + ','.join(grounding_result) + ',%s)' % slot

        return False, 'null()'
    def work(self, belief):
        """Primary response function of HDC policy
        """
        global_summary = SummaryMapping.globalSummary(belief, domainUtil=self.domainUtil)
        array_slot_summary = SummaryMapping.arraySlotSummary(belief, self.domainUtil)
        logger.debug(str(global_summary))
        logger.debug('HDC policy: getGlobal')
        done, output = self._getGlobal(belief, global_summary)

        if not done:
            logger.debug('HDC policy: getConfirmSelect')
            done, output = self._getConfirmSelect(belief, array_slot_summary)
        if not done:
            logger.debug('HDC policy: getInform')
            inform_summary = []
            for num_accepted in range(1, MAX_NUM_ACCEPTED+1):
                temp = SummaryMapping.actionSpecificInformSummary(belief, num_accepted, self.domainUtil)
                inform_summary.append(temp)
                       
            done, output = self._getInform(belief, global_summary, inform_summary)
        if not done:
            logger.debug('HDC policy: getRequest')
            done, output = self._getRequest(belief, array_slot_summary)
        if not done:
            logger.warning("HDCPolicy couldn't find action: execute reqmore().")
            output = 'reqmore()'

        if output == 'badact()' or output == 'null()':
            logger.warning('HDCPolicy chose bad or null action')
            output = 'null()'

        if self.use_confreq:
            #TODO - known problem here if use_confreq is True (ie being used)  FIXME
            output = DMUtils.add_venue_count(output, belief)
        return output
Пример #8
0
    def _getRequest(self, belief, array_slot_summary):
        #slots = Settings.ontology['system_requestable']

        # This is added for confreq.
        need_grounding = DMUtils.getTopBeliefs(belief,
                                               0.8,
                                               domainUtil=self.domainUtil)

        for slot in self.domainUtil.sorted_system_requestable_slots:  #slots:
            summary = array_slot_summary[slot]
            (_, topprob) = summary['TOPTWO'][0]
            (_, secprob) = summary['TOPTWO'][1]

            if topprob < 0.8:
                # Add implicit confirmation (for confreq.)
                grounding_slots = copy.deepcopy(need_grounding)
                if slot in grounding_slots:
                    del grounding_slots[slot]

                grounding_result = []
                for grounding_slot in grounding_slots:
                    if len(grounding_result) < 3:
                        (value, prob) = grounding_slots[grounding_slot]
                        grounding_result.append('%s="%s"' %
                                                (grounding_slot, value))

                if not grounding_result or not self.use_confreq:
                    return True, 'request(%s)' % slot
                else:
                    return True, 'confreq(' + ','.join(
                        grounding_result) + ',%s)' % slot

        return False, 'null()'
Пример #9
0
    def _getInform(self, belief, global_summary, inform_summary):
        act = 'null()'

        count80 = global_summary['GLOBAL_COUNT80']
        offer_happened = global_summary['GLOBAL_OFFERHAPPENED']

        if count80 >= MAX_NUM_ACCEPTED:
            count80 = MAX_NUM_ACCEPTED - 1

        arr = inform_summary[count80]
        first = arr[0]  # True if there is no matching entities
        second = arr[1]  # True if there is one matching entities
        #third = arr[2]  # True if there is two~four matching entities
        discr = arr[4]  # True if we can discriminate more

        logger.debug(
            '%d among %d slots are accepted (>=0.8 belief).' %
            (count80, len(self.domainUtil.sorted_system_requestable_slots)))
        #logger.debug('%d among %d slots are accepted (>=0.8 belief).' % (count80, len(Settings.ontology['system_requestable'])))

        if first or second or not discr or count80 >= len(
                self.domainUtil.ontology['system_requestable']):
            # If this inform gives either 0 or 1 or we've found everything we can ask about
            logger.debug(
                'Trying to get inform action, have enough accepted slots.')
            logger.debug('Is there no matching entity? %s.' % str(first))
            logger.debug('Is there only one matching entity? %s.' %
                         str(second))
            logger.debug('Can we discriminate more? %s.' % str(discr))
            requested_slots = DMUtils.getRequestedSlots(belief)

            if len(requested_slots) > 0 and offer_happened:
                logger.debug('Getting inform requested action.')
                act = DMUtils.getGlobalAction(belief,
                                              'INFORM_REQUESTED',
                                              domainUtil=self.domainUtil)
            else:
                logger.debug(
                    'Getting inform exact action with %d accepted slots.' %
                    count80)
                act = DMUtils.getInformAction(count80,
                                              belief,
                                              domainUtil=self.domainUtil)

        if act != 'null()':
            return True, act
        return False, act
Пример #10
0
 def dRdEi(self, E, mx, i):
     R = self.exposure * self.frac[i] * DMU.dRdE(
         E, self.N_p[i], self.N_n[i], mx,
         [1.0 / self.N_p[i], 0.0, 0.0, 0.0])
     if (R < 1e-30):
         return 1e-30
     else:
         return R
Пример #11
0
 def dRdE(self, E, mx, l):
     R = 0
     for i in range(self.N_iso):
         R += self.frac[i] * DMU.dRdE(E, self.N_p[i], self.N_n[i], mx, l)
     #print R
     if (R < 1e-30):
         return 1e-30
     else:
         return R * self.exposure
Пример #12
0
 def sig_eff(self, mx, l):
     N1 = (1.973e-14 * 1.973e-14) * 4.0 * (DMU.reduced_m(1.0,
                                                         mx))**2.0 / np.pi
     sig0 = 0
     for i in range(self.N_iso):
         sig0 += 0.5 * self.frac[i] * (
             (l[0] * self.N_p[i] + l[1] * self.N_n[i])**2.0 +
             (l[2] * self.N_p[i] + l[3] * self.N_n[i])**2.0)
     sig_p = N1 * sig0 / np.sum(self.frac * (self.N_p + self.N_n)**2)
     return sig_p
 def getRestart(self, belief):
     '''
     '''
     global_summary = SummaryMapping.globalSummary(belief, self.domainUtil)
     done = False
     act = 'null()'
     if global_summary['GLOBAL_RESTART'] > 0.5:
         act = DMUtils.getGlobalAction(belief, 'RESTART', self.domainUtil)
     if act != 'null()':
         done = True
     return done, act
 def getRestart(self, belief):
     """
     """
     global_summary = SummaryMapping.globalSummary(belief, self.domainUtil)
     done = False
     act = "null()"
     if global_summary["GLOBAL_RESTART"] > 0.5:
         act = DMUtils.getGlobalAction(belief, "RESTART", self.domainUtil)
     if act != "null()":
         done = True
     return done, act
 def getInformAlternatives(self, belief):
     """
     """
     global_summary = SummaryMapping.globalSummary(belief, self.domainUtil)
     done = False
     act = "null()"
     if global_summary["GLOBAL_BYALTERNATIVES"] > 0.5:
         act = DMUtils.getGlobalAction(belief, "INFORM_ALTERNATIVES", self.domainUtil)
     if act != "null()":
         done = True
     return done, act
 def getInformRequested(self, belief):
     """
     """
     global_summary = SummaryMapping.globalSummary(belief, self.domainUtil)
     done = False
     act = "null()"
     if global_summary["GLOBAL_BYNAME"] > 0.5:
         act = DMUtils.getGlobalAction(belief, "INFORM_REQUESTED", self.domainUtil)
     if act != "null()":
         done = True
     return done, act
 def getBye(self, belief):
     '''
     '''
     global_summary = SummaryMapping.globalSummary(belief, self.domainUtil)
     done = False
     act = 'null()'
     if global_summary['GLOBAL_FINISHED'] > 0.5:
         act = DMUtils.getGlobalAction(belief, 'BYE', self.domainUtil)
     if act != 'null()':
         done = True
     return done, act
 def getReqMore(self, belief):
     """
     """
     global_summary = SummaryMapping.globalSummary(belief, self.domainUtil)
     done = False
     act = "null()"
     # if global_summary['GLOBAL_ACK'] > 0.5 or global_summary['GLOBAL_THANKYOU']>0.5:
     act = DMUtils.getGlobalAction(belief, "REQMORE", self.domainUtil)
     if act != "null()":
         done = True
     return done, act
 def getReqMore(self, belief):
     '''
     '''
     global_summary = SummaryMapping.globalSummary(belief, self.domainUtil)
     done = False
     act = 'null()'
     #if global_summary['GLOBAL_ACK'] > 0.5 or global_summary['GLOBAL_THANKYOU']>0.5:
     act = DMUtils.getGlobalAction(belief, 'REQMORE', self.domainUtil)
     if act != 'null()':
         done = True
     return done, act
 def getBye(self, belief):
     """
     """
     global_summary = SummaryMapping.globalSummary(belief, self.domainUtil)
     done = False
     act = "null()"
     if global_summary["GLOBAL_FINISHED"] > 0.5:
         act = DMUtils.getGlobalAction(belief, "BYE", self.domainUtil)
     if act != "null()":
         done = True
     return done, act
 def getInformAlternatives(self, belief):
     '''
     '''
     global_summary = SummaryMapping.globalSummary(belief, self.domainUtil)
     done = False
     act = 'null()'
     if global_summary['GLOBAL_BYALTERNATIVES'] > 0.5:
         act = DMUtils.getGlobalAction(belief, 'INFORM_ALTERNATIVES',
                                       self.domainUtil)
     if act != 'null()':
         done = True
     return done, act
 def getInformRequested(self, belief):
     '''
     '''
     global_summary = SummaryMapping.globalSummary(belief, self.domainUtil)
     done = False
     act = 'null()'
     if global_summary['GLOBAL_BYNAME'] > 0.5:
         act = DMUtils.getGlobalAction(belief, 'INFORM_REQUESTED',
                                       self.domainUtil)
     if act != 'null()':
         done = True
     return done, act
def actionSpecificInformSummary(belief, numAccepted, domainUtil):
    """count: # of entities matching with numAccepted slots in acceptance list.

        :param belief: (dict) full belief state
        :param numAccepted: (int) 
        :param informable_slots: (list)
        :returns: summary_array [count==0, count==1, 2<=count<=4, count>4, discriminatable] \  discriminatable: matching entities can be further discriminated
    """
    acceptanceList = DMUtils.getTopBeliefs(belief, domainUtil=domainUtil)
    count = _countEntitiesForAcceptanceListPart(acceptanceList, numAccepted, domainUtil)
    discriminatable = _acceptanceListCanBeDiscriminated(acceptanceList, numAccepted, domainUtil)
    summary_array = [count == 0, count == 1, 2 <= count <= 4, count > 4, discriminatable]
    return summary_array
Пример #24
0
    def _getGlobal(self, belief, global_summary):
        act = 'null()'

        if global_summary['GLOBAL_BYCONSTRAINTS'] > 0.5 and\
            global_summary['GLOBAL_COUNT80'] > 3:
            act = DMUtils.getGlobalAction(belief,
                                          'INFORM_BYNAME',
                                          domainUtil=self.domainUtil)
        elif global_summary['GLOBAL_BYALTERNATIVES'] > 0.5:
            act = DMUtils.getGlobalAction(belief,
                                          'INFORM_ALTERNATIVES',
                                          domainUtil=self.domainUtil)
        elif global_summary['GLOBAL_BYNAME'] > 0.5:
            act = DMUtils.getGlobalAction(belief,
                                          'INFORM_REQUESTED',
                                          domainUtil=self.domainUtil)
        elif global_summary['GLOBAL_FINISHED'] > 0.5:
            act = DMUtils.getGlobalAction(belief,
                                          'BYE',
                                          domainUtil=self.domainUtil)
        elif global_summary['GLOBAL_REPEAT'] > 0.5:
            act = DMUtils.getGlobalAction(belief,
                                          'INFORM_REPEAT',
                                          domainUtil=self.domainUtil)
        elif global_summary['GLOBAL_REQMORE'] > 0.5:
            act = DMUtils.getGlobalAction(belief,
                                          'INFORM_BYNAME',
                                          domainUtil=self.domainUtil)
        elif global_summary['GLOBAL_THANKYOU'] > 0.5:
            act = DMUtils.getGlobalAction(belief,
                                          'REQMORE',
                                          domainUtil=self.domainUtil)
        elif global_summary['GLOBAL_ACK'] > 0.5:
            act = DMUtils.getGlobalAction(belief,
                                          'REQMORE',
                                          domainUtil=self.domainUtil)
        elif global_summary['GLOBAL_RESTART'] > 0.5:
            act = DMUtils.getGlobalAction(belief,
                                          'RESTART',
                                          domainUtil=self.domainUtil)

        if act != 'null()':
            return True, act
        return False, act
def actionSpecificInformSummary(belief, numAccepted, domainUtil):
    '''count: # of entities matching with numAccepted slots in acceptance list.

        :param belief: (dict) full belief state
        :param numAccepted: (int) 
        :param informable_slots: (list)
        :returns: summary_array [count==0, count==1, 2<=count<=4, count>4, discriminatable] \  discriminatable: matching entities can be further discriminated
    '''
    acceptanceList = DMUtils.getTopBeliefs(belief, domainUtil=domainUtil)
    count = _countEntitiesForAcceptanceListPart(acceptanceList, numAccepted, domainUtil)
    discriminatable = _acceptanceListCanBeDiscriminated(acceptanceList, numAccepted, domainUtil)
    summary_array = [count == 0, count == 1, 2 <= count <= 4, count > 4, discriminatable]
    return summary_array
 def getInformByName(self, belief):
     '''
     '''
     global_summary = SummaryMapping.globalSummary(belief, self.domainUtil)
     done = False
     act = 'null()'
     if (global_summary['GLOBAL_BYCONSTRAINTS'] > 0.5 #or global_summary['GLOBAL_BYNAME'] >0 or global_summary['GLOBAL_BYALTERNATIVES'] > 0.5
         ) and\
         global_summary['GLOBAL_COUNT80'] > 3:
         act = DMUtils.getGlobalAction(belief, 'INFORM_BYNAME',
                                       self.domainUtil)
     if act != 'null()':
         done = True
     return done, act
 def getInformByName(self, belief):
     """
     """
     global_summary = SummaryMapping.globalSummary(belief, self.domainUtil)
     done = False
     act = "null()"
     if (
         global_summary["GLOBAL_BYCONSTRAINTS"]
         > 0.5  # or global_summary['GLOBAL_BYNAME'] >0 or global_summary['GLOBAL_BYALTERNATIVES'] > 0.5
     ) and global_summary["GLOBAL_COUNT80"] > 3:
         act = DMUtils.getGlobalAction(belief, "INFORM_BYNAME", self.domainUtil)
     if act != "null()":
         done = True
     return done, act
def globalSummary(belief, domainUtil):
    '''summary of global actions such as offer happened etc.

        :param belief: (dict) full belief state
        :returns: (dict) summary. dict keys are given by :meth:`global_summary_features` 
    '''
    topMethod, topMethodBelief = DMUtils.getTopBelief(belief['beliefs']['method'])
    topDiscourseAct, topDiscourseActBelief = DMUtils.getTopBelief(belief['beliefs']['discourseAct'])
    if topMethod == 'byconstraints':
        globalpoint = 'GLOBAL_BYCONSTRAINTS'
    elif topMethod == 'byalternatives':
        globalpoint = 'GLOBAL_BYALTERNATIVES'
    elif topMethod == 'byname':
        globalpoint = 'GLOBAL_BYNAME'
    elif topMethod == 'finished' and topMethodBelief > 0.5:
        globalpoint = 'GLOBAL_FINISHED'
    elif topMethod == 'restart' and topMethodBelief > 0.5:
        globalpoint = 'GLOBAL_RESTART'
    else:
        globalpoint = 'GLOBAL_BYCONSTRAINTS'

    if topDiscourseAct == 'repeat' and topDiscourseActBelief > 0.5:
        globalpoint = 'GLOBAL_REPEAT'
    elif topDiscourseAct == 'reqmore' and topDiscourseActBelief > 0.5:
        globalpoint = 'GLOBAL_REQMORE'
    elif topDiscourseAct == 'thankyou' and topDiscourseActBelief > 0.5:
        globalpoint = 'GLOBAL_THANKYOU'
    elif topDiscourseAct == 'ack' and topDiscourseActBelief > 0.5:
        globalpoint = 'GLOBAL_ACK'

    summaryArray = dict.fromkeys(global_summary_features, False)
    summaryArray[globalpoint] = True
    summaryArray['GLOBAL_COUNT80'] = len(DMUtils.getTopBeliefs(belief, domainUtil=domainUtil))
    summaryArray['GLOBAL_NAMENONE'] = belief['features']['lastActionInformNone']
    summaryArray['GLOBAL_OFFERHAPPENED'] = belief['features']['offerHappened']

    return summaryArray
def globalSummary(belief, domainUtil):
    """summary of global actions such as offer happened etc.

        :param belief: (dict) full belief state
        :returns: (dict) summary. dict keys are given by :meth:`global_summary_features` 
    """
    topMethod, topMethodBelief = DMUtils.getTopBelief(belief["beliefs"]["method"])
    topDiscourseAct, topDiscourseActBelief = DMUtils.getTopBelief(belief["beliefs"]["discourseAct"])
    if topMethod == "byconstraints":
        globalpoint = "GLOBAL_BYCONSTRAINTS"
    elif topMethod == "byalternatives":
        globalpoint = "GLOBAL_BYALTERNATIVES"
    elif topMethod == "byname":
        globalpoint = "GLOBAL_BYNAME"
    elif topMethod == "finished" and topMethodBelief > 0.5:
        globalpoint = "GLOBAL_FINISHED"
    elif topMethod == "restart" and topMethodBelief > 0.5:
        globalpoint = "GLOBAL_RESTART"
    else:
        globalpoint = "GLOBAL_BYCONSTRAINTS"

    if topDiscourseAct == "repeat" and topDiscourseActBelief > 0.5:
        globalpoint = "GLOBAL_REPEAT"
    elif topDiscourseAct == "reqmore" and topDiscourseActBelief > 0.5:
        globalpoint = "GLOBAL_REQMORE"
    elif topDiscourseAct == "thankyou" and topDiscourseActBelief > 0.5:
        globalpoint = "GLOBAL_THANKYOU"
    elif topDiscourseAct == "ack" and topDiscourseActBelief > 0.5:
        globalpoint = "GLOBAL_ACK"

    summaryArray = dict.fromkeys(global_summary_features, False)
    summaryArray[globalpoint] = True
    summaryArray["GLOBAL_COUNT80"] = len(DMUtils.getTopBeliefs(belief, domainUtil=domainUtil))
    summaryArray["GLOBAL_NAMENONE"] = belief["features"]["lastActionInformNone"]
    summaryArray["GLOBAL_OFFERHAPPENED"] = belief["features"]["offerHappened"]

    return summaryArray
    def _getInform(self, belief, global_summary, inform_summary):
        act = 'null()'

        count80 = global_summary['GLOBAL_COUNT80']
        offer_happened = global_summary['GLOBAL_OFFERHAPPENED']

        if count80 >= MAX_NUM_ACCEPTED:
            count80 = MAX_NUM_ACCEPTED - 1

        arr = inform_summary[count80]
        first = arr[0]  # True if there is no matching entities
        second = arr[1] # True if there is one matching entities
        #third = arr[2]  # True if there is two~four matching entities
        discr = arr[4]  # True if we can discriminate more

        logger.debug('%d among %d slots are accepted (>=0.8 belief).' % (count80, len(self.domainUtil.sorted_system_requestable_slots)))
        #logger.debug('%d among %d slots are accepted (>=0.8 belief).' % (count80, len(Settings.ontology['system_requestable'])))

        if first or second or not discr or count80 >= len(self.domainUtil.ontology['system_requestable']):  
            # If this inform gives either 0 or 1 or we've found everything we can ask about
            logger.debug('Trying to get inform action, have enough accepted slots.')
            logger.debug('Is there no matching entity? %s.' % str(first))
            logger.debug('Is there only one matching entity? %s.' % str(second))
            logger.debug('Can we discriminate more? %s.' % str(discr))
            requested_slots = DMUtils.getRequestedSlots(belief)

            if len(requested_slots) > 0 and offer_happened:
                logger.debug('Getting inform requested action.')
                act = DMUtils.getGlobalAction(belief, 'INFORM_REQUESTED', domainUtil=self.domainUtil)
            else:
                logger.debug('Getting inform exact action with %d accepted slots.' % count80)
                act = DMUtils.getInformAction(count80, belief, domainUtil=self.domainUtil)

        if act != 'null()':
            return True, act
        return False, act
def arraySlotSummary(belief, domainUtil): 
    '''Gets the summary vector for goal slots, including the top probabilities, entropy, etc.

    :param belief: (dict) full belief state
    :return: (dict) of slot goal summaries
    '''
    summary = {}
    for slot in domainUtil.sorted_system_requestable_slots:
        #Settings.ontology['system_requestable']:#Settings.ontology['informable']:
        summary[slot] = {}
        slot_belief = belief['beliefs'][slot]
        summary[slot]['TOPTWO'], summary[slot]['ISTOPNONE'] = \
            DMUtils.getTopTwoBeliefsExcludingNone(belief['beliefs'][slot])
        belief_dist = slot_belief.values()
        filtered_dist = filter(lambda prob: prob > ZERO_THRESHOLD, belief_dist)
        summary[slot]['ENTROPY'] = filtered_dist * np.log(filtered_dist)

        # Array indicating whether 'request' has top probability
        summary[slot]['ISREQUESTTOP'] = belief['beliefs']['requested'][slot] > 0.5
    return summary
def arraySlotSummary(belief, domainUtil):
    """Gets the summary vector for goal slots, including the top probabilities, entropy, etc.

    :param belief: (dict) full belief state
    :return: (dict) of slot goal summaries
    """
    summary = {}
    for slot in domainUtil.sorted_system_requestable_slots:
        # Settings.ontology['system_requestable']:#Settings.ontology['informable']:
        summary[slot] = {}
        slot_belief = belief["beliefs"][slot]
        summary[slot]["TOPTWO"], summary[slot]["ISTOPNONE"] = DMUtils.getTopTwoBeliefsExcludingNone(
            belief["beliefs"][slot]
        )
        belief_dist = slot_belief.values()
        filtered_dist = filter(lambda prob: prob > ZERO_THRESHOLD, belief_dist)
        summary[slot]["ENTROPY"] = filtered_dist * np.log(filtered_dist)

        # Array indicating whether 'request' has top probability
        summary[slot]["ISREQUESTTOP"] = belief["beliefs"]["requested"][slot] > 0.5
    return summary
Пример #33
0
    def work(self, belief):
        """Primary response function of HDC policy
        """
        global_summary = SummaryMapping.globalSummary(
            belief, domainUtil=self.domainUtil)
        array_slot_summary = SummaryMapping.arraySlotSummary(
            belief, self.domainUtil)
        logger.debug(str(global_summary))
        logger.debug('HDC policy: getGlobal')
        done, output = self._getGlobal(belief, global_summary)

        if not done:
            logger.debug('HDC policy: getConfirmSelect')
            done, output = self._getConfirmSelect(belief, array_slot_summary)
        if not done:
            logger.debug('HDC policy: getInform')
            inform_summary = []
            for num_accepted in range(1, MAX_NUM_ACCEPTED + 1):
                temp = SummaryMapping.actionSpecificInformSummary(
                    belief, num_accepted, self.domainUtil)
                inform_summary.append(temp)

            done, output = self._getInform(belief, global_summary,
                                           inform_summary)
        if not done:
            logger.debug('HDC policy: getRequest')
            done, output = self._getRequest(belief, array_slot_summary)
        if not done:
            logger.warning(
                "HDCPolicy couldn't find action: execute reqmore().")
            output = 'reqmore()'

        if output == 'badact()' or output == 'null()':
            logger.warning('HDCPolicy chose bad or null action')
            output = 'null()'

        if self.use_confreq:
            #TODO - known problem here if use_confreq is True (ie being used)  FIXME
            output = DMUtils.add_venue_count(output, belief)
        return output
Пример #34
0
import DMUtils as DMU

#We'll also import some useful libraries
import numpy as np
import matplotlib.pyplot as pl

# ### Loading nuclear form factors

# We load the NREFT form factor coefficients for the nucleus we're interested in (say Iodine for now) as follows. The form factor coefficients (`FF_I` in this case) are required to calculate the recoil rate.

# In[34]:

A_I = 127  #Nucleon number
Z_I = 53  #Atomic number
root = "FormFactors"  #Folder where the form factor files are stored
FF_I = DMU.LoadFormFactors(root, A_I, Z_I)

# ### Differential recoil rate

# Before we calculate the differential recoil rate $\mathrm{d}R/\mathrm{d}E_R$, we have to specify the couplings. We do this by defining two vectors of couplings: 1 for the couplings to protons and 1 for the couplings to neutrons. Each vector should have 11 elements (one entry for each of the 11 NREFT operators - note that $\mathcal{O}_2$ is set to zero by default, but we keep 11 entries so that the numbering matches):

# In[35]:

#Initialise the empty vectors
cp = np.zeros(11)
cn = np.zeros(11)

# Let's start with the standard spin-independent interaction (so we want to set the first element $\mathcal{O}_1$, noting that the numbers of arrays starts from zero in python):

# In[36]: