
    cU                        d Z ddlZddlZddlZddlZddlmZmZ ddl	m
Z
mZmZ ddlmZmZ ddlmZmZ ddlmZ  ej        e          ZdZd	Zd
 ZddZ G d d          Z G d de
j        ej                  Z G d d          Z dS )a  Module for `online Hierarchical Dirichlet Processing
<http://jmlr.csail.mit.edu/proceedings/papers/v15/wang11a/wang11a.pdf>`_.

The core estimation code is directly adapted from the `blei-lab/online-hdp <https://github.com/blei-lab/online-hdp>`_
from `Wang, Paisley, Blei: "Online Variational Inference for the Hierarchical Dirichlet Process",  JMLR (2011)
<http://jmlr.csail.mit.edu/proceedings/papers/v15/wang11a/wang11a.pdf>`_.

Examples
--------

Train :class:`~gensim.models.hdpmodel.HdpModel`

.. sourcecode:: pycon

    >>> from gensim.test.utils import common_corpus, common_dictionary
    >>> from gensim.models import HdpModel
    >>>
    >>> hdp = HdpModel(common_corpus, common_dictionary)

You can then infer topic distributions on new, unseen documents, with

.. sourcecode:: pycon

    >>> unseen_document = [(1, 3.), (2, 4)]
    >>> doc_hdp = hdp[unseen_document]

To print 20 topics with top 10 most probable words.

.. sourcecode:: pycon

    >>> topic_info = hdp.print_topics(num_topics=20, num_words=10)

The model can be updated (trained) with new documents via

.. sourcecode:: pycon

    >>> hdp.update([[(1, 2)], [(1, 1), (4, 5)]])

    N)gammalnpsi)
interfacesutilsmatutils)dirichlet_expectationmean_absolute_difference)	basemodelldamodel)
deprecatedgh㈵>        c                 ^   t          t          j        | d                    }t          | d                   |z
  }t          | d                   |z
  }t          | d                   dz   }t          j        |          }||d|dz
  <   |dd         t          j        |          z   |dd<   |S )a   For stick-breaking hdp, get the :math:`\mathbb{E}[log(sticks)]`.

    Parameters
    ----------
    sticks : numpy.ndarray
        Array of values for stick.

    Returns
    -------
    numpy.ndarray
        Computed :math:`\mathbb{E}[log(sticks)]`.

    r      N)r   npsumlenzeroscumsum)sticksdig_sumElogWElog1_Wn
Elogstickss         6lib/python3.11/site-packages/gensim/models/hdpmodel.pyexpect_log_sticksr   H   s     "&##$$Gq	NNW$E&)nnw&GF1IA!J Jq!a%x^bi&8&88JqrrN    d   c                    t          j        t          |                    }t          j        t	          |                    }|dd| f         }t          j        ||          dz   }t          j        |          }	t          |          D ]}
|}||t          j        |	|z  |j                  z  z   }t	          |          }t          j        |          }t          j        ||          dz   }t          ||          }|t          k     r nt          j        |	t          j        |          z            }|t          j        ||z
  |z            z  }|t          j        t          |          t          |          z
            z  }|t          t          j        |                    t          t          j        |                    z
  z  }||fS )av  Performs EM-iteration on a single document for calculation of likelihood for a maximum iteration of `max_iter`.

    Parameters
    ----------
    doc_word_ids : int
        Id of corresponding words in a document.
    doc_word_counts : int
        Count of words in a single document.
    alpha : numpy.ndarray
        Lda equivalent value of alpha.
    beta : numpy.ndarray
        Lda equivalent value of beta.
    max_iter : int, optional
        Maximum number of times the expectation will be maximised.

    Returns
    -------
    (numpy.ndarray, numpy.ndarray)
        Computed (:math:`likelihood`, :math:`\gamma`).

    Ng0.++)r   onesr   expr   dotarrayrangeTr	   meanchangethreshr   logr   )doc_word_idsdoc_word_countsalphabetamax_itergammaexpElogthetabetadphinormcounts_	lastgamma	Elogtheta
meanchange
likelihoods                  r   
lda_e_stepr7   a   s   , GCJJE6/6677LL!Ef\5))F2GXo&&F8__ 	 		rvfw.>'H'HHH)%00	vi((&u--6-eY??
(( 	E	 011J"&%%-94555J"&'%..8999J'"&--((726%==+A+AAAJur   c                       e Zd ZdZd Zd ZdS )	SuffStatsa8  Stores sufficient statistics for the current chunk of document(s) whenever Hdp model is updated with new corpus.
    These stats are used when updating lambda and top level sticks. The statistics include number of documents in the
    chunk, length of words in the documents and top level truncation level.

    c                 |    || _         t          j        |          | _        t          j        ||f          | _        dS )z

        Parameters
        ----------
        T : int
            Top level truncation level.
        Wt : int
            Length of words in the documents.
        Dt : int
            Chunk size.

        N)m_chunksizer   r   m_var_sticks_ssm_var_beta_ss)selfr%   WtDts       r   __init__zSuffStats.__init__   s8     !x{{Xq"g..r   c                 n    | j                             d           | j                            d           dS )z3Fill the sticks and beta array with 0 scalar value.r   N)r<   fillr=   )r>   s    r   set_zerozSuffStats.set_zero   s6    !!#&&&$$$$$r   N)__name__
__module____qualname____doc__rA   rD    r   r   r9   r9      s<         
/ / /"% % % % %r   r9   c                       e Zd ZdZ	 	 	 	 d!dZd Zd"dZd Zd Zd#dZ	d Z
d Zd Zd Zd$dZd Zd%dZ ed          d&d            Z ed          d             Zd Zd Zd  ZdS )'HdpModela  `Hierarchical Dirichlet Process model <http://jmlr.csail.mit.edu/proceedings/papers/v15/wang11a/wang11a.pdf>`_

    Topic models promise to help summarize and organize large archives of texts that cannot be easily analyzed by hand.
    Hierarchical Dirichlet process (HDP) is a powerful mixed-membership model for the unsupervised analysis of grouped
    data. Unlike its finite counterpart, latent Dirichlet allocation, the HDP topic model infers the number of topics
    from the data. Here we have used Online HDP, which provides the speed of online variational Bayes with the modeling
    flexibility of the HDP. The idea behind Online variational Bayes in general is to optimize the variational
    objective function  with stochastic optimization.The challenge we face is that the existing coordinate ascent
    variational Bayes algorithms for the HDP require complicated approximation methods or numerical optimization. This
    model utilises stick breaking construction of Hdp which enables it to allow for coordinate-ascent variational Bayes
    without numerical approximation.

    **Stick breaking construction**

    To understand the HDP model we need to understand how it is modelled using the stick breaking construction. A very
    good analogy to understand the stick breaking construction is `chinese restaurant franchise
    <https://www.cs.princeton.edu/courses/archive/fall07/cos597C/scribe/20070921.pdf>`_.


    For this assume that there is a restaurant franchise (`corpus`) which has a large number of restaurants
    (`documents`, `j`) under it. They have a global menu of dishes (`topics`, :math:`\Phi_{k}`) which they serve.
    Also, a single dish (`topic`, :math:`\Phi_{k}`) is only served at a single table `t` for all the customers
    (`words`, :math:`\theta_{j,i}`) who sit at that table.
    So, when a customer enters the restaurant he/she has the choice to make where he/she wants to sit.
    He/she can choose to sit at a table where some customers are already sitting , or he/she can choose to sit
    at a new table. Here the probability of choosing each option is not same.

    Now, in this the global menu of dishes correspond to the global atoms  :math:`\Phi_{k}`, and each restaurant
    correspond to a single document `j`. So the number of dishes served in a particular restaurant correspond to the
    number of topics in a particular document. And the number of people sitting at each table correspond to the number
    of words belonging to each topic inside the document `j`.

    Now, coming on to the stick breaking construction, the concept understood from the chinese restaurant franchise is
    easily carried over to the stick breaking construction for hdp (`"Figure 1" from "Online Variational Inference
    for the Hierarchical Dirichlet Process" <http://proceedings.mlr.press/v15/wang11a/wang11a.pdf>`_).

    A two level hierarchical dirichlet process is a collection of dirichlet processes :math:`G_{j}` , one for each
    group, which share a base distribution :math:`G_{0}`, which is also a dirichlet process. Also, all :math:`G_{j}`
    share the same set of atoms, :math:`\Phi_{k}`, and only the atom weights :math:`\pi _{jt}` differs.

    There will be multiple document-level atoms :math:`\psi_{jt}` which map to the same corpus-level atom
    :math:`\Phi_{k}`. Here, the :math:`\beta` signify the weights given to each of the topics globally. Also, each
    factor :math:`\theta_{j,i}` is distributed according to :math:`G_{j}`, i.e., it takes on the value of
    :math:`\Phi_{k}` with probability :math:`\pi _{jt}`. :math:`C_{j,t}` is an indicator variable whose value `k`
    signifies the index of :math:`\Phi`. This helps to map :math:`\psi_{jt}` to :math:`\Phi_{k}`.

    The top level (`corpus` level) stick proportions correspond the values of :math:`\beta`,
    bottom level (`document` level) stick proportions correspond to the values of :math:`\pi`.
    The truncation level for the corpus (`K`) and document (`T`) corresponds to the number of :math:`\beta`
    and :math:`\pi` which are in existence.

    Now, whenever coordinate ascent updates are to be performed, they happen at two level. The document level as well
    as corpus level.

    At document level, we update the following:

    #. The parameters to the document level sticks, i.e, a and b parameters of :math:`\beta` distribution of the
       variable :math:`\pi _{jt}`.
    #. The parameters to per word topic indicators, :math:`Z_{j,n}`. Here :math:`Z_{j,n}` selects topic parameter
       :math:`\psi_{jt}`.
    #. The parameters to per document topic indices :math:`\Phi_{jtk}`.

    At corpus level, we update the following:

    #. The parameters to the top level sticks, i.e., the parameters of the :math:`\beta` distribution for the
       corpus level :math:`\beta`, which signify the topic distribution at corpus level.
    #. The parameters to the topics :math:`\Phi_{k}`.

    Now coming on to the steps involved, procedure for online variational inference for the Hdp model is as follows:

    1. We initialise the corpus level parameters, topic parameters randomly and set current time to 1.
    2. Fetch a random document j from the corpus.
    3. Compute all the parameters required for document level updates.
    4. Compute natural gradients of corpus level parameters.
    5. Initialise the learning rate as a function of kappa, tau and current time. Also, increment current time by 1
       each time it reaches this step.
    6. Update corpus level parameters.

    Repeat 2 to 6 until stopping condition is not met.

    Here the stopping condition corresponds to

    * time limit expired
    * chunk limit reached
    * whole corpus processed

    Attributes
    ----------
    lda_alpha : numpy.ndarray
        Same as :math:`\alpha` from :class:`gensim.models.ldamodel.LdaModel`.
    lda_beta : numpy.ndarray
        Same as :math:`\beta` from from :class:`gensim.models.ldamodel.LdaModel`.
    m_D : int
        Number of documents in the corpus.
    m_Elogbeta : numpy.ndarray:
        Stores value of dirichlet expectation, i.e., compute :math:`E[log \theta]` for a vector
        :math:`\theta \sim Dir(\alpha)`.
    m_lambda : {numpy.ndarray, float}
        Drawn samples from the parameterized gamma distribution.
    m_lambda_sum : {numpy.ndarray, float}
        An array with the same shape as `m_lambda`, with the specified axis (1) removed.
    m_num_docs_processed : int
        Number of documents finished processing.This is incremented in size of chunks.
    m_r : list
        Acts as normaliser in lazy updating of `m_lambda` attribute.
    m_rhot : float
        Assigns weight to the information obtained from the mini-chunk and its value it between 0 and 1.
    m_status_up_to_date : bool
        Flag to indicate whether `lambda `and :math:`E[log \theta]` have been updated if True, otherwise - not.
    m_timestamp : numpy.ndarray
        Helps to keep track and perform lazy updates on lambda.
    m_updatect : int
        Keeps track of current time and is incremented every time :meth:`~gensim.models.hdpmodel.HdpModel.update_lambda`
        is called.
    m_var_sticks : numpy.ndarray
        Array of values for stick.
    m_varphi_ss : numpy.ndarray
        Used to update top level sticks.
    m_W : int
        Length of dictionary for the input corpus.

    N         ?      P@      r   {Gz?-C6?c                 8   || _         || _        || _        || _        || _        || _        t          j        |          | _        d| _	        d| _
        t          |          | _        d| _        |rt          |          | _        |	| _        || _        |
| _        || _        t%          j        d|	dz
  f          | _        d| j        d<   t+          |	dz
  dd          | j        d<   t%          j        |	          | _        | j                            dd|	| j        f          | j        z  dz  |	| j        z  z  |z
  | _        || _        t5          | j        | j        z             | _        |dz   | _        || _        || _        d| _        d| _         d| _!        t%          j        | j        tD          	          | _#        dg| _$        t%          j%        | j        d
          | _&        || _'        | j        r| (                                 || )                    |           dS dS )a  

        Parameters
        ----------
        corpus : iterable of list of (int, float)
            Corpus in BoW format.
        id2word : :class:`~gensim.corpora.dictionary.Dictionary`
            Dictionary for the input corpus.
        max_chunks : int, optional
            Upper bound on how many chunks to process. It wraps around corpus beginning in another corpus pass,
            if there are not enough chunks in the corpus.
        max_time : int, optional
            Upper bound on time (in seconds) for which model will be trained.
        chunksize : int, optional
            Number of documents in one chuck.
        kappa: float,optional
            Learning parameter which acts as exponential decay factor to influence extent of learning from each batch.
        tau: float, optional
            Learning parameter which down-weights early iterations of documents.
        K : int, optional
            Second level truncation level
        T : int, optional
            Top level truncation level
        alpha : int, optional
            Second level concentration
        gamma : int, optional
            First level concentration
        eta : float, optional
            The topic Dirichlet
        scale : float, optional
            Weights information from the mini-chunk of corpus to calculate rhot.
        var_converge : float, optional
            Lower bound on the right side of convergence. Used when updating variational parameters for a
            single document.
        outputdir : str, optional
            Stores topic and options information in the specified directory.
        random_state : {None, int, array_like, :class:`~np.random.RandomState`, optional}
            Adds a little random jitter to randomize results around same alpha when trying to fetch a closest
            corresponding lda model from :meth:`~gensim.models.hdpmodel.HdpModel.suggested_lda_model`

        Nr      r   rM   r   T)dtypeaxis)*corpusid2word	chunksize
max_chunksmax_time	outputdirr   get_random_staterandom_state	lda_alphalda_betar   m_Wm_Dm_Tm_Km_alpham_gammar   r   m_var_sticksr$   m_varphi_ssr-   m_lambdam_etar   
m_Elogbetam_taum_kappam_scale
m_updatectm_status_up_to_datem_num_docs_processedintm_timestampm_rr   m_lambda_summ_var_convergesave_optionsupdate)r>   rY   rZ   r\   r]   r[   kappatauKr%   r*   r-   etascalevar_converger^   r`   s                    r   rA   zHdpModel.__init__'  s   Z "$ "!2<@@w<< 	#6{{DHHaQZ00"!$QUAr22!8A;;)//S1dh-HH48SVYY]^aeai]ijmpp
/
T]0JKK1W
#' $%!8DHC8883F4=q999*> 	   	 KK	  	 r   c                    | j         | j        t          d          t          |          }t	          |          dk    r(t
                              dt	          |                     t          j        t	          |          | j        j	        d         f          }t          |          D ]<\  }}|st          | \  }}t          ||| j         | j                  \  }}|||ddf<   =|S )a|  Infers the gamma value based for `chunk`.

        Parameters
        ----------
        chunk : iterable of list of (int, float)
            Corpus in BoW format.

        Returns
        -------
        numpy.ndarray
            First level concentration, i.e., Gamma value.

        Raises
        ------
        RuntimeError
            If model doesn't trained yet.

        Nz*model must be trained to perform inferencer   z/performing inference on a chunk of %i documentsr   )ra   rb   RuntimeErrorlistr   loggerdebugr   r   shape	enumeratezipr7   )	r>   chunkr-   ddocidsr1   r2   gammads	            r   	inferencezHdpModel.inference  s    & > 	MT] 	MKLLLUu::> 	XLLJCPUJJWWW#e**dm&9!&<=>>&& 	! 	!FAs s)KC"3NNIAv E!QQQ$KKr   c                    t          j        |          \  }}|r|                     |          S |                     |g          d         }t	          |          dk    r|t	          |          z  ng }fdt          |          D             S )a_  Accessor method for generating topic distribution of given document.

        Parameters
        ----------
        bow : {iterable of list of (int, float), list of (int, float)
            BoW representation of the document/corpus to get topics for.
        eps : float, optional
            Ignore topics with probability below `eps`.

        Returns
        -------
        list of (int, float) **or** :class:`gensim.interfaces.TransformedCorpus`
            Topic distribution for the given document/corpus `bow`, as a list of `(topic_id, topic_probability)` or
            transformed corpus

        r   c                 *    g | ]\  }}|k    ||fS rI   rI   ).0topicid
topicvalueepss      r   
<listcomp>z(HdpModel.__getitem__.<locals>.<listcomp>  s/    lll*=':ZdhkZkl*%lllr   )r   	is_corpus_applyr   r   r   )r>   bowr   r   rY   r-   
topic_dists     `    r   __getitem__zHdpModel.__getitem__  s    " "OC00	6 	';;v&&&u%%a(+.u::?BUSZZ''
llll:AVAVllllr   c                    t          dt          d| j        z                      }d}t          j                    }	 t          j        || j                  D ]}|                     |           | xj        t          |          z  c_        |dz  }| 
                    ||| j                  rl|                                  |                                 \  }}|| _        || _        |                     d           | j        r|                                   dS ||z  dk    rO|                                  |                     d           t$                              d| j        | j                   8)aM  Train the model with new documents, by EM-iterating over `corpus` until any of the conditions is satisfied.

        * time limit expired
        * chunk limit reached
        * whole corpus processed

        Parameters
        ----------
        corpus : iterable of list of (int, float)
            Corpus in BoW format.

        r   i'  r   T   Nz$PROGRESS: finished document %i of %i)maxrt   r[   timeperf_counterr   grouperupdate_chunkrs   r   update_finishedupdate_expectations
hdp_to_ldara   rb   print_topicsr^   save_topicsr   inford   )r>   rY   	save_freqchunks_processed
start_timer   r*   r+   s           r   rz   zHdpModel.update  s{    3ut~56677	&((
	mvt~>> m m!!%((())SZZ7)) A% ''
4DdF_`` m,,..."&//"3"3KE4%*DN$(DM%%b)))~ +((***FF%	1Q6 m,,...%%b)))KK FHacgcklll)	mr   c                     | j         r|| j         k    p@| j        ot          j                    |z
  | j        k    p| j          o| j         o
|| j        k    S )a  Flag to determine whether the model has been updated with the new corpus or not.

        Parameters
        ----------
        start_time : float
            Indicates the current processor time as a floating point number expressed in seconds.
            The resolution is typically better on Windows than on Unix by one microsecond due to differing
            implementation of underlying function calls.
        chunks_processed : int
            Indicates progress of the update in terms of the number of chunks processed.
        docs_processed : int
            Indicates number of documents finished processing.This is incremented in size of chunks.

        Returns
        -------
        bool
            If True - model is updated, False otherwise.

        )r\   r]   r   r   rd   )r>   r   r   docs_processeds       r   r   zHdpModel.update_finished  sk    , _D!1T_!D Z R$"3"5"5
"BT]"RZ O#XDM(9XnPTPX>X	[r   Tc           	          t                      }g }|D ]5}|D ]0\  }}||vr't          |          ||<   |                    |           16t          |          }	t          j         fd j        |         D                       }
 j        dd|fxx         t          j         j        d         |
z
            z  cc<   t           j
         j        dd|f         z             t           j         j
        z   j        ddt          j        f         z             z
   j        dd|f<   t           j        |	t          |                    }t#           j                  }d}d}|D ]W}t          |          dk    rBt'          | \  }}                     ||||| j                  }|t-          |          z  }||z  }X|r                     |||           ||fS )a  Performs lazy update on necessary columns of lambda and variational inference for documents in the chunk.

        Parameters
        ----------
        chunk : iterable of list of (int, float)
            Corpus in BoW format.
        update : bool, optional
            If True - call :meth:`~gensim.models.hdpmodel.HdpModel.update_lambda`.
        opt_o : bool, optional
            Passed as argument to :meth:`~gensim.models.hdpmodel.HdpModel.update_lambda`.
            If True then the topics will be ordered, False otherwise.

        Returns
        -------
        (float, int)
            A tuple of likelihood and sum of all the word counts from each document in the corpus.

        c                 *    g | ]}j         |         S rI   )rv   )r   tr>   s     r   r   z)HdpModel.update_chunk.<locals>.<listcomp>&  s    HHHqtx{HHHr   NrU   r   r   )dictr   appendr   r#   ru   rk   r!   rv   r   rl   rc   rw   newaxisrm   r9   re   r   ri   r   
doc_e_steprx   r   update_lambda)r>   r   rz   opt_ounique_words	word_listr   word_idr2   wtrwssElogsticks_1stscorecountr(   r)   	doc_scores   `                 r   r   zHdpModel.update_chunk  s   ( vv	 	. 	.C! . .
,. .,/,=,=L)$$W---.
 ^^ XHHHHD,<Y,GHHHIIaaal###rvdhrlR.?'@'@@###
T]111i<88994:%(9!!!RZ-(HHIIJ 	9% txSZZ00*4+<==  		# 		#C3xx!| #03S	-o OO ,#T%8 	
 _---" 	5r9e444e|r   c           	      	   fd|D             }| j         dd|f         }t          j        d| j        dz
  f          }	d|	d<   | j        |	d<   t          j        t          |          | j        f          dz  | j        z  }
d}d}d}d}d	}||k     r|dk     s||k    r|d
k     rNt          j        |
j        ||z  j                  }t          j
        |          \  }}t          j        |          }nPt          j        |
j        ||z  j                  |z   }t          j
        |          \  }}t          j        |          }|d
k     rFt          j        ||          j        }
t          j
        |
          \  }}t          j        |          }
nHt          j        ||          j        |z   }
t          j
        |
          \  }}t          j        |          }
|
t          j        |          ddt          j        f         z  }dt          j        |ddd| j        dz
  f         d          z   |	d<   t          j        t          j        |ddddf         d                    }| j        t          j        t          j        |                    z   |	d<   t#          |	          }d}|t          j        ||z
  |z            z  }t          j        | j                  }|| j        dz
  |z  z  }t'          t          j        |	d                    }|t          j        t          j        d| j        g          ddt          j        f         |	z
  t'          |	          |z
  z            z  }|t          j        t)          t          j        |	d                              t          j        t)          |	                    z
  z  }|t          j        ||z
  |
z            z  }|t          j        |
j        t          j        |||z            z            z  }||z
  t+          |          z  }|}|dk     rt,                              d           |dz  }||k     r|dk     ||k    |xj        t          j        |d          z  c_        |j        dd|fxx         t          j        |j        |
j        |z            z  cc<   |S )aO  Performs E step for a single doc.

        Parameters
        ----------
        ss : :class:`~gensim.models.hdpmodel.SuffStats`
            Stats for all document(s) in the chunk.
        Elogsticks_1st : numpy.ndarray
            Computed Elogsticks value by stick-breaking process.
        unique_words : dict of (int, int)
            Number of unique words in the chunk.
        doc_word_ids : iterable of int
            Word ids of for a single document.
        doc_word_counts : iterable of int
            Word counts of all words in a single document.
        var_converge : float
            Lower bound on the right side of convergence. Used when updating variational parameters for a single
            document.

        Returns
        -------
        float
            Computed value of likelihood for a single document.

        c                      g | ]
}|         S rI   rI   )r   idr   s     r   r   z'HdpModel.doc_e_step.<locals>.<listcomp>\  s    <<<L$<<<r   NrT   r   rM   r   r   gZbtr      gưzlikelihood is decreasing!)rm   r   r   rf   rg   r    r   r"   r%   r   ret_log_normalize_vecr!   r#   r   r   flipudr   r   r'   r   r   absr   warningr<   r=   )r>   r   r   r   r(   r)   r   chunkidsElogbeta_docvphir6   old_likelihoodconvergeiterr,   var_philog_var_philog_normlog_phiElogsticks_2ndphi_allphi_cum	log_alphar   s      `                     r   r   zHdpModel.doc_e_stepC  s   2 =<<<|<<<qqq,7HaA&''!|! gs<(($(344s:TXE
Xo 6	8c> 6	X5L 6	 ax .&)G(JKK*2*H*Q*Q'h&--&)G(JKKn\*2*H*Q*Q'h&-- ax &fWl335&.&DS&I&I#(fWoofWl335F&.&DS&I&I#(fWoo BH_55aaamDDG=DHqL=(8 91===AaDiwqqq!""u~q 9 9::G<")BIg,>,>"?"??AaD.q11NJ "&.;">'!IJJJJ t|,,I48a<944J"&A,,''G"&"(C+>"?"?2:"NQR"RWZ[\W]W]`gWg!hiiiJ"&1!6!677"&:L:LLLJ "&.7":c!ABBBJ "&9W)X)X!XYYYJ"^3s>7J7JJH'N)# <:;;;AIDm Xo 6	8c> 6	X5L 6	t 	bfWa000
H%%%	35?;R)S)SS%%%r   c                    d| _         | j        t          | j        | j        z   | j                   z  }|t          k     rt          }|| _        | j        dd|f         d|z
  z  || j	        z  |j
        z  |j        z  z   | j        dd|f<   d|z
  | j        z  || j	        z  t          j        |j
        d          z  |j        z  z   | _        | xj        dz  c_        | j        | j        |<   | j                            | j        d         t          j        d|z
            z              d|z
  | j        z  ||j        z  | j	        z  |j        z  z   | _        |r|                                  | j        d| j        dz
           dz   | j        d<   t          j        | j        dd                   }t          j        t          j        |                    | j        z   | j        d<   dS )a  Update appropriate columns of lambda and top level sticks based on documents.

        Parameters
        ----------
        sstats : :class:`~gensim.models.hdpmodel.SuffStats`
            Statistic for all document(s) in the chunk.
        word_list : list of int
            Contains word id of all the unique words in the chunk of documents on which update is being performed.
        opt_o : bool, optional
            If True - invokes a call to :meth:`~gensim.models.hdpmodel.HdpModel.optimal_ordering` to order the topics.

        FNr   rW   rU   rM   r   )rr   rp   powrn   rq   ro   
rhot_boundm_rhotrk   rd   r=   r;   rw   r   r   ru   rv   r   r'   rj   r<   optimal_orderingre   ri   r   r   rh   )r>   sstatsr   r   rhotvar_phi_sums         r   r   zHdpModel.update_lambda  s    $)  |c$*t">NNN* 	D M!!!Y,'1t84tdhI]7]`f`r7rr 	aaal#X)::48ObfV%9BBBBVEWWX 	1&*o#rva$h'7'77888 4Z4++dV5K.Kdh.VY_Yk.kk 	  	$!!###  $/A>D!i 0 455!y;)?)?@@4<O!r   c                     t          j        | j        d          }| j        |         | _        | j        |ddf         | _        | j        |         | _        | j        |ddf         | _        dS )z Performs ordering on the topics.TreverseN)r   argsortrw   rj   rk   rm   )r>   idxs     r   r   zHdpModel.optimal_ordering  sj    t0$???+C0c111f- -c2/#qqq&1r   c           
         t          | j                  D ]Q}| j        dd|fxx         t          j        | j        d         | j        | j        |                  z
            z  cc<   Rt          | j        | j        z             t          | j        | j        z  | j	        ddt          j
        f         z             z
  | _        | j        | j        dd<   d| _        dS )a0  Since we're doing lazy updates on lambda, at any given moment the current state of lambda may not be
        accurate. This function updates all of the elements of lambda and Elogbeta so that if (for example) we want to
        print out the topics we've learned we'll get the correct behavior.

        NrU   T)r$   rc   rk   r   r!   rv   ru   r   rl   rw   r   rm   rq   rr   )r>   ws     r   r   zHdpModel.update_expectations  s     tx 	X 	XAM!!!Q$26$(2,$BRSTBU9V*V#W#WW
T]*++c$(TZ2G$J[\]\]\]_a_i\iJj2j.k.kk 	 #o#'   r   r   Fc                     |t          j        d           |}| j        s|                                  | j        | j        z   }t          | j        |          }|                    ||||          S )a  Print the `num_words` most probable words for topic `topic_id`.

        Parameters
        ----------
        topic_id : int
            Acts as a representative index for a particular topic.
        topn : int, optional
            Number of most probable words to show from given `topic_id`.
        log : bool, optional
            If True - logs a message with level INFO on the logger object.
        formatted : bool, optional
            If True - get the topics as a list of strings, otherwise - get the topics as lists of (weight, word) pairs.
        num_words : int, optional
            DEPRECATED, USE `topn` INSTEAD.

        Warnings
        --------
        The parameter `num_words` is deprecated, will be removed in 4.0.0, please use `topn` instead.

        Returns
        -------
        list of (str, numpy.float) **or** list of str
            Topic terms output displayed whose format depends on `formatted` parameter.

        N]The parameter `num_words` is deprecated, will be removed in 4.0.0, please use `topn` instead.)	warningswarnrr   r   rk   rl   HdpTopicFormatterrZ   
show_topic)r>   topic_idtopnr'   	formatted	num_wordsbetashdp_formatters           r   r   zHdpModel.show_topic  s    4  	Mo   D' 	'$$&&&
*)$,>>''$YGGGr   c                 f    | j         | j        z   }||                    d          dddf         z  S )zGet the term topic matrix learned during inference.

        Returns
        -------
        np.ndarray
            `num_topics` x `vocabulary_size` array of floats

        r   rW   N)rk   rl   r   )r>   topicss     r   
get_topicszHdpModel.get_topics  s8     +


**111d7333r   c                     | j         s|                                  | j        | j        z   }t	          | j        |          }|                    ||||          S )a=  Print the `num_words` most probable words for `num_topics` number of topics.

        Parameters
        ----------
        num_topics : int, optional
            Number of topics for which most probable `num_words` words will be fetched, if -1 - print all topics.
        num_words :  int, optional
            Number of most probable words to show from `num_topics` number of topics.
        log : bool, optional
            If True - log a message with level INFO on the logger object.
        formatted : bool, optional
            If True - get the topics as a list of strings, otherwise - get the topics as lists of (weight, word) pairs.

        Returns
        -------
        list of (str, numpy.float) **or** list of str
            Output format for topic terms depends on the value of `formatted` parameter.

        )rr   r   rk   rl   r   rZ   show_topics)r>   
num_topicsr   r'   r   r   r   s          r   r   zHdpModel.show_topics  sZ    ( ' 	'$$&&&
*)$,>>((YYOOOr   z9This method will be removed in 4.0.0, use `save` instead.c                     | j         st                              d           |d}nd|z  }| j         d|d}t                              d|           | j        | j        z   }t          j        ||           dS )a>  Save discovered topics.

        Warnings
        --------
        This method is deprecated, use :meth:`~gensim.models.hdpmodel.HdpModel.save` instead.

        Parameters
        ----------
        doc_count : int, optional
            Indicates number of documents finished processing and are to be saved.

        z@cannot store topics without having specified an output directoryNfinalzdoc-%i/z.topicszsaving topics to %s)r^   r   errorr   rk   rl   r   savetxt)r>   	doc_countfnamer   s       r   r   zHdpModel.save_topics9  s     ~ 	]LL[\\\ 	)EEy(E"&...%%%8)5111
*

5%     r   c                 ^   | j         st                              d           dS d| j         z  }t          j        |d          5 }|                    dt          | j        dz
            z             |                    dt          | j                  z             |                    dt          | j	                  z             |                    d	t          | j
                  z             |                    d
t          | j                  z             |                    dt          | j                  z             |                    dt          | j                  z             |                    dt          | j                  z             |                    dt          | j                  z             |                    dt          | j                  z             |                    dt          | j                  z             ddd           dS # 1 swxY w Y   dS )zWrites all the values of the attributes for the current model in "options.dat" file.

        Warnings
        --------
        This method is deprecated, use :meth:`~gensim.models.hdpmodel.HdpModel.save` instead.

        zAcannot store options without having specified an output directoryNz%s/options.datwbztau: %s
r   zchunksize: %s
zvar_converge: %s
zD: %s
zK: %s
zT: %s
zW: %s
z
alpha: %s
z
kappa: %s
zeta: %s
z
gamma: %s
)r^   r   r   r   openwritestrrn   r[   rx   rd   rf   re   rc   rg   ro   rl   rh   )r>   r   fouts      r   ry   zHdpModel.save_optionsS  s    ~ 	LL\]]]F 4>1Zt$$ 	:JJ{Sa%8%88999JJ(3t~+>+>>???JJ+c$2E.F.FFGGGJJy3tx==0111JJy3tx==0111JJy3tx==0111JJy3tx==0111JJ}s4<'8'88999JJ}s4<'8'88999JJ{S__4555JJ}s4<'8'88999	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	:s   GH""H&)H&c                    | j         d         | j         d         | j         d         z   z  }t          j        | j                  }d}t	          d| j        dz
            D ]}||         |z  ||<   |||         z
  }||| j        dz
  <   || j        z  }| j        | j        z   | j        | j        z  | j	        ddt          j
        f         z   z  }||fS )zGet corresponding alpha and beta values of a LDA almost equivalent to current HDP.

        Returns
        -------
        (numpy.ndarray, numpy.ndarray)
            Alpha and Beta arrays.

        r   r   rM   N)ri   r   r   re   r$   rg   rk   rl   rc   rw   r   )r>   r   r*   leftir+   s         r   r   zHdpModel.hdp_to_ldam  s     "1%):1)=@QRS@T)TU""q$(Q,'' 	# 	#Aay4'E!H%(?DD"dhl 
*tx$*/DtGXYZYZYZ\^\fYfGg/ghd{r   c                     |                                  \  }}t          j        | j        || j        | j        t          j                  }||j        dd<   |S )aI  Get a trained ldamodel object which is closest to the current hdp model.

        The `num_topics=m_T`, so as to preserve the matrices shapes when we assign alpha and beta.

        Returns
        -------
        :class:`~gensim.models.ldamodel.LdaModel`
            Closest corresponding LdaModel to current HdpModel.

        )r   r*   rZ   r`   rV   N)	r   r   LdaModelre   rZ   r`   r   float64expElogbeta)r>   r*   r+   ldams       r   suggested_lda_modelzHdpModel.suggested_lda_model  s]     oo''t xudlQUQbjljt
 
 
 #r   c                    t                               d           | j        | j        !|                                 \  | _        | _        d}d}t          |          D ]\  }}t          |          dk    rt          | \  }}t          ||| j        | j                  \  }}	|	t          j
        |	          z  }
| j        dd|f         }t          j        t          j        |
|                    }t          |          t          |          z  }t                               d||           ||z  }|t          |          z  }t                               d||z  |t          |                     |S )aM  Evaluates the model on test corpus.

        Parameters
        ----------
        corpus : iterable of list of (int, float)
            Test corpus in BoW format.

        Returns
        -------
        float
            The value of total likelihood obtained by evaluating the model for all documents in the test corpus.

        zTEST: evaluating test corpusNr   r   zTEST: %6d    %.5fz<TEST: average score: %.5f, total score: %.5f,  test docs: %d)r   r   ra   rb   r   r   r   r   r7   r   r   r'   r"   )r>   rY   r   total_wordsr  r   r(   r)   r6   r-   theta	lda_betadlog_predictsr   s                 r   evaluate_test_corpuszHdpModel.evaluate_test_corpus  sd    	2333> 	>T] 	>,0OO,=,=)DNDM'' 
	4 
	4FAs3xx!| 	403S	-o$.|_dn^b^k$l$l!
Eu- M!!!\/:	!vbfUI&>&>??--C8	/I>>>#s?333JKF	
 	
 	
 r   )NNrL   rM   rN   rO   rP   r   r   rQ   rM   rR   NN)rQ   )TTr   FFN)r   r   FT)N)rE   rF   rG   rH   rA   r   r   rz   r   r   r   r   r   r   r   r   r   r   r   ry   r   r  r  rI   r   r   rK   rK      s       y yt CGHI<B.2^  ^  ^  ^ @     Dm m m m2%m %m %mN[ [ [<: : : :xh h hT(P (P (PT2 2 2( ( ($H $H $H $HL
4 
4 
4P P P P4 ZKLL! ! ! ML!2 ZKLL: : ML:2  0  $" " " " "r   rK   c                   P    e Zd ZdZd\  ZZddZddZdd	Zdd
Z	ddZ
d Zd ZdS )r   zYHelper class for :class:`gensim.models.hdpmodel.HdpModel` to format the output of topics.)r   rT   Nc                 $   |t          d          ||}n)|t          j        d|z            }nt          d          t          j        |d          }t	          j        |d          }||         | _        || _        || j        }|| _	        dS )	a  Initialise the :class:`gensim.models.hdpmodel.HdpTopicFormatter` and store topic data in sorted order.

        Parameters
        ----------
        dictionary : :class:`~gensim.corpora.dictionary.Dictionary`,optional
            Dictionary for the input corpus.
        topic_data : numpy.ndarray, optional
            The term topic matrix.
        topic_file : {file-like object, str, pathlib.Path}
            File, filename, or generator to read. If the filename extension is .gz or .bz2, the file is first
            decompressed. Note that generators should return byte strings for Python 3k.
        style : bool, optional
            If True - get the topics as a list of strings, otherwise - get the topics as lists of (word, weight) pairs.

        Raises
        ------
        ValueError
            Either dictionary is None or both `topic_data` and `topic_file` is None.

        Nzno dictionary!z%szno topic data!r   rW   Tr   )

ValueErrorr   loadtxtr   r   r   data
dictionarySTYLE_GENSIMstyle)r>   r  
topic_data
topic_filer  r   topics_sumsr   s           r   rA   zHdpTopicFormatter.__init__  s    *  	/-... 	/FF 	/Zz 122FF-... fV!,,,{D9993K	$ 	&%E


r   
   c                 0    |                      ||d          S )aT  Give the most probable `num_words` words from `num_topics` topics.
        Alias for :meth:`~gensim.models.hdpmodel.HdpTopicFormatter.show_topics`.

        Parameters
        ----------
        num_topics : int, optional
            Top `num_topics` to be printed.
        num_words : int, optional
            Top `num_words` most probable words to be printed from each topic.

        Returns
        -------
        list of (str, numpy.float) **or** list of str
            Output format for `num_words` words from `num_topics` topics depends on the value of `self.style` attribute.

        T)r   )r>   r   r   s      r   r   zHdpTopicFormatter.print_topics  s    " 
It<<<r   FTc           	      $   g }t          |d          }t          |t          | j                            }t	          |          D ]}| j        |ddf         }||                                z  }t          |t	          t          |                              }t          |d d          }|                     ||          }	|r3| 	                    ||	          }
|rt                              |
           n||	f}
|                    |
           |S )a  Give the most probable `num_words` words from `num_topics` topics.

        Parameters
        ----------
        num_topics : int, optional
            Top `num_topics` to be printed.
        num_words : int, optional
            Top `num_words` most probable words to be printed from each topic.
        log : bool, optional
            If True - log a message with level INFO on the logger object.
        formatted : bool, optional
            If True - get the topics as a list of strings, otherwise as lists of (word, weight) pairs.

        Returns
        -------
        list of (int, list of (str, numpy.float) **or** list of str)
            Output format for terms from `num_topics` topics depends on the value of `self.style` attribute.

        r   Nc                     | d         S Nr   rI   xs    r   <lambda>z/HdpTopicFormatter.show_topics.<locals>.<lambda>  s
    ad r   Tkeyr   )r   minr   r  r$   r   r   sortedshow_topic_termsformat_topicr   r   r   )r>   r   r   r'   r   shownklambdaktemptopic_termstopics              r   r   zHdpTopicFormatter.show_topics  s   ( Q''
S^^44
z"" 	  	 Ai111oG-Gwc'll 3 344D$NNDAAAD//i@@K )))![99  'KK&&&K(LLr   c                 b    |t          j        d           |}|                     ||d          S )a  Print the `topn` most probable words from topic id `topic_id`.

        Warnings
        --------
        The parameter `num_words` is deprecated, will be removed in 4.0.0, please use `topn` instead.

        Parameters
        ----------
        topic_id : int
            Acts as a representative index for a particular topic.
        topn : int, optional
            Number of most probable words to show from given `topic_id`.
        num_words : int, optional
            DEPRECATED, USE `topn` INSTEAD.

        Returns
        -------
        list of (str, numpy.float) **or** list of str
            Output format for terms from a single topic depends on the value of `formatted` parameter.

        Nr   T)r   )r   r   r   )r>   r   r   r   s       r   print_topiczHdpTopicFormatter.print_topic+  sB    ,  	Mo   Dx>>>r   r   c                    |t          j        d           |}| j        |ddf         }||                                z  }t	          |t          t          |                              }t          |d d          }|                     ||          }|r3| 	                    ||          }	|rt                              |	           n||f}	|	d         S )a  Give the most probable `num_words` words for the id `topic_id`.

        Warnings
        --------
        The parameter `num_words` is deprecated, will be removed in 4.0.0, please use `topn` instead.

        Parameters
        ----------
        topic_id : int
            Acts as a representative index for a particular topic.
        topn : int, optional
            Number of most probable words to show from given `topic_id`.
        log : bool, optional
            If True logs a message with level INFO on the logger object, False otherwise.
        formatted : bool, optional
            If True return the topics as a list of strings, False as lists of
            (word, weight) pairs.
        num_words : int, optional
            DEPRECATED, USE `topn` INSTEAD.

        Returns
        -------
        list of (str, numpy.float) **or** list of str
            Output format for terms from a single topic depends on the value of `self.style` attribute.

        Nr   c                     | d         S r$  rI   r%  s    r   r'  z.HdpTopicFormatter.show_topic.<locals>.<lambda>n  s
    !A$ r   Tr(  r   )r   r   r  r   r   r$   r   r+  r,  r-  r   r   )
r>   r   r   r'   r   r   r0  r1  r2  r3  s
             r   r   zHdpTopicFormatter.show_topicI  s    6  	Mo   D)HaaaK(GKKMM)7E#g,,//00d===++D$77 	,%%h<<E  #E"""{+E Qxr   c                 0      fd|d|         D             S )a  Give the topic terms along with their probabilities for a single topic data.

        Parameters
        ----------
        topic_data : list of (str, numpy.float)
            Contains probabilities for each word id belonging to a single topic.
        num_words : int
            Number of words for which probabilities are to be extracted from the given single topic data.

        Returns
        -------
        list of (str, numpy.float)
            A sequence of topic terms and their probabilities.

        c                 4    g | ]\  }}j         |         |fS rI   )r  )r   weightwidr>   s      r   r   z6HdpTopicFormatter.show_topic_terms.<locals>.<listcomp>  s)    [[[=FC%v.[[[r   NrI   )r>   r  r   s   `  r   r,  z"HdpTopicFormatter.show_topic_terms~  s*      \[[[JzPYzDZ[[[[r   c                     | j         | j        k    r d                    d |D                       }nd                    d |D                       }||f}|S )a  Format the display for a single topic in two different ways.

        Parameters
        ----------
        topic_id : int
            Acts as a representative index for a particular topic.
        topic_terms : list of (str, numpy.float)
            Contains the most probable words from a single topic.

        Returns
        -------
        list of (str, numpy.float) **or** list of str
            Output format for topic terms depends on the value of `self.style` attribute.

        z + c              3   *   K   | ]\  }}d ||fz  V  dS )z%.3f*%sNrI   r   wordr:  s      r   	<genexpr>z1HdpTopicFormatter.format_topic.<locals>.<genexpr>  s/      ZZNT6Y&$7ZZZZZZr   
c              3   *   K   | ]\  }}d ||fz  V  dS )z    %20s    %.8fNrI   r>  s      r   r@  z1HdpTopicFormatter.format_topic.<locals>.<genexpr>  s0      bbNT6.$?bbbbbbr   )r  r  join)r>   r   r2  fmts       r   r-  zHdpTopicFormatter.format_topic  sh      
* 	c**ZZkZZZZZCC))bbVabbbbbCo
r   )NNNN)r   r   )r   r   FT)NNr  )rE   rF   rG   rH   r  STYLE_PRETTYrA   r   r   r5  r   r,  r-  rI   r   r   r   r     s        cc#) \<) ) ) )V= = = =&+ + + +Z? ? ? ?<3 3 3 3j\ \ \$    r   r   )r   )!rH   loggingr   r   numpyr   scipy.specialr   r   gensimr   r   r   gensim.matutilsr   r	   gensim.modelsr
   r   gensim.utilsr   	getLoggerrE   r   r&   r   r   r7   r9   TransformationABCBaseTopicModelrK   r   rI   r   r   <module>rP     s  & &P        & & & & & & & & . . . . . . . . . . K K K K K K K K - - - - - - - - # # # # # # 
	8	$	$ 
  2+ + + +\% % % % % % % %:M M M M Mz+Y-E M M M`j j j j j j j j j jr   