Пример #1
0
    def g0(self, data, p):
        # Get counter dictionary of given data
        count = dict(sorted(Counter(data).items()))
        x = []

        # Getting the values of count else put 0
        for k in range(self.S):
            if k in count:
                x.append(count[k])
            else:
                x.append(0)

        # Numerator part
        # numerator = math.factorial(
        #     self.total_flip_per_experimentation) * np.prod(
        #     [math.pow(prob, v) for prob, (k, v) in zip(p, count.items())])

        # First get list of factorials of all values, then multiply all together
        # Denominator part
        # denominator = np.prod([math.factorial(v) for k, v in count.items()])

        # result = numerator/denominator
        result = multinomial.pmf(np.array(x),
                                 n=self.total_flip_per_experimentation,
                                 p=p)
        return result
Пример #2
0
def multinomial_pmf(choice_vector, probability_vector):
    from scipy.stats import multinomial
    if np.sum(choice_vector) == 0:
        return 1.0
    return multinomial.pmf(choice_vector,
                           n=np.sum(choice_vector),
                           p=probability_vector)
Пример #3
0
def pci(ranks, alpha=0.05):
    """
    Compute confidence interval on binomial successes
    with willson correction
    """
    from collections import Counter

    hist = Counter(ranks)

    #     pvals = {}
    from scipy.stats import norm, multinomial, chi2_contingency

    #     z = norm.ppf(1 - alpha / 2)
    #     n = len(hist)
    n = len(ranks)

    hist = dict(sorted(hist.items(), key=lambda x: x[1])[::-1])

    candidates = [i for i in hist.keys()]
    success = [i for i in hist.values()]

    #     print(success)
    for ni in range(len(hist)):
        p = multinomial.pmf(success[: ni + 1], n=n, p=np.ones(ni + 1) * 1 / (ni + 1))
        #         chi2, p, dof, expected = chi2_contingency(t,  correction = 0)
        #         print(chi2, p, dof, expected)
        driverset = set(candidates[: ni + 1])
        if p >= alpha:
            #             print(driverset, hist)
            break

    return driverset
Пример #4
0
def multinomial_dengue(raw_data, sim_data):
    num_obs = len(raw_data)
    num_strains = len(raw_data[0])
    LL = 0.0

    for x in range(num_obs):
        temp_raw_data = list()
        temp_sim_data = list()
        for y in range(num_strains):
            if raw_data[x][y] > 0:
                temp_raw_data.append(raw_data[x][y])
                denominator = sum(sim_data[x][1:1 + num_strains])
                if denominator == 0:
                    temp_sim_data.append(0)
                else:
                    temp_sim_data.append(sim_data[x][y + 1] / denominator)
        if sum(temp_sim_data) == 0:
            length = len(temp_sim_data)
            proportion = 1. / length
            for y in range(length):
                temp_sim_data[y] = proportion
        LL_temp = multinomial.pmf(temp_raw_data,
                                  n=sum(temp_raw_data),
                                  p=temp_sim_data)
        if math.isnan(LL_temp):
            print('nan LL: no reported infections in this simulation year')
            #print temp_sim_data
        else:
            LL += LL_temp
        #print LL_temp

    return LL
Пример #5
0
def tie_probability(distribution, candidate1, candidate2):
    """
    Calculate the probability for tie between 2 candidates.

    Args:
        distribution(list): Distribution over three candidates.
        candidate1(int): Index of the first candidate for the tie.
        candidate2(int): Index of the second candidate for the tie.

   Return:
       double. the probability that both candidate1 and candidate2 win.
    """
    candidates_index = [candidate1, candidate2]
    candidate3 = [
        x for x in range(len(distribution)) if x not in candidates_index
    ][0]

    total_amount = float(sum(distribution))
    candidates_probability = [
        distribution[cand] / total_amount
        for cand in [candidate1, candidate2, candidate3]
    ]

    start_value = int(math.ceil(total_amount / 3.0))
    tie_probability_value = 0
    for votes in range(start_value, int(total_amount) / 2 + 1):
        state = [votes, votes, total_amount - 2 * votes]
        state_probability = multinomial.pmf(state, total_amount,
                                            candidates_probability)
        tie_probability_value += state_probability

    return tie_probability_value
Пример #6
0
    def get_next_states(self, action, dice_state):
        """
        Get all possible results of taking an action from a given state.

        :param action: the action taken
        :param dice_state: the current dice
        :return: state, game_over, reward, probabilities
                 state:
                    a list containing each possible resulting state as a tuple,
                    or a list containing None if it is game_over, to indicate
                    the terminal state
                 game_over:
                    a Boolean indicating if all dice were held
                 reward:
                    the reward for this action, equal to the final value of the
                    dice if game_over, otherwise equal to -1 * penalty
                 probabilities:
                    a list of size equal to state containing the probability of
                    each state occurring from this action
        """
        if action not in self.actions:
            raise ValueError("action must be a valid tuple of dice indices")
        if dice_state not in self.states:
            raise ValueError("state must be a valid tuple of dice values")

        count = len(action)
        if count == self._dice:
            return [None], True, self.final_score(dice_state), np.array([1])
        else:
            # first, build a mask (array of True/False) to indicate which values are held
            mask = np.zeros(self._dice, dtype=np.bool)
            hold = np.array(action, dtype=np.int)
            mask[hold] = True

            # get all possible combinations of values for the non-held dice
            other_vals = np.array(list(itertools.combinations_with_replacement(self._values,
                                                                               self._dice - count)),
                                  dtype=np.int)

            # in v1, dice only went from 1 to n
            # now dice can have any values, but values don't matter for probability, so get same data with 0 to n-1
            other_index = np.array(list(itertools.combinations_with_replacement(range(self._sides),
                                                                                self._dice - count)),
                                   dtype=np.int)

            # other_index will look like this, a numpy array of combinations
            #   [[0, 0], [0, 1], ..., [5, 5]]
            # need to calculate the probability of each one, so will query a multinomial distribution
            # if dice show (1, 3) then the correct query format is index based: [1, 0, 1, 0, 0, 0]
            queries = np.apply_along_axis(partial(np.bincount, minlength=self._sides), 1, other_index)
            probabilities = multinomial.pmf(queries, self._dice - count, self._bias)

            other_vals = np.insert(other_vals, np.zeros(count, dtype=np.int),
                                   np.asarray(dice_state, dtype=np.int)[mask], axis=1)

            other_vals.sort(axis=1)

            other_vals = [tuple(x) for x in other_vals]

            return other_vals, False, -1*self._penalty, probabilities
Пример #7
0
def hmm(theta, emissions, states, expression_value):
    """
    Emissions are the vector of triplets (X)
    Hidden states are one of the 9 possible states

    :param theta:
    :param emissions:
    :return:
    """
    # Find emission probabilities
    emission_probs = defaultdict(lambda: 0)

    # Get mu for all states
    # TODO This is a point of dissonance between what I'm seeeing online and what's in the paper
    mu = theta['alpha'] / theta['beta']

    for emission, state in itertools.product(emissions, states):
        """
        emission is a vector<int> of size 3 representing RPF counts
        """
        prob_Y_given_Z = poisson.pmf(sum(emission),
                                     mu[state] * expression_value)
        prob_X_given_Y_Z = multinomial.pmf(x=emission,
                                           n=sum(emission),
                                           p=theta['pi'].loc[state])
        """
        TODO Does the emission (X) need to be uniquely identified? For example, if two separate emissions are both 
        (4,5,5) then they will come out with the same emission prob, is that desired?
        """
        emission_probs[(emission, state)] = prob_X_given_Y_Z * prob_Y_given_Z

    return emission_probs
Пример #8
0
def close_tie_probability(distribution, candidate1, candidate2):
    """
    Calculate the probability that candidate2 have one more vote than
        candidate1.

    Args:
        distribution(list): Distribution over three candidates.
        candidate1(int): Index of the first candidate for the tie.
        candidate2(int): Index of the second candidate for the tie.

   Return:
       double. the probability that candidate2 wins and candidate1 have one
            less vote.
    """

    candidates_index = [candidate1, candidate2]
    candidate3 = [
        x for x in range(len(distribution)) if x not in candidates_index
    ][0]

    total_amount = float(sum(distribution))
    candidates_probability = [
        distribution[cand] / total_amount
        for cand in [candidate1, candidate2, candidate3]
    ]

    start_value = int(math.floor((total_amount + 1) / 3.0)) + 1
    close_tie_probability_value = 0
    for votes in range(start_value, int(total_amount + 1) / 2 + 1):
        state = [votes - 1, votes, total_amount - 2 * votes + 1]
        state_probability = multinomial.pmf(state, total_amount,
                                            candidates_probability)
        close_tie_probability_value += state_probability

    return close_tie_probability_value
Пример #9
0
def main():
    s = 0.0
    for x in range(0,200):
        s = s + norm.pdf(x,0,1)
        s = s + binom.pmf(x,100,0.1)
        s = s + gamma.pdf(x,1,1)
        s = s + beta.pdf(x/200,1,2)
        s = s + multinomial.pmf([x,200-x,0],200,[1/3, 1/3, 1/3])
    return s
Пример #10
0
def main():
    s = 0.0
    x = np.arange(201)
    s = s + sum(norm.pdf(x,0,1))
    s = s + sum(binom.pmf(x,100,0.1))
    s = s + sum(gamma.pdf(x,1,1))
    s = s + sum(beta.pdf(x/200,1,2))
    s = s + sum(multinomial.pmf([[x,200-x,0] for x in x],200,[1/3, 1/3, 1/3]))
    return s
Пример #11
0
 def pdf(self, F, y, Y_metadata=None):
     Y_oneK = self.onehot(y)
     eF = safe_exp(F)
     den = 1 + eF.sum(1)[:, None]
     p = eF / np.tile(den, eF.shape[1])
     p = np.hstack((p, 1 / den))
     p = np.clip(p, 1e-9, 1 - 1e-9)
     p = p / np.tile(p.sum(1)[:,None], (1, p.shape[1]))
     pdf = multinomial.pmf(x=Y_oneK, n=1, p=p)
     return pdf
Пример #12
0
 def loglikelihood(self):
     ll = 0
     for x in range(self.M):
         tmp = 0
         # pmf returns nan of the vector is empty, therefore: set n to 1 for empty vectors
         if np.sum(self.keywords[x]) > 0:
             n_k = np.sum(self.keywords[x])
         else: n_k = 1
         if np.sum(self.persons[x]) > 0:
             n_p = np.sum(self.persons[x])
         else: n_p = 1
         if np.sum(self.places[x]) > 0:
             n_l = np.sum(self.places[x])
         else: n_l = 1
         for e in range(self.k):
             t_prob = norm.pdf(self.days[x], self.mus[e], self.sigmas[e]) + self.a
             k_prob = multinomial.pmf(self.keywords[x], n_k, self.phi_k[:, e]) + self.a
             p_prob = multinomial.pmf(self.persons[x], n_p, self.phi_p[:, e]) + self.a
             l_prob = multinomial.pmf(self.places[x], n_l, self.phi_l[:, e]) + self.a
             tmp += (self.pi[e] + self.a) * k_prob * p_prob * l_prob * t_prob
         ll += np.log(tmp)
     return ll
Пример #13
0
def getCOC(file1, file2, aaID, globalR):

    CodonTable = [['GAT', 'GAC'], ['ATA', 'ATT', 'ATC']]

    aaList = ['E', 'I']

    codonChoice = CodonTable[aaID]

    choiceSize = len(codonChoice)

    f1 = open(file1, 'r')

    while (True):

        line = f1.readline()

        if line == '':
            break

        if line[0] != '>':

            DNA = line
            Seq = []

            for i in range(len(DNA) - 2):

                Seq.append(DNA[i * 3:(i + 1) * 3])

            X = []

            for k in range(choiceSize):

                X.append(DNA.count(codonChoice[k]))

            lenSub = sum(X)

            Pi = multinomial.pmf(X, lenSub, globalR)

            Pmax = Efor(choiceSize, lenSub, globalR)

            f2 = open(file2, 'a')

            f2.write(aaList[aaID] + ',' + X + ',' + lenSub + ',' + Pi + ',' + Pmax \
                     + '\n')

    f2.close()
    f1.close()

    return
Пример #14
0
def compute_p_value(data):
    '''
    :param data:
    :return:
    '''
    assert isinstance(data, pd.DataFrame)

    res = 1
    for i in range(3):
        temp = list(data.iloc[:, i])
        print(temp)
        res = res * multinomial.pmf(
            temp, sum(temp), p=[1 / 4, 1 / 4, 1 / 4, 1 / 4])

    return res
Пример #15
0
def get_attacking_points(player_id, position, team, opponent, is_home, minutes,
                         model_team, df_player):
    """
    use team-level and player-level models.
    """
    if position == "GK" or minutes == 0.0:
        # don't bother with GKs as they barely ever get points like this
        # if no minutes are played, can't score any points
        return 0.0

    # compute multinomial probabilities given time spent on pitch
    pr_score = (minutes / 90.0) * df_player.loc[player_id]["pr_score"]
    pr_assist = (minutes / 90.0) * df_player.loc[player_id]["pr_assist"]
    pr_neither = 1.0 - pr_score - pr_assist
    multinom_probs = (pr_score, pr_assist, pr_neither)

    def _get_partitions(n):
        # partition n goals into possible combinations of
        # [n_goals, n_assists, n_neither]
        partitions = []
        for i in range(0, n + 1):
            for j in range(0, n - i + 1):
                partitions.append([i, j, n - i - j])
        return partitions

    def _get_partition_score(partition):
        # calculate the points scored for a given partition
        return (points_for_goal[position] * partition[0] +
                points_for_assist * partition[1])

    # compute the weighted sum of terms like:
    #   points(ng, na, nn) * p(ng, na, nn | Ng, T) * p(Ng)
    exp_points = 0.0
    for ngoals in range(1, 11):
        partitions = _get_partitions(ngoals)
        probabilities = multinomial.pmf(partitions,
                                        n=[ngoals] * len(partitions),
                                        p=multinom_probs)
        scores = map(_get_partition_score, partitions)
        exp_score_inner = sum(pi * si for pi, si in zip(probabilities, scores))
        team_goal_prob = model_team.score_n_probability(
            ngoals, team, opponent, is_home)
        exp_points += exp_score_inner * team_goal_prob
    return exp_points
def Sampling_goal(Otb_B, THETA):
    #THETAを展開
    W, W_index, Myu, S, pi, phi_l, K, L = THETA

    #Prob math func of p(it | Otb_B, THETA) = Σc p(it | phi_c)p(st=Otb_B | Wc)p(c | pi)
    pmf_it = np.ones(K)
    for i in range(K):
        sum_Ct = np.sum([
            phi_l[c][i] * multinomial.pmf(Otb_B, sum(Otb_B), W[c]) * pi[c]
            for c in range(L)
        ])
        pmf_it[i] = sum_Ct

    #Normalization
    pmf_it_n = np.array([pmf_it[i] / float(np.sum(pmf_it)) for i in range(K)])

    #Sampling it from multinomial distribution
    sample_it = multinomial.rvs(Sampling_J,
                                pmf_it_n,
                                size=1,
                                random_state=None)
    print(sample_it)
    goal_candidate = []
    for it in range(K):
        count_it = 0
        while (count_it < sample_it[0][it]):
            goal_candidate += [
                Map_coordinates_To_Array_index(
                    multivariate_normal.rvs(mean=Myu[it],
                                            cov=S[it],
                                            size=1,
                                            random_state=None))
            ]
            count_it += 1
    #Xt_max = Map_coordinates_To_Array_index( [ Xp[pox.index(max(pox))][0], Xp[pox.index(max(pox))][1] ] ) #[0.0,0.0] ##確率最大の座標候補
    goal_candidate_tuple = [(goal_candidate[j][1], goal_candidate[j][0])
                            for j in range(Sampling_J)]
    print("Goal candidates:", goal_candidate_tuple)
    return goal_candidate_tuple
Пример #17
0
def cdist(carbon, ci):
    if (carbon >= ci):
        return multinomial.pmf([carbon - ci, ci], carbon, [0.989, 0.0107])
    else:
        return 0
Пример #18
0
from scipy.stats import multinomial
import numpy


def Efor(cLeng, subLeng, cfPart)

    P = cfPart

    X = subLeng * cfPart

    Xtest = mod(X,1) * 10

    if Xtest.search[~0]=0:

        Pmax = multinomial.pmf(Xtest, sum(Xtest), P)

    else:

        Xpre = X

        rmv = subLeng - sum(np.floor(Xpre))

        Pmax = getPmax(cLeng, cfPart, np.floor(Xpre) , rmv)

    return Pmax
Пример #19
0
    def calculate_chain_loglikelihood(self,
                      p_initial: InitDict,
                      p_emission: NestedInitDict,
                      p_transition: NestedInitDict,
                      n_initial: InitDict,
                      n_transition: NestedInitDict,
                      state_distribution,
                      chains,
                      states) -> Numeric:
        
        """
        Negative log likelihood of the chain, using the given parameters.
        Usually called with parameters given by the parent HDPHMM object.
        :param p_initial: dict, initial probabilities
        :param p_emission: dict, emission probabilities
        :param p_transition: dict, transition probabilities
        :return: float
        """
        
        # edge case: zero-length sequence
        if self.T == 0:
            return 0

        # np.prod([])==1, so this is safe

        # pull out the number of separate chains 
        n_chains = len(chains)
        
       

        if state_distribution == 'dirichlet':

            """
            to calculate likelihood if state_distribution == 'dirichlet'
            (i.e. p(Data|θ)), then we:
            1. calculate the log multionmial density of the n_initials given the parameters of the
            multinomial distribution p_initial drawn from the dirichlet prior;
            2. calculate the log multinomial density of the n_transitions for each state given the 
            parameters of the multinomial distributions p_transition for each state drawn from the dirichlet
            prior;
            3. calculate the log multinomial density of the n_emissions for each state given the 
            parameters of the multinomial distributions n_emissions for each state drawn from the dirichlet 
            prior, and;
            4 add the log densities together
            """

            start_likelihood = np.log(multinomial.pmf(list(n_initial[state].values()), 
                            n=n_chains, 
                            p=list(p_transition[state].values())))

            transition_likelihood = sum(np.log(multinomial.pmf(list(n_transition[state].values()), 
                            n=sum(list(n_transition[state].values())), 
                            p=list(p_transition[state].values()))) for state in states)

            emission_likelihood = sum(np.log(multinomial.pmf(list(n_emission[state].values()), 
                            n=sum(list(n_emission[state].values())), 
                            p=list(p_emission[state].values()))) for state in states)

            return start_likelihood + transition_likelihood + emission_likelihood

        elif state_distribution == 'univariate_gaussian':

            """
            to calculate likelihood if state_distribution == 'dirichlet'
            (i.e. p(Data|θ)), then we:
            1. calculate the log multionmial density of the n_initials given the parameters of the
            multinomial distribution p_initial drawn from the dirichlet prior;
            2. calculate the log multinomial density of the n_transitions for each state given the 
            parameters of the multinomial distributions p_transition for each state drawn from the dirichlet
            prior;
            3. for each emission in each chain, calculate the log gaussian density of the emission given the
            parameters of its respective state's gaussian distribution 
            4 add the log densities together
            """

            start_likelihood = np.log(multinomial.pmf(list(n_initial[state].values()), 
                            n=n_chains, 
                            p=list(p_transition[state].values())))

            transition_likelihood = sum(np.log(multinomial.pmf(list(n_transition[state].values()), 
                            n=sum(list(n_transition[state].values())), 
                            p=list(p_transition[state].values()))) for state in states)

            

            emission_likelihood = sum([sum([np.log(norm.pdf(chains[i].emission_sequence[j],
                p_emission[chains[i].latent_sequence[j]]['location'], p_emission[s]['scale']) \
                    for j in range(len(chains[i].latent_sequence)))]) for i in range(len(n_chains))])


            return start_likelihood + transition_likelihood + emission_likelihood
Пример #20
0
def Location_from_speech(Otb_B, THETA):
    #THETAを展開
    W, W_index, Myu, S, pi, phi_l, K, L = THETA

    ##全てのthe position distribution (Gaussian)の平均ベクトルを候補とする
    Xp = []

    for j in range(K):
        #x1,y1 = np.random.multivariate_normal([Myu[j][0][0],Myu[j][1][0]],S[j],1).T
        #the position distribution (Gaussian)の平均値とthe position distribution (Gaussian)からサンプリングした99点の1the position distribution (Gaussian)に対して合計100点をxtの候補とした
        #for i in range(9):
        #  x1,y1 = np.mean(np.array([ np.random.multivariate_normal([Myu[j][0][0],Myu[j][1][0]],S[j],1).T ]),0)
        #  Xp = Xp + [[x1,y1]]
        #  print x1,y1
        Xp = Xp + [[Myu[j][0], Myu[j][1]]]
        print(Myu[j][0], Myu[j][1])

    pox = [0.0 for i in range(len(Xp))]

    ##位置dataごとに
    for xdata in range(len(Xp)):
        ###提案手法による尤度計算####################
        #Ot_index = 0

        #for otb in range(len(W_index)):
        #Otb_B = [0 for j in range(len(W_index))]
        #Otb_B[Ot_index] = 1
        temp = [0.0 for c in range(L)]
        #print Otb_B
        for c in range(L):
            ##the name of place, multinomial distributionの計算
            #W_temp = multinomial(W[c])
            #temp[c] = W_temp.pmf(Otb_B)
            temp[c] = multinomial.pmf(Otb_B, sum(Otb_B), W[c]) * pi[c]
            #temp[c] = W[c][otb]
            ##場所概念のmultinomial distribution, piの計算
            #temp[c] = temp[c]

            ##itでサメーション
            it_sum = 0.0
            for it in range(K):
                """
                if (S[it][0][0] < pow(10,-100)) or (S[it][1][1] < pow(10,-100)) :    ##共分散の値が0だとゼロワリになるので回避
                    if int(Xp[xdata][0]) == int(Myu[it][0]) and int(Xp[xdata][1]) == int(Myu[it][1]) :  ##他の方法の方が良いかも
                        g2 = 1.0
                        print "gauss 1"
                    else : 
                        g2 = 0.0
                        print "gauss 0"
                else : 
                    g2 = gaussian2d(Xp[xdata][0],Xp[xdata][1],Myu[it][0],Myu[it][1],S[it])  #2-dimensionGaussian distributionを計算
                """
                g2 = multivariate_normal.pdf(Xp[xdata],
                                             mean=Myu[it],
                                             cov=S[it])
                it_sum = it_sum + g2 * phi_l[c][it]

            temp[c] = temp[c] * it_sum

        pox[xdata] = sum(temp)

        #print Ot_index,pox[Ot_index]
        #Ot_index = Ot_index + 1
        #POX = POX + [pox.index(max(pox))]

        #print pox.index(max(pox))
        #print W_index_p[pox.index(max(pox))]

    Xt_max = Map_coordinates_To_Array_index(
        [Xp[pox.index(max(pox))][0],
         Xp[pox.index(max(pox))][1]])  #[0.0,0.0] ##確率最大の座標候補
    Xt_max_tuple = (Xt_max[1], Xt_max[0])
    print("Goal:", Xt_max_tuple)
    return Xt_max_tuple
Пример #21
0
def row_multinomial(row):
    ns = [r for r in row[:4] if r > 0]
    ns.append(row['counts'] - sum(ns))
    alphas = [ n / row['counts'] for n in ns]
    return multinomial.pmf(ns, n=row['counts'], p=alphas)
Пример #22
0
def sdist(sulphur, s33i, s34i):
    if (sulphur >= (s33i + s34i)):
        return multinomial.pmf([sulphur - s33i - s34i, s33i, s34i], sulphur,
                               [0.9493, 0.0076, 0.0429])
    else:
        return 0
Пример #23
0
def odist(oxygen, o17i, o18i):
    if (oxygen >= (o17i + o18i)):
        return multinomial.pmf([oxygen - o17i - o18i, o17i, o18i], oxygen,
                               [0.99757, 0.00038, 0.00205])
    else:
        return 0
Пример #24
0
def ndist(nitrogen, ni):
    if (nitrogen >= ni):
        return multinomial.pmf([nitrogen - ni, ni], nitrogen,
                               [0.99632, 0.00368])
    else:
        return 0
Пример #25
0
def rowmnd(row):
    ns = [r for r in row.iloc[:4] if r > 0]
    ns.append(row.iloc[4] - sum(ns))
    alphas = [n / row.iloc[4] for n in ns]
    return multinomial.pmf(ns, n=row.iloc[4], p=alphas)
Пример #26
0
def PathPlanner(S_Nbest, X_init, THETA, CostMapProb): #gridmap, costmap):
    print "[RUN] PathPlanner"
    #THETAを展開
    W, W_index, Mu, Sig, Pi, Phi_l, K, L = THETA

    #ROSの座標系の現在位置を2-dimension array index にする
    X_init_index = X_init ###TEST  #Map_coordinates_To_Array_index(X_init)
    print "Initial Xt:",X_init_index

    #length and width of the MAP cells
    map_length = len(CostMapProb)     #len(costmap)
    map_width  = len(CostMapProb[0])  #len(costmap[0])
    print "MAP[length][width]:",map_length,map_width

    #Pre-calculation できるものはしておく
    if (St_separate == 1):
        Sum_C_Multi_nbest = [ sum([multinomial.pmf(S_Nbest[n], sum(S_Nbest[n]), W[c]) for c in xrange(L)]) for n in xrange(N_best)]
        LookupTable_ProbCt = np.array([ sum([ (multinomial.pmf(S_Nbest[n], sum(S_Nbest[n]), W[c])/Sum_C_Multi_nbest[n]) for n in xrange(N_best)]) * Pi[c] for c in xrange(L)])  #Ctごとの確率分布 p(St|W_Ct)×p(Ct|Pi) の確率値
    else:
        LookupTable_ProbCt = np.array([multinomial.pmf(S_Nbest, sum(S_Nbest), W[c])*Pi[c] for c in xrange(L)])  #Ctごとの確率分布 p(St|W_Ct)×p(Ct|Pi) の確率値

    ###SaveLookupTable(LookupTable_ProbCt, outputfile)
    ###LookupTable_ProbCt = ReadLookupTable(outputfile)  #Read the result from the Pre-calculation file(計算する場合と大差ないかも)


    print "Please wait for PostProbMap"
    output = outputfile + "N"+str(N_best)+"G"+str(speech_num) + "_PathWeightMap.csv"
    if (os.path.isfile(output) == False) or (UPDATE_PostProbMap == 1):  #すでにファイルがあれば作成しない
      #PathWeightMap = PostProbMap_jit(CostMapProb,Mu,Sig,Phi_l,LookupTable_ProbCt,map_length,map_width,L,K) #マルチCPUで高速化できるかも #CostMapProb * PostProbMap #後の処理のために, この時点ではlogにしない
      PathWeightMap = PostProbMap_nparray_jit(CostMapProb,Mu,Sig,Phi_l,LookupTable_ProbCt,map_length,map_width,L,K) #,IndexMap) 
      
      #[TEST]計算結果を先に保存
      SaveProbMap(PathWeightMap, outputfile)
    else:
      PathWeightMap = ReadProbMap(outputfile)
      #print "already exists:", output
    print "[Done] PathWeightMap."


    #[メモリ・処理の軽減]初期位置のセルからT_horizonよりも離れた位置のセルをすべて2-dimension array から消す([(2*T_horizon)+1][(2*T_horizon)+1]の array になる)
    Bug_removal_savior = 0  #座標変換の際にバグを生まないようにするためのフラグ
    x_min = X_init_index[0] - T_horizon
    x_max = X_init_index[0] + T_horizon
    y_min = X_init_index[1] - T_horizon
    y_max = X_init_index[1] + T_horizon
    if (x_min>=0 and x_max<=map_width and y_min>=0 and y_max<=map_length):
      PathWeightMap = PathWeightMap[x_min:x_max+1, y_min:y_max+1] # X[-T+I[0]:T+I[0],-T+I[1]:T+I[1]]
      X_init_index = [T_horizon, T_horizon]
      #再度, length and width of the MAP cells
      map_length = len(PathWeightMap)
      map_width  = len(PathWeightMap[0])
    else:
      print "[WARNING] The initial position (or init_pos +/- T_horizon) is outside the map."
      Bug_removal_savior = 1  #バグを生まない(1)
      #print X_init, X_init_index

    #計算量削減のため状態数を減らす(状態空間をone-dimension array にする⇒0の要素を除く)
    #PathWeight = np.ravel(PathWeightMap)
    PathWeight_one_NOzero = PathWeightMap[PathWeightMap!=0.0]
    state_num = len(PathWeight_one_NOzero)
    print "PathWeight_one_NOzero state_num:", state_num

    #map の2-dimension array インデックスとone-dimension array の対応を保持する
    IndexMap = np.array([[(i,j) for j in xrange(map_width)] for i in xrange(map_length)])
    IndexMap_one_NOzero = IndexMap[PathWeightMap!=0.0].tolist() #先にリスト型にしてしまう #実装上, np.arrayではなく2-dimension array リストにしている
    print "IndexMap_one_NOzero"


    #one-dimension array 上の初期位置
    if (X_init_index in IndexMap_one_NOzero):
      X_init_index_one = IndexMap_one_NOzero.index(X_init_index)
    else:
      print "[ERROR] The initial position is not a movable position on the map."
      #print X_init, X_init_index
      X_init_index_one = 0
    print "Initial index", X_init_index_one

    #移動先候補 index 座標のリスト(相対座標)
    MoveIndex_list = MovePosition_2D([0,0]) #.tolist()
    #MoveIndex_list = np.round(MovePosition(X_init_index)).astype(int)
    print "MoveIndex_list"

    """
    #状態遷移確率(Motion model)の計算
    print "Please wait for Transition"
    output_transition = outputfile + "T"+str(T_horizon) + "_Transition_sparse.mtx" # + "_Transition_log.csv"
    if (os.path.isfile(output_transition) == False):  #すでにファイルがあれば作成しない
      #IndexMap_one_NOzero内の2-dimension array 上 index と一致した要素のみ確率1を持つようにする
      #Transition = Transition_log_jit(state_num,IndexMap_one_NOzero,MoveIndex_list)
      Transition = Transition_sparse_jit(state_num,IndexMap_one_NOzero,MoveIndex_list)

      #[TEST]計算結果を先に保存
      #SaveTransition(Transition, outputfile)
      SaveTransition_sparse(Transition, outputfile)
    else:
      Transition = ReadTransition_sparse(state_num, outputfile) #ReadTransition(state_num, outputfile)
      #print "already exists:", output_transition

    Transition_one_NOzero = Transition #[PathWeightMap!=0.0]
    print "[Done] Transition distribution."
    """

    #Viterbi Algorithmを実行
    Path_one = ViterbiPath(X_init_index_one, np.log(PathWeight_one_NOzero), state_num,IndexMap_one_NOzero,MoveIndex_list, outputname, X_init, Bug_removal_savior) #, Transition_one_NOzero)

    #one-dimension array index を2-dimension array index へ⇒ROSの座標系にする
    Path_2D_index = np.array([ IndexMap_one_NOzero[Path_one[i]] for i in xrange(len(Path_one)) ])
    if ( Bug_removal_savior == 0):
      Path_2D_index_original = Path_2D_index + np.array(X_init) - T_horizon
    else:
      Path_2D_index_original = Path_2D_index
    Path_ROS = Array_index_To_Map_coordinates(Path_2D_index_original) #ROSのパスの形式にできればなおよい

    #Path = Path_2D_index_original #Path_ROS #必要な方をPathとして返す
    print "Init:", X_init
    print "Path:\n", Path_2D_index_original
    return Path_2D_index_original, Path_ROS, PathWeightMap
Пример #27
0
def hdist(hydrogen, hi):
    if (hydrogen >= hi):
        return multinomial.pmf([hydrogen - hi, hi], hydrogen,
                               [0.999885, 0.000115])
    else:
        return 0
Пример #28
0
Файл: stat.py Проект: cwand/mmct
def multinomialProb(x, ref):
    n_obs = np.sum(x)
    return multinomial.pmf(x, n=n_obs, p=ref)