/// <summary>
 ///     Constructs a new State associating all computed variables.
 /// </summary>
 /// <param name="states">Number of observations.</param>
 public TemporalState(int states)
 {
     Alpha = new double[states];
     Beta = new double[states];
     Gamma = new double[states];
     Delta = new double[states];
     State = new int[states];
     Xi = new MySparse2DMatrix();
 }
        /// <summary>
        ///     Returns a random index of the matrix state column using the given distribution.
        /// </summary>
        /// <param name="state">Current state.</param>
        /// <param name="matrix">Probability distribution matrix.</param>
        /// <returns>Random index of the matrix state column.</returns>
        private int randomExtraction(int state, MySparse2DMatrix matrix)
        {
            var rand = SystemRandomSource.Default;
            var extraction = rand.NextDouble();

            for (int i = 0; i < Symbols; i++)
            {
                if (extraction < matrix.getValue(state, i))
                    return i;
                extraction -= matrix.getValue(state, i);
            }

            return -1;
        }
        /// <summary>
        ///     Determining the frequency of the transition-emission pair values
        ///     and dividing it by the probability of the entire string.
        ///     
        ///     Using the scaled values, I don't need to divide it for the
        ///     probability of the entire string anymore
        /// </summary>
        /// <param name="t">Current time.</param>
        /// <param name="nextObservation">Observation at time t + 1.</param>
        /// <returns>Probability of transition from each state to any other at time t</returns>
        private MySparse2DMatrix calcXi(int t, int nextObservation)
        {
            if (tempInstancts == null)
                throw new ArgumentNullException("tempInstancts");

            if (tempInstancts[t].Alpha == null || tempInstancts[t].Beta == null)
                throw new ArgumentNullException("Alpha and Beta aren't set");

            MySparse2DMatrix currentXi = new MySparse2DMatrix();

            double s = 0;

            for (int i = 0; i < States; i++)
            {
                for (int j = 0; j < States; j++)
                {
                    double temp = tempInstancts[t].Alpha[i] * Transitions.getValue(i, j) * Emissions.getValue(j, nextObservation) * tempInstancts[t + 1].Beta[j];
                    s += temp;
                    if (temp != 0)
                        currentXi.setValue(i, j, temp);
                }
            }

            if (s != 0) // Scaling
            {
                for (int i = 0; i < States; i++)
                {
                    for (int j = 0; j < States; j++)
                    {
                        if (currentXi.getValue(i, j) != 0)
                            currentXi.setValue(i, j, currentXi.getValue(i, j) / s);
                    }
                }
            }

            return currentXi;
        }
 /// <summary>
 ///     Constructs a new Hidden Markov Model.
 /// </summary>
 /// <param name="transitions">The transitions matrix A for this model.</param>
 /// <param name="emissions">The emissions matrix B for this model.</param>
 /// <param name="probabilities">The initial state probabilities for this model.</param>
 public HiddenMarkovModel(MySparse2DMatrix transitions, MySparse2DMatrix emissions, double[] probabilities, int emissionSymbols)
 {
     A = transitions;
     B = emissions;
     Pi = probabilities;
     states = Pi.Length;
     symbols = emissionSymbols;
     tempInstancts = null;
 }
예제 #5
0
        private void openTransition_Click(object sender, EventArgs e)
        {
            // Set filter options and filter index.
            openFileDialog.FileName = "";
            openFileDialog.Filter = "Transition Files (.trans)|*.trans|All Files (*.*)|*.*";
            openFileDialog.FilterIndex = 1;
            openFileDialog.Multiselect = false;

            // Call the ShowDialog method to show the dialog box.
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                var firstLine = true;
                string line, firstState = "INIT";
                A = new MySparse2DMatrix();
                Pi = new List<double>();
                piSymbols = new List<string>();
                stateSymbols = new Id2Str();

                System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog.FileName);
                transitionsRichTextBox.Text = "";

                while ((line = sr.ReadLine()) != null)
                {
                    transitionsRichTextBox.Text += line + "\n";
                    if (firstLine)
                    {
                        firstState = line;
                        firstLine = false;
                    }
                    else
                    {
                        string[] stateValue = line.Split('\t');
                        if (stateValue.Length == 3)
                        {
                            if (stateValue[0] == firstState)
                            {
                                stateSymbols.setId(stateValue[1]);
                                piSymbols.Add(stateValue[1]);
                                Pi.Add(Double.Parse(stateValue[2], CultureInfo.InvariantCulture));
                            }
                            else
                            {
                                int row = stateSymbols.setId(stateValue[0]);
                                int col = stateSymbols.setId(stateValue[1]);
                                A.setValue(row, col, Double.Parse(stateValue[2], CultureInfo.InvariantCulture));
                                // Still need to add states to pi with probability 0
                                if (!piSymbols.Contains(stateValue[0]))
                                {
                                    piSymbols.Add(stateValue[0]);
                                    Pi.Add(0.0);
                                }
                                if (!piSymbols.Contains(stateValue[1]))
                                {
                                    piSymbols.Add(stateValue[1]);
                                    Pi.Add(0.0);
                                }
                            }
                        }
                    }
                }
                sr.Close();
                if (A.Count > 0)
                {
                    buttonOpenEmissions.Enabled = true;
                    openEmissionsToolStripMenuItem.Enabled = true;
                }
                else
                {
                    buttonOpenEmissions.Enabled = false;
                    openEmissionsToolStripMenuItem.Enabled = false;
                    MessageBox.Show("Error! Parsed transitions matrix resulted empty. Check your input file please.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
예제 #6
0
        private void openEmissions_Click(object sender, EventArgs e)
        {
            // Set filter options and filter index.
            openFileDialog.FileName = "";
            openFileDialog.Filter = "Emission Files (.emit)|*.emit|All Files (*.*)|*.*";
            openFileDialog.FilterIndex = 1;
            openFileDialog.Multiselect = false;

            // Call the ShowDialog method to show the dialog box.
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string line;
                B = new MySparse2DMatrix();
                emissionsSymbols = new Id2Str();
                var separator = '\t';

                System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog.FileName);
                emissionsRichTextBox.Text = "";

                if ((line = sr.ReadLine()) != null)
                {
                    if (line.Split(separator).Length == 1)
                        separator = ' ';
                    sr.DiscardBufferedData();
                    sr.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
                    sr.BaseStream.Position = 0;
                }

                while ((line = sr.ReadLine()) != null)
                {
                    emissionsRichTextBox.Text += line + "\n";

                    string[] stateValue = line.Split(separator);
                    if (stateValue.Length == 3)
                    {
                        int row = stateSymbols.setId(stateValue[0]);
                        int col = emissionsSymbols.setId(stateValue[1]);
                        B.setValue(row, col, Double.Parse(stateValue[2], CultureInfo.InvariantCulture));
                    }
                }
                sr.Close();
                if (B.Count > 0)
                {
                    buttonCreateHMM.Enabled = true;
                    openObservationsToolStripMenuItem.Enabled = true;
                }
                else
                {
                    buttonCreateHMM.Enabled = false;
                    openObservationsToolStripMenuItem.Enabled = false;
                    MessageBox.Show("Error! Parsed emissions matrix resulted empty. Check your input file please.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }