# Sinhala Sentence Embedding: A Two-Tiered Structure for Low-Resource
Languages

Gihan Weeraprameshwara Department of Computer Science & Engineering,
University of Moratuwa, Sri Lanka  Vihanga Jayawickrama Department of Computer
Science & Engineering, University of Moratuwa, Sri Lanka  Nisansa de Silva
Department of Computer Science & Engineering, University of Moratuwa, Sri
Lanka
Yudhanjaya Wijeratne LIRNEasia, Sri Lanka

###### Abstract

In the process of numerically modeling natural languages, developing language
embeddings is a vital step. However, it is challenging to develop functional
embeddings for resource-poor languages such as Sinhala, for which sufficiently
large corpora, effective language parsers, and any other required resources
are difficult to find. In such conditions, the exploitation of existing models
to come up with an efficacious embedding methodology to numerically represent
text could be quite fruitful. This paper explores the effectivity of several
one-tiered and two-tiered embedding architectures in representing Sinhala text
in the sentiment analysis domain. With our findings, the two-tiered embedding
architecture where the lower-tier consists of a word embedding and the upper-
tier consists of a sentence embedding has been proven to perform better than
one-tier word embeddings, by achieving a maximum F1 score of 88.04% in
contrast to the 83.76% achieved by word embedding models. Furthermore,
embeddings in the hyperbolic space are also developed and compared with
Euclidean embeddings in terms of performance. A sentiment data set consisting
of Facebook posts and associated reactions have been used for this research.
To effectively compare the performance of different embedding systems, the
same deep neural network structure has been trained on sentiment data with
each of the embedding systems used to encode the text associated.

##  1 Introduction

An effective numerical representation of the textual content is crucial for
natural language processing models, in order to understand the underlying
relational patterns among words and discover patterns in natural languages.
For resource-rich languages like English, numerous pre-trained models as well
as the required materials to develop an embedding system are readily
available. On the contrary, for resource-poor languages such as Sinhala,
neither of those options could be easily found de Silva (2019). Even the data
sets that are available for training often fail to meet adequate standards
Caswell et al. (2021). Thus, discovering a convenient methodology to develop
embeddings for text would be a great step forward in the NLP domain for the
Sinhala language.

Sinhala, also known as Sinhalese, is an Indo-Aryan language that is used
within Sri Lanka Kanduboda (2011). The primary user base of this language is
the Sinhalese ethnic group of the country. In total, 17 million people use
Sinhala as their first language while 2 million people use it as a second
language de Silva (2019). Furthermore, Sinhala is structurally different from
English, which uses a subject-verb-object structure as opposed to the subject-
object-verb structure used by Sinhala as shown in the figure 1 thus most of
the pre-trained embedding models for English may not be effective with
Sinhala.

Figure 1: SVO grammar structure of English and SOV grammar structure of
Sinhala

This study therefore is focused on discovering an effective embedding system
for Sinhala text that provides reasonable results when used in training deep
learning models. Sentiment analysis with Facebook data is utilized as the use
case for the study.

Upon considering common forms of vector presentations of textual content, bag
of words, word embedding, and sentence embedding are three of the leading
methodologies in the present. Word embeddings have been observed to surpass
the performance of bag of words for large enough data sets Rudkowsky et al.
(2018) because bag of words often met with various problems such as
disregarding the grammatical structure of the text, large vocabulary dimension
and sparse representation Le and Mikolov (2014); El-Din (2016). In order to
tackle the above challenges, word embeddings can be used. Since word
embeddings capture the similarities among ingrained sentiments in words and
represent them in the vector space, word embeddings tend to increase the
accuracy of classification models Goldberg (2016).

However, one of the major weaknesses of word embedding models is that they
fail to capture syntax and polysemy; i.e. the presence of multiple possible
meanings for a certain word or a phrase Mu et al. (2016). In order to overcome
these obstacles and also to achieve fine granularity in the embedding,
sentence embeddings are used. The idea is to test common Euclidean space word
embedding techniques such as fastText Bojanowski et al. (2017); Joulin et al.
(2016), Word2vec Mikolov et al. (2013), and GloVe Pennington et al. (2014)
with sentence embedding techniques. The pooling methods (i.e. max pooling, min
pooling and avg pooling) will be considered as the baseline methods for the
test. More advanced models such as sequence to sequence model (i.e. seq2seq
model) Sutskever et al. (2014) and the modified version of the sequence to
sequence model introduced by the work of Cho et al. (2014) with GRU Chung et
al. (2014) and LSTM Hochreiter and Schmidhuber (1997) recurrent neural network
units will be tested against the pooling means. Furthermore, the addition of
attention mechanism Vaswani et al. (2017) into the sequence to sequence model
will also be tested.

Most models created using word and sentence embeddings are based on the
Euclidean space. Though this vector space is commonly used, it poses
significant limitations when representing complex structures Nickel and Kiela
(2017). Using the hyperbolic space provides a plausible solution for such
instances. The hyperbolic space is a negatively-curved, non-Euclidean space.
It is advantageous for embedding trees as the circumference of a circle grows
exponentially with the radius. The usage of hyperbolic embedding is still a
novel research area as it was only introduced recently, through the work of
Nickel and Kiela (2017); Chamberlain et al. (2017); Sala et al. (2018). The
work of Lu et al. (2019, 2020) highlight the importance of using the
hyperbolic space to improve the quality of embeddings in a practical context
within the medical domain. However, research done on the applicability of
hyperbolic embeddings in different arenas is highly limited. Thus, the full
potential of the hyperbolic space is yet to be fully uncovered.

Through this paper, we are testing the effectiveness of a set of two-tiered
word representation models that include various word embeddings as the lower
tier and sentence embeddings as the upper tier will be compared.

##  2 Related Work

The sequence to sequence model introduced by the work of Sutskever et al.
(2014) is vital in this research as it is one of the core models in developing
sentence embedding. Though originally developed for translation purposes the
model has gone under multiple modifications depending on the context such as
description generation for images Karpathy and Fei-Fei (2015), phrase
representation Cho et al. (2014), attention models Vaswani et al. (2017) and
BERT models Devlin et al. (2018) thus proving the potential it holds in the
machine learning area.

The work of Nickel and Kiela (2017) introduces and explores the potential of
hyperbolic embedding by using an n-dimension Poincaré ball. The research work
compares the hyperbolic and Euclidean embeddings for a complex latent data
structure and comes to the conclusion that hyperbolic embedding surpasses the
Euclidean embedding in effectivity. Inspired by the above results, both
Leimeister and Wilson (2018) and Dhingra et al. (2018) have extended the
methodology introduced by Nickel and Kiela (2017). Leimeister and Wilson
(2018) have developed a hyperbolic word embedding using the skip-ngram
negative sampling architecture taken from Word2vec. In lower embedding
dimensions, the developed model performs better in comparison to its Euclidean
counterpart. The work of Dhingra et al. (2018) uses re-parameterization to
extend the Poincaré embedding, in order to learn the embedding of arbitrarily
parameterized objects. The framework thus created is used to develop word and
sentence embeddings. In our research, we will be following the footsteps of
the above papers.

When considering the usage of hyperbolic embeddings in a practical context,
the work of Lu et al. (2019, 2020) can be examined. The research by Lu et al.
(2019) improves the state-of-the-art model used to predict ICU (intensive care
unit) re-admissions and surpasses the accepted benchmark used to predict in-
hospital mortality using hyperbolic embedding of Electronic Health Records,
while the work of Lu et al. (2020) introduces a novel network embedding method
which is capable of maintaining the consistency of the node representation
across two views of networks, thus emphasizing the capabilities of hyperbolic
embeddings. To the best of our knowledge, hyperbolic embeddings have not been
previously applied to Sinhala content. Therefore, this research may reveal
novel insight regarding hyperbolic embedding and its effectivity in sentiment
analysis.

In the research work of Senevirathne et al. (2020), capsule-B model Zhao et
al. (2018) is crowned as the state-of-the-art model for the Sinhala sentiment
analysis. In this work, a set of deep learning models are tested for the
ability to predict the sentiment of Sinhala news comments. The GRU Chung et
al. (2014) model with a CNN Wang et al. (2016) layer which is used for the
testing of each embedding in this work is taken from the aforementioned
research. Furthermore, the work of Weeraprameshwara et al. (2022) has extended
the idea and tested the same set of deep learning models with the addition of
sentiment analysis models introduced in the work of Jayawickrama et al. (2021)
using the Facebook data set which is used in this research work. According to
their results, the 3 layer stacked BiLSTM model Zhou et al. (2019) outshines
as the state-of-the-art model.

##  3 Methodology

In order to test the feasibility of two-tiered word representation as a means
of representing Sinhala text in the sentiment analysis domain, a series of
experiments were conducted as described in the following subsections.

###  3.1 Data Set

The data set used for the project is extracted from the work of Wijeratne and
de Silva (2020), which contains 1,820,930 Facebook posts from 533 Facebook
pages popular in Sri Lanka over the time window of 2010 to 2020. The research
work has produced two cleaned corpora and a set of stop words for the given
context. The larger corpus among them consists of a total of 28 to 29 million
words. The data set covers a wide range of subjects such as politics, media,
and celebrities. Table 1 illustrates the fields taken from the data set for
the embedding development, model training and testing phases.

Field Name | Total Count | Percentage(%)
---|---|---
Likes | 312,282,979 | 93.58
Loves | 10,637,722 | 3.19
Wow | 1,633,255 | 0.49
Haha | 5,377,815 | 1.61
Sad | 2,611,908 | 0.78
Angry | 1,158,182 | 0.35
Thankful | 12,933 | 0.00
Table 1: The counts and percentages of the reactions in the Facebook data set

###  3.2 Preprocessing

Even though there are two preprocessed corpora introduced through the work of
Wijeratne and de Silva (2020), the raw data set was used for this research
with the objective of preprocessing it to suit our requirements. As such,
numerical content, URLs, email addresses, hashtags, words in other languages
except for Sinhala and English, and excessive spaces were removed from the
text. While the focus of this study is colloquial Sinhala, English is included
in the data set as the two languages are often codemixed in colloquial use.
Codemixing of Sinhala with other languages is much less in comparison.
Furthermore, stop words were removed from the text as well, as recommended by
Wijeratne and de Silva (2020). Posts with no textual content after thus
preprocessing as well as posts with no reaction annotations were also removed
as they yield no value in the annotation stage. The final preprocessed data
set consists of Sinhala, English, and Sinhala-English code mixed content,
adding up to a total of 542,871 Facebook posts consisting of 8,605,849 words.

###  3.3 Annotation

Since the procedure followed in the model development is supervised learning,
the data set needed to be annotated Schapire and Freund (2012). It is quite a
considerable challenge to obtain sufficiently large annotated data sets for
resource-poor languages like Sinhala thus Facebook data set is ideal for the
given scenario as the Facebook posts are pre-annotated by Facebook users using
Facebook reactions. Though this is not an expert annotation, it can be
considered as an effective means of community annotation as the collective
opinion of a large number of Facebook users is represented by the reaction
annotation Pool and Nissim (2016); Freeman et al. (2020); Graziani et al.
(2019); Jayawickrama et al. (2021).

A binary classification method which was introduced through the work of
Senevirathne et al. (2020) and further improved for Facebook data by
Weeraprameshwara et al. (2022) is used in this research as the annotation
schema which is illustrated in the figure 2. Here, the Facebook reactions are
divided into two classes; positive reactions and negative reactions. The
reactions love and wow are considered as positive reactions while sad and
angry are classified as negative reactions. The reactions like and thankful
have been excluded as they are outliers in the data set with respect to the
other reactions. The like is the de facto reaction given by the users and it
does not yield a valid sentiment. The thankful reaction has appeared in a
small time period making the presence insignificant compared to other
reactions (only 0.00003% of the total reaction count). The haha reaction is
also excluded due to the contradicting nature of its use cases Jayawickrama et
al. (2021). The care reaction is not included in this data set as it was first
introduced to the platform in 2020 Lyles (2020), after the creation of the
data set.

Figure 2: Reaction categorization for the annotation

###  3.4 Word Embeddings

The final vector representation of Facebook posts consists of two major
elements: word embeddings and sentence embeddings.

Word embeddings are used both as the first tier of the two-tiered embedding
systems and as the basic one-tiered embedding systems used in the form of a
benchmark against which the performance of two-tiered embedding systems would
be compared. The performance of both Euclidean and hyperbolic word embeddings
has been thus evaluated in this research.

####  3.4.1 Euclidean Word Embeddings

For the purpose of representing words in the Euclidean space; fastText,
Word2vec, and GloVe word embedding techniques were utilized. Word vectors
consisting of 200 dimensions were created using each of the aforementioned
models and a window size of 40 was picked based on the work of Senevirathne et
al. (2020); Weeraprameshwara et al. (2022) which precedes this research.

####  3.4.2 Hyperbolic Embeddings

The hyperbolic space exhibits different mathematical properties in comparison
to the Euclidean space. Due to its inherent properties, the Euclidean space
struggles to model a latent hierarchy. This issue could be addressed by
mapping the embedding into a higher dimension Nickel and Kiela (2017).
However, this may lead to sparse data mapping, causing the curse of
dimensionality to affect the performance. This may induce adverse effects such
as causing the machine learning model to overfit by the data and using a high
memory capacity for computations and storage.

The hyperbolic space has caught the attention of researchers as a plausible
solution to such issues encountered in using the Euclidean space for modeling
complex structures. The unique feature of this mathematical model is that the
space covered by an n-ball in an n-dimensional hyperbolic space increases
exponentially with the radius. In contrast to the Euclidean space where the
space covered by an n-ball remains restricted by the $n^{th}$ power of the
radius, the hyperbolic space could easily handle complex models such as tree-
like structures within a limited dimensionality.

The distance ($D$) between two vectors ($i$ and $j$) in the hyperbolic space
can be calculated as shown in equation 1.

$D_{(i,j)}=\operatorname{arcCosh}{(1+\frac{2\lvert\lvert
i-j\rvert\rvert^{2}}{(1-\lvert\lvert i\rvert\rvert^{2})(1-\lvert\lvert
j\rvert\rvert^{2})})}$ (1)

Since both the circumference and the area of a hyperbolic circle grow
exponentially with the radius, the hyperbolic space has the capability to
effectively store a complex latent hierarchy of data using a much lower number
of dimensions than the Euclidean space would require to store the exact same
structure.

In order to create hyperbolic word embeddings, the data set should be reformed
in such a manner that the syntactic structure of data is highlighted. However,
an adequate language parser for Sinhala does not currently exist de Silva
(2019). Using parsers dedicated to the English language is also unfitting
since the underlying grammatical structure of Sinhala is significantly
different from that of English. Furthermore, for codemixed colloquial data
present in this data set, grammatical structures of both Sinhala and English
languages would have to be taken into consideration. Therefore, the parsing
mechanism shown in figure3 is used to generate word tokens. A total of 8605849
tokens have been thus generated.

Figure 3: Examples of parsing mechanism used for the hyperbolic embeddings
where each word is matched to the sentence

The two-dimensional illustration of the Poincaré ball after training with the
Facebook data set is shown in the figure 4. Each node represents a word in the
figure and each edge represents the connection between words. Here for the
illustration purposes, only a thousand nodes are shown and the dimension is
projected from 200 to 2.

Figure 4: Poincaré word embedding done on Facebook data set

The clustering of semantically related words in the Poincaré embedding is
shown in the figure 5. A set of words related to cricket sport is clustered in
the top left corner while a set of Sinhala words related to Christianity is
clustered in the bottom left. A cluster which represents news-related terms is
formed in the bottom right corner. With this evidence, we can safely assume
that the hyperbolic space has the capability to store a complex latent
hierarchy such as the semantic relation of words.

Figure 5: Word clustering in the Poincaré embedding. The meaning of the
Sinhala words are given in the brackets

###  3.5 Sentence Embeddings

Sentence embeddings are used as the second tier of the two-tiered embedding
models. Basic pooling methods as well as the sequence to sequence model are
used to generate sentence embeddings by using the word embedding of each word
in a sentence. For both Euclidean space and hyperbolic space embeddings, the
sentence embeddings are generated in a similar fashion as described below.

####  3.5.1 Pooling

Sentence embeddings have been created with three different pooling mechanisms
for each of fastText, Word2vec, GloVe, and hyperbolic word embeddings; namely,
max pooling, min pooling, and avg pooling. Pooling embeddings will be
considered as baseline sentence embeddings against which the performance of
the sequence to sequence model is compared.

####  3.5.2 Sequence to Sequence Model

This sentence embedding mechanism follows the sequence to sequence model
introduced through the work of Sutskever et al. (2014), referred to as the
seq2seq model from here onwards.

The data set is randomly shuffled and a subset consisting of 400,000 data rows
is used for training the encoder, decoder units.

In the original model, the encoder accepts a set of vectors which consists of
the word embedding of each word in a sentence followed by the $<EOS>$ token as
input and returns a context vector as the output. In order to train the model,
the decoder is fed with the context vector from the encoder, with the
objective of getting the $<SOS>$ token followed by the translated sentence as
the final output. For our research, the output expected from the decoder is
the same sentence that has been inputted into the encoder. For a given
sentence, the word embedding of each word in the sentence is inputted into the
Recurrent Neural Network encoder, which has a hidden layer similar in
dimensions to the word embedding. Since the expected output from the RNN
decoder is also the same sentence, the context vector (output of the encoder)
can be considered as the sentence embedding that we are seeking.

Different sentence embeddings are thus generated using both Euclidean and
hyperbolic word embeddings as inputs to the seq2seq model. For each type of
word embeddings, the RNNs inside the encoder and decoder are also modified to
generate different sentence embeddings. Here, GRU Chung et al. (2014), LSTM
Hochreiter and Schmidhuber (1997), and simple RNN models are used. The
architecture of the GRU seq2seq model has been inspired by the model
introduced through the work of Cho et al. (2014).

Furthermore, two different decoder structures have been used to train the
seq2seq model. A simple decoder which functions as explained above and a
decoder with the attention mechanism introduced in the work of Vaswani et al.
(2017) are thus utilized. Both models use a teacher forcing value of 0.5 with
the objective of performing better at the prediction task Lamb et al. (2016).

The squared L2 norm between the predicted word embedding and the actual word
embedding is used as the loss function for Euclidean embeddings. Equations 2
shows embedding value of the $i$th sentence which is calculated by summing up
all the word embeddings in the predicted sequence of word embeddings. The
symbol $n$ is the length of the longest sentence which may vary for the
selected data set. $WE_{k}$ is the value of each dimension in the 200
dimension word embedding. Equation 3 calculates the value of $i$th true word
embedding sequence ($TV_{i}$) which is the summation of the word embeddings of
True word sequence. Then in the equation 4, the squared L2 norm ($Err$) is
calculated. $n$ denotes the number of data items used. The procedure follows
for both Euclidean and hyperbolic space embeddings.

$PV_{i}={\sum_{j=1}^{n}\sum_{k=1}^{200}WE_{K}}\\\ $ (2)

$TV_{i}={\sum_{j=1}^{n}\sum_{k=1}^{200}WE_{K}}\\\ $ (3)
$Err=(1/n){\sum_{i=1}^{n}(PV_{i}-TV_{i})^{2}}$ (4)

###  3.6 Testing

To the extent of our knowledge, there does not exist a well known or effective
benchmark to test the performance of Sinhala sentence embeddings. Therefore,
the GRU RNN model with a CNN layer introduced by the work of Chung et al.
(2014); Senevirathne et al. (2020) is used to test each embedding. The
function of this model is to understand the sentimental reactions of Facebook
users to Facebook posts and thus classify each post as either positive or
negative based on its prediction of the sentimental reaction of users to that
post. The classification of the Facebook posts was done as explained in the
section 3.3.

As mentioned above since the scarcity of a large enough data set for Sinhala
language to train deep learning models, the same Facebook data set is used for
the model training purpose. However, a different set of Facebook posts are
used in order to avoid repetition of the data set and a total of 200,000 posts
were used for the training purpose. The holdout method was used with data set
splits into the 8:1:1 ratio for train, validate, and test sets. Tests were run
multiple times and the average performance measures were recorded.

##  4 Results

The results obtained by training the models only using word embeddings are
displayed in table 2. Here, the row fastText(Sinhala News Comments) taken from
the work of Weeraprameshwara et al. (2022) is used as a benchmark against
which the performance measures of the other word embeddings are compared.
There, the Facebook data set was embedded using the fastText word embeddings
trained with the Sinhala News Comments data set introduced through the work of
Senevirathne et al. (2020), while the latter rows display the results of
embedding the Facebook data set with word embeddings trained with the Facebook
data set itself.

As the table portrays, using the Facebook data set containing 542,871
preprocessed Facebook posts, which is much larger in size than the Sinhala
News Comments data set with 15,000 Sinhala News comments, to develop the word
embeddings has resulted in a comparatively higher F1 score.

Word Embedding | Performance Measures
---|---
Accuracy | Precision | Recall | F1
fastText (Sinhala News comments) Weeraprameshwara et al. (2022) | 81.17 | 81.17 | 81.57 | 81.37
Word2vec | 83.47 | 83.65 | 83.47 | 83.56
GloVe | 82.09 | 81.91 | 82.65 | 82.28
fastText | 83.76 | 83.76 | 83.76 | 83.76
Hyperbolic | 82.78 | 82.11 | 83.58 | 82.84
Table 2: Word Embedding results

The results of each embedding in the two-tiered structure are shown in table
3. The first column presents the word embedding method used while the second
column depicts the sentence embedding method utilized and the rest of the
columns are used to present the performance measures. The best performance
measures from each word embedding category are highlighted.

Embedding level | Performance Measures
---|---
Word | Sentence |  Accuracy |  Precision |  Recall |  F1 Score
Word2vec | Max Pooling |  77.23 |  80.06 |  94.59 |  86.72
Min Pooling |  77.29 |  81.55 |  92.41 |  86.64
Avg Pooling |  77.44 |  81.43 |  93.41 |  87.01
Seq2seq GRU |  75.86 |  76.74 |  97.14 |  85.75
Seq2seq GRU with attention |  79.12 |  79.72 |  96.45 |  87.29
Seq2seq LSTM |  75.97 |  76.17 |  98.76 |  86.01
Seq2seq LSTM with attention |  77.42 |  77.86 |  97.36 |  86.53
GloVe | Max Pooling |  75.63 |  77.74 |  96.79 |  86.22
Min Pooling |  75.34 |  78.68 |  94.81 |  85.99
Avg Pooling |  76.11 |  76.90 |  97.38 |  85.93
Seq2seq GRU |  74.23 |  74.15 |  100.00 |  85.16
Seq2seq GRU with attention |  74.23 |  74.09 |  100.00 |  85.12
Seq2seq LSTM |  74.23 |  74.15 |  100.00 |  85.16
Seq2seq LSTM with attention |  74.23 |  74.09 |  100.00 |  85.12
fastText | Max Pooling |  79.93 |  81.23 |  94.78 |  87.49
Min Pooling |  79.80 |  82.49 |  93.22 |  87.52
Avg Pooling |  80.86 |  82.55 |  94.07 |  87.93
Seq2seq GRU |  78.12 |  80.90 |  92.33 |  86.23
Seq2seq GRU with attention |  80.61 |  81.31 |  96.00 |  88.04
Seq2seq LSTM |  79.00 |  82.12 |  91.59 |  86.60
Seq2seq LSTM with attention |  80.31 |  80.06 |  96.98 |  87.72
Hyperbolic | Max Pooling |  76.71 |  77.54 |  95.95 |  85.77
Min Pooling |  76.11 |  77.68 |  94.11 |  85.11
Avg Pooling |  77.00 |  77.31 |  95.56 |  85.47
Seq2seq GRU |  76.38 |  77.09 |  97.57 |  86.13
Seq2seq GRU with attention |  77.31 |  78.31 |  96.70 |  86.54
Seq2seq LSTM |  76.48 |  77.91 |  95.49 |  85.81
Seq2seq LSTM with attention |  77.19 |  78.22 |  96.24 |  86.30
Table 3: Performance measures of each embedding

The best F1 score is produced by the two-tiered embedding which uses fastText
as the word embedding and the seq2seq model with GRU RNNs and attention layer
as the sentence embedding while the second-best F1 is scored by the fastText
embedding with average pooling. For each of the sentence embedding methods,
the highest F1 score is produced by pairing with fastText word embeddings.
fastText embeddings have resulted in a better F1 score in the one-tiered
embeddings as well. Thus, we can conclude that fastText is the word embedding
schema which provides the best performance in this context.

Upon taking the word embedding categories into consideration, Word2vec
embeddings provide the second-best results, with performance scores slightly
lower than those of fastText. The ranking of F1 scores achieved by hyperbolic
and GloVe embeddings seem to be highly dependent on the type of sentence
embedding used. However, the best F1 score obtained by hyperbolic embeddings,
which was by pairing with the seq2seq model with GRU encoder and decoder units
including an attention layer, is higher than the best F1 score GloVe
embeddings have achieved upon pairing with max pooling sentence embeddings. It
should be noted that the structure of data utilized here may not be optimal
for hyperbolic embeddings.

In sentence embeddings, the performance of seq2seq model with GRU encoder,
decoder units and an attention layer tend to surpass other sentence embedding
models except when the word embedding utilized is GloVe. Nonetheless,
stripping off the attention layer brings the performance of the seq2seq model
with LSTM encoders and decoders to a level higher than that obtained with GRU
encoder and decoder units, with the exception of the case where hyperbolic
word embeddings are utilized.

Furthermore, there is a clear improvement in the performance scores of the
seq2seq model when the attention layer is applied to the decoder. However,
when the attention layer is not applied, pooling embeddings manage to perform
better than seq2seq models except when hyperbolic word embeddings are
utilized. The reason for this exception could be that the Euclidean pooling
mechanisms used may not be the best fit for hyperbolic embeddings.

##  5 Conclusion

Comparing tables 2 and 3 makes it evident that there is a clear improvement in
performance when two-tiered embedding systems are used, in contrast to simply
using a single tier of word embeddings. The possibility of sentence embeddings
used in two-tiered embedding systems to enable the models to consider the
syntax of sentences could be the reason for this improvement. When word
embeddings of Sinhala Facebook posts are directly fed to a sentiment analysis
model, the model is likely to see the Facebook posts as merely an unorganized
set of words instead of an organized set of sentences.

In addition, the results displayed in table 3 exhibit the use of the two-
tiered embedding system that combines fastText word embeddings and seq2seq
sentence embeddings with GRU encoder and decoder units as well as an attention
layer has given rise to the best performance measures. Although Word2vec
embeddings follow closely behind in performance, they have failed to surpass
fastText, possibly due to the inability of the embedding system to consider
the internal structure of words, which the fastText embedding system by nature
is capable of Bojanowski et al. (2017); Joulin et al. (2016).

Though the hyperbolic space has an advantage over the Euclidean space due to
its ability to effectively represent complex hierarchical data structures
Nickel and Kiela (2017), fastText and Word2vec embeddings have outperformed
hyperbolic embeddings in this research. The reason for this could be the lack
of potent parsing tools for the Sinhala language de Silva (2019). To obtain
the optimum performance from hyperbolic embeddings, an effective hierarchical
structure such as sentence structures identified via parsing is required. The
simple $[word,sentence]$ relation structure used in this research may not be
sufficient for this. Furthermore, the pooling techniques also fail to be on
par with the seq2seq model, possibly due to the fact that the vectors
generated by applying Euclidean pooling mechanisms on hyperbolic embeddings do
not always fall within the space of the Poincaré ball.

Another noteworthy fact is that the GloVe embeddings tend to underperform in
comparison to the other word embeddings models used in this research. Unlike
resource-rich languages such as English, no pre-trained GloVe models exist for
the Sinhala language. This could hinder the ability of GloVe embeddings to
achieve their full potential.

Thus, it can be concluded that though a robust embedding model for Sinhala
that is applicable across all domains may not be currently available, it could
be possible to develop an effective embedding system that would at least be
potent within the domain of the training data set by applying a two-tiered
embedding model such as the seq2seq sentence embeddings with GRU encoders and
decoders stacked on top of fastText word embeddings on a sufficiently large
data set.

##  6 Future Work

This research is related to the work of Jayawickrama et al. (2021) and as the
final goal, a Facebook reaction prediction tool for colloquial Sinhala text
will be developed and the word representations developed in this project will
be used for that tool.

The data set contains both Sinhala and English text since our aim is to
develop a word representation for colloquial Sinhala text which consists of
English and Sinhala code-mixed content. However, a pure Sinhala embedding can
be generated in the future.

Furthermore, Poincaré embeddings could be developed for Sinhala text with the
use of a proper parser to identify sentence structures though developing a
reasonable parser for colloquial text will be a challenge.

Though this research only considers sentiment analysis for the Sinhala
language, the applicability of the two-tiered embedding systems discussed in
other areas of natural language processing as well as for other resource-poor
languages could be tested as well.

## References

  * Bojanowski et al. (2017) Piotr Bojanowski, Edouard Grave, Armand Joulin, and Tomas Mikolov. 2017.  Enriching word vectors with subword information.  _Transactions of the Association for Computational Linguistics_ , 5:135–146.
  * Caswell et al. (2021) Isaac Caswell, Julia Kreutzer, Lisa Wang, Ahsan Wahab, Daan van Esch, Nasanbayar Ulzii-Orshikh, Allahsera Tapo, Nishant Subramani, Artem Sokolov, Claytone Sikasote, et al. 2021.  Quality at a glance: An audit of web-crawled multilingual datasets.  _arXiv preprint arXiv:2103.12028_.
  * Chamberlain et al. (2017) Benjamin Paul Chamberlain, James Clough, and Marc Peter Deisenroth. 2017.  Neural embeddings of graphs in hyperbolic space.  _arXiv preprint arXiv:1705.10359_.
  * Cho et al. (2014) Kyunghyun Cho, Bart Van Merriënboer, Caglar Gulcehre, Dzmitry Bahdanau, Fethi Bougares, Holger Schwenk, and Yoshua Bengio. 2014.  Learning phrase representations using rnn encoder-decoder for statistical machine translation.  _arXiv preprint arXiv:1406.1078_.
  * Chung et al. (2014) Junyoung Chung, Caglar Gulcehre, KyungHyun Cho, and Yoshua Bengio. 2014.  Empirical evaluation of gated recurrent neural networks on sequence modeling.  _arXiv preprint arXiv:1412.3555_.
  * de Silva (2019) Nisansa de Silva. 2019.  Survey on publicly available sinhala natural language processing tools and research.  _arXiv preprint arXiv:1906.02358_.
  * Devlin et al. (2018) Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2018.  Bert: Pre-training of deep bidirectional transformers for language understanding.  _arXiv preprint arXiv:1810.04805_.
  * Dhingra et al. (2018) Bhuwan Dhingra, Christopher J Shallue, Mohammad Norouzi, Andrew M Dai, and George E Dahl. 2018.  Embedding text in hyperbolic spaces.  _arXiv preprint arXiv:1806.04313_.
  * El-Din (2016) Doaa Mohey El-Din. 2016.  Enhancement bag-of-words model for solving the challenges of sentiment analysis.  _International Journal of Advanced Computer Science and Applications_ , 7(1).
  * Freeman et al. (2020) Cole Freeman, Hamed Alhoori, and Murtuza Shahzad. 2020.  Measuring the diversity of facebook reactions to research.  _Proceedings of the ACM on Human-Computer Interaction_ , 4(GROUP):1–17.
  * Goldberg (2016) Yoav Goldberg. 2016.  A primer on neural network models for natural language processing.  _Journal of Artificial Intelligence Research_ , 57:345–420.
  * Graziani et al. (2019) Lisa Graziani, Stefano Melacci, and Marco Gori. 2019.  Jointly learning to detect emotions and predict facebook reactions.  In _International Conference on Artificial Neural Networks_ , pages 185–197. Springer.
  * Hochreiter and Schmidhuber (1997) Sepp Hochreiter and Jürgen Schmidhuber. 1997.  Long short-term memory.  _Neural computation_ , 9(8):1735–1780.
  * Jayawickrama et al. (2021) Vihanga Jayawickrama, Gihan Weeraprameshwara, Nisansa de Silva, and Yudhanjaya Wijeratne. 2021.  Seeking sinhala sentiment: Predicting facebook reactions of sinhala posts.  In _2021 21st International Conference on Advances in ICT for Emerging Regions (ICter)_ , pages 177–182. IEEE.
  * Joulin et al. (2016) Armand Joulin, Edouard Grave, Piotr Bojanowski, and Tomas Mikolov. 2016.  Bag of tricks for efficient text classification.  _arXiv preprint arXiv:1607.01759_.
  * Kanduboda (2011) AB Kanduboda. 2011.  The role of animacy in determining noun phrase cases in the sinhalese and japanese languages.  _Science of words_ , 24:5–20.
  * Karpathy and Fei-Fei (2015) Andrej Karpathy and Li Fei-Fei. 2015.  Deep visual-semantic alignments for generating image descriptions.  In _Proceedings of the IEEE conference on computer vision and pattern recognition_ , pages 3128–3137.
  * Lamb et al. (2016) Alex M Lamb, Anirudh Goyal Alias Parth Goyal, Ying Zhang, Saizheng Zhang, Aaron C Courville, and Yoshua Bengio. 2016.  Professor forcing: A new algorithm for training recurrent networks.  In _Advances in neural information processing systems_ , pages 4601–4609.
  * Le and Mikolov (2014) Quoc Le and Tomas Mikolov. 2014.  Distributed representations of sentences and documents.  In _International conference on machine learning_ , pages 1188–1196. PMLR.
  * Leimeister and Wilson (2018) Matthias Leimeister and Benjamin J Wilson. 2018.  Skip-gram word embeddings in hyperbolic space.  _arXiv preprint arXiv:1809.01498_.
  * Lu et al. (2020) Qiuhao Lu, Nisansa de Silva, Dejing Dou, Thien Huu Nguyen, Prithviraj Sen, Berthold Reinwald, and Yunyao Li. 2020.  Exploiting node content for multiview graph convolutional network and adversarial regularization.  In _Proceedings of the 28th International Conference on Computational Linguistics_ , pages 545–555.
  * Lu et al. (2019) Qiuhao Lu, Nisansa de Silva, Sabin Kafle, Jiazhen Cao, Dejing Dou, Thien Huu Nguyen, Prithviraj Sen, Brent Hailpern, Berthold Reinwald, and Yunyao Li. 2019\.  Learning electronic health records through hyperbolic embedding of medical ontologies.  In _Proceedings of the 10th ACM International Conference on Bioinformatics, Computational Biology and Health Informatics_ , pages 338–346.
  * Lyles (2020) Taylor Lyles. 2020.  Facebook adds a ’care’ reaction to the like button.
  * Mikolov et al. (2013) Tomas Mikolov, Kai Chen, Greg Corrado, and Jeffrey Dean. 2013.  Efficient estimation of word representations in vector space.  _arXiv preprint arXiv:1301.3781_.
  * Mu et al. (2016) Jiaqi Mu, Suma Bhat, and Pramod Viswanath. 2016.  Geometry of polysemy.  _arXiv preprint arXiv:1610.07569_.
  * Nickel and Kiela (2017) Maximillian Nickel and Douwe Kiela. 2017.  Poincaré embeddings for learning hierarchical representations.  _Advances in neural information processing systems_ , 30:6338–6347.
  * Pennington et al. (2014) Jeffrey Pennington, Richard Socher, and Christopher D Manning. 2014.  Glove: Global vectors for word representation.  In _Proceedings of the 2014 conference on empirical methods in natural language processing (EMNLP)_ , pages 1532–1543.
  * Pool and Nissim (2016) Chris Pool and Malvina Nissim. 2016.  Distant supervision for emotion detection using facebook reactions.  _arXiv preprint arXiv:1611.02988_.
  * Rudkowsky et al. (2018) Elena Rudkowsky, Martin Haselmayer, Matthias Wastian, Marcelo Jenny, Štefan Emrich, and Michael Sedlmair. 2018.  More than bags of words: Sentiment analysis with word embeddings.  _Communication Methods and Measures_ , 12(2-3):140–157.
  * Sala et al. (2018) Frederic Sala, Chris De Sa, Albert Gu, and Christopher Ré. 2018.  Representation tradeoffs for hyperbolic embeddings.  In _International conference on machine learning_ , pages 4460–4469. PMLR.
  * Schapire and Freund (2012) Robert E Schapire and Yoav Freund. 2012.  Foundations of machine learning.  _Mit Press_.
  * Senevirathne et al. (2020) Lahiru Senevirathne, Piyumal Demotte, Binod Karunanayake, Udyogi Munasinghe, and Surangika Ranathunga. 2020.  Sentiment analysis for sinhala language using deep learning techniques.  _arXiv preprint arXiv:2011.07280_.
  * Sutskever et al. (2014) Ilya Sutskever, Oriol Vinyals, and Quoc V Le. 2014.  Sequence to sequence learning with neural networks.  In _Advances in neural information processing systems_ , pages 3104–3112.
  * Vaswani et al. (2017) Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin. 2017.  Attention is all you need.  In _Advances in neural information processing systems_ , pages 5998–6008.
  * Wang et al. (2016) Xingyou Wang, Weijie Jiang, and Zhiyong Luo. 2016.  Combination of convolutional and recurrent neural network for sentiment analysis of short texts.  In _Proceedings of COLING 2016, the 26th international conference on computational linguistics: Technical papers_ , pages 2428–2437.
  * Weeraprameshwara et al. (2022) Gihan Weeraprameshwara, Vihanga Jayawickrama, Nisansa de Silva, and Yudhanjaya Wijeratne. 2022.  Sentiment analysis with deep learning models: a comparative study on a decade of sinhala language facebook data.  In _2022 The 3rd International Conference on Artificial Intelligence in Electronics Engineering_ , pages 16–22.
  * Wijeratne and de Silva (2020) Yudhanjaya Wijeratne and Nisansa de Silva. 2020.  Sinhala language corpora and stopwords from a decade of sri lankan facebook.  _arXiv preprint arXiv:2007.07884_.
  * Zhao et al. (2018) Wei Zhao, Jianbo Ye, Min Yang, Zeyang Lei, Suofei Zhang, and Zhou Zhao. 2018.  Investigating capsule networks with dynamic routing for text classification.  _arXiv preprint arXiv:1804.00538_.
  * Zhou et al. (2019) Junhao Zhou, Yue Lu, Hong-Ning Dai, Hao Wang, and Hong Xiao. 2019.  Sentiment analysis of chinese microblog based on stacked bidirectional lstm.  _IEEE Access_ , 7:38856–38866.


acoustics actuators addictions adhesives admsci adolescents aerobiology
aerospace agriculture agriengineering agrochemicals agronomy ai air algorithms
allergies alloys amh analytica analytics anatomia anesthres animals
antibiotics antibodies antioxidants applbiosci appliedchem appliedmath
applmech applmicrobiol applnano applsci aquacj architecture arm arthropoda
arts asc asi astronomy atmosphere atoms audiolres automation axioms bacteria
batteries bdcc behavsci beverages biochem bioengineering biologics biology
biomass biomechanics biomed biomedicines biomedinformatics biomimetics
biomolecules biophysica biosensors biotech birds blockchains bloods blsf
brainsci breath buildings businesses cancers carbon cardiogenetics catalysts
cells ceramics challenges chemengineering chemistry chemosensors chemproc
children chips cimb civileng cleantechnol climate clinpract clockssleep cmd
coasts coatings colloids colorants commodities compounds computation computers
condensedmatter conservation constrmater cosmetics covid crops cryo
cryptography crystals csmf ctn curroncol cyber dairy data ddc dentistry
dermato dermatopathology designs devices diabetology diagnostics dietetics
digital disabilities diseases diversity dna drones dynamics earth ebj ecm
ecologies econometrics economies education ejihpe electricity electrochem
electronicmat electronics encyclopedia endocrines energies eng engproc
entomology entropy environments environsciproc epidemiologia epigenomes est
fermentation fibers fintech fire fishes fluids foods forecasting forensicsci
forests fossstud foundations fractalfract fuels future futureinternet
futurepharmacol futurephys futuretransp galaxies games gases gastroent
gastrointestdisord gastronomy gels genealogy genes geographies geohazards
geomatics geometry geosciences geotechnics geriatrics grasses gucdd hardware
hazardousmatters healthcare hearts hemato hematolrep heritage higheredu
highthroughput histories horticulturae hospitals humanities humans
hydrobiology hydrogen hydrology hygiene glacies idr ijerph ijfs ijgi ijmd ijms
ijns ijpb ijt ijtm ijtpp ime immuno informatics information infrastructures
inorganics insects instruments inventions iot j jal jcdd jcm jcp jcs jcto jdad
jdb jeta jfb jfmk jimaging jintelligence jlpea jmahp jmmp jmp jmse jne jnt jof
joitmc joma jor journalmedia jox jpbi jpm jrfm jsan jtaer jvd jzbg kidneydial
kinasesphosphatases knowledge laboratories land languages laws life limnolrev
lipidology liquids literature livers logics logistics lubricants lymphatics
machines macromol magnetism magnetochemistry make marinedrugs materials
materproc mathematics mca measurements medicina medicines medsci membranes
merits metabolites metals meteorology methane metrology micro microarrays
microbiolres micromachines microorganisms microplastics minerals mining
modelling molbank molecules mps msf mti muscles nanoenergyadv
nanomanufacturing nanomaterials ncrna ndt network neuroglia neurolint neurosci
nitrogen notspecified nursrep nutraceuticals nutrients obesities oceans ohbm
onco optics oral organics organoids osteology oxygen parasites parasitologia
particles pathogens pathophysiology pediatrrep pets pharmaceuticals
pharmaceutics pharmacoepidemiology pharmacy philosophies photochem photonics
phycology physchem physics physiologia plants plasma platforms pollutants
polymers polysaccharides poultry powders preprints proceedings processes
prosthesis proteomes psf psycholint psychiatryint psychoactives publications
purification quantumrep quaternary qubs radiation reactions realestate
receptors recycling regeneration religions remotesensing reports reprodmed
resources rheumato risks robotics ruminants safety sci scipharm sclerosis
seeds sensors separations sexes signals sinusitis siuj skins smartcities sna
societies socsci software soilsystems solar solids spectroscj sports standards
stats std stresses surfaces surgeries suschem sustainability symmetry synbio
systems targets taxonomy technologies telecom test textiles thalassrep
therapeutics thermo timespace tomography tourismhosp toxics toxins
transplantology transportation traumacare traumas tropicalmed universe
urbansci uro vaccines vehicles venereology vetsci vibration virtualworlds
viruses vision waste water wem wevj wind women world youth zoonoticdis


# The algorithmicx package111This is the documentation for the version 1.2 of
the package. This package is released under LPPL.

Szász János
<EMAIL_ADDRESS>
###### Abstract

The algorithmicx package provides many possibilities to customize the layout
of algorithms. You can use one of the predefined layouts (pseudocode, pascal
and c and others), with or without modifications, or you can define a
completely new layout for your specific needs.

###### Contents

  1. 1 Introduction
  2. 2 General informations
    1. 2.1 The package
    2. 2.2 The algorithmic block
    3. 2.3 Simple lines
    4. 2.4 Placing comments in sources
    5. 2.5 Labels and references
    6. 2.6 Breaking up long algorithms
    7. 2.7 Multiple layouts in the same document
  3. 3 The predefined layouts
    1. 3.1 The algpseudocode layout
      1. 3.1.1 The for block
      2. 3.1.2 The while block
      3. 3.1.3 The repeat block
      4. 3.1.4 The if block
      5. 3.1.5 The procedure block
      6. 3.1.6 The function block
      7. 3.1.7 The loop block
      8. 3.1.8 Other commands in this layout
      9. 3.1.9 Package options
      10. 3.1.10 Changing command names
    2. 3.2 The algpascal layout
      1. 3.2.1 The begin … end block
      2. 3.2.2 The for loop
      3. 3.2.3 The while loop
      4. 3.2.4 The repeat… until block
      5. 3.2.5 The if command
      6. 3.2.6 The procedure command
      7. 3.2.7 The function command
    3. 3.3 The algc layout
  4. 4 Custom algorithmic blocks
    1. 4.1 Blocks and loops
    2. 4.2 Defining blocks
    3. 4.3 Defining loops
    4. 4.4 Continuing blocks and loops
    5. 4.5 Even more customisation
    6. 4.6 Parameters, custom text
    7. 4.7 The ONE defining macro
  5. 5 Examples
    1. 5.1 A full example using algpseudocode
    2. 5.2 Breaking up an algorithm
    3. 5.3 Using multiple layouts
  6. 6 Bugs

##  1 Introduction

All this has begun in my last year at the university. The only thing that I
knew of LaTeX was that it exists, and that it is “good”. I started using it,
but I needed to typeset some algorithms. So I begun searching for a good
algorithmic style, and I have found the algorithmic package. It was a great
joy for me, and I started to use it… Well… Everything went nice, until I
needed some block that wasn’t defined in there. What to do? I was no LaTeX
guru, in fact I only knew the few basic macros. But there was no other way, so
I opened the style file, and I copied one existing block, renamed a few
things, and voilà! This (and some other small changes) where enough for me…

One year later — for one good soul — I had to make some really big changes on
the style. And there on a sunny day came the idea. What if I would write some
macros to let others create blocks automatically? And so I did! Since then the
style was completely rewritten… several times…

I had fun writing it, may you have fun using it! I am still no LaTeX guru, so
if you are, and you find something really ugly in the style, please mail me!
All ideas for improvements are welcome!

Thanks go to Benedek Zsuzsa, Ionescu Clara, Szőcs Zoltán, Cseke Botond, Kanoc
and many-many others. Without them I would have never started or continued
algorithmicx.

##  2 General informations

###  2.1 The package

The package algorithmicx itself doesn’t define any algorithmic commands, but
gives a set of macros to define such a command set. You may use only
algorithmicx, and define the commands yourself, or you may use one of the
predefined command sets.

These predefined command sets (layouts) are:

algpseudocode

has the same look222almost :-) as the one defined in the algorithmic package.
The main difference is that while the algorithmic package doesn’t allow you to
modify predefined structures, or to create new ones, the algorithmicx package
gives you full control over the definitions (ok, there are some limitations —
you can not send mail with a, say, `\For` command).

algcompatible

is fully compatible with the algorithmic package, it should be used only in
old documents.

algpascal

aims to create a formatted pascal program, it performs automatic indentation
(!), so you can transform a pascal program into an algpascal algorithm
description with some basic substitution rules.

algc

– yeah, just like the algpascal… but for c… This layout is incomplete.

To create floating algorithms you will need `algorithm.sty`. This file may or
may not be included in the algorithmicx package. You can find it on CTAN, in
the algorithmic package.

###  2.2 The algorithmic block

Each algorithm begins with the `\begin{algorithmic}[lines]` command, the
optional `lines` controls the line numbering: $0$ means no line numbering, $1$
means number every line, and $n$ means number lines $n$, $2n$, $3n$… until the
`\end{algorithmic}` command, witch ends the algorithm.

###  2.3 Simple lines

A simple line of text is beginned with `\State`. This macro marks the begin of
every line. You don’t need to use `\State` before a command defined in the
package, since these commands use automatically a new line.

To obtain a line that is not numbered, and not counted when counting the lines
for line numbering (in case you choose to number lines), use the `Statex`
macro. This macro jumps into a new line, the line gets no number, and any
label will point to the previous numbered line.

We will call stataments the lines starting with `\State`. The `\Statex` lines
are not stataments.

###  2.4 Placing comments in sources

Comments may be placed everywhere in the source using the `\Comment` macro
(there are no limitations like those in the algorithmic package), feel the
freedom! If you would like to change the form in witch comments are displayed,
just change the `\algorithmiccomment` macro:

    \algrenewcommand{\algorithmiccomment}[1]{\hskip3em$\rightarrow$ #1}

will result:

1:$x\leftarrow x+1$ $\rightarrow$ Here is the new comment

###  2.5 Labels and references

Use the `\label` macro, as usual to label a line. When you use `\ref` to
reference the line, the `\ref` will be subtitued with the corresponding line
number. When using the algorithmicx package togedher with the algorithm
package, then you can label both the algorithm and the line, and use the
`\algref` macro to reference a given line from a given algorithm:

    \algref{<algorithm>}{<line>}

    The \textbf{while} in algorithm
    \ref{euclid} ends in line
    \ref{euclidendwhile}, so
    \algref{euclid}{euclidendwhile}
    is the line we seek.

The while in algorithm 1 ends in line 7, so 1.7 is the line we seek.

###  2.6 Breaking up long algorithms

Sometimes you have a long algorithm that needs to be broken into parts, each
on a separate float. For this you can use the following:

`\algstore{<savename>}` saves the line number, indentation, open blocks of the
current algorithm and closes all blocks. If used, then this must be the last
command before closing the algorithmic block. Each saved algorithm must be
continued later in the document.

`\algstore*{<savename>}` Like the above, but the algorithm must not be
continued.

`\algrestore{<savename>}` restores the state of the algorithm saved under
`<savename>` in this algorithmic block. If used, then this must be the first
command in an algorithmic block. A save is deleted while restoring.

`\algrestore*{<savename>}` Like the above, but the save will not be deleted,
so it can be restored again.

See example in the Examples section.

###  2.7 Multiple layouts in the same document

You can load multiple algorithmicx layouts in the same document. You can
switch between the layouts using the `\alglanguage{<layoutname>}` command.
After this command all new algorithmic environments will use the given layout
until the layout is changed again.

##  3 The predefined layouts

###  3.1 The algpseudocode layout

If you are familiar with the algorithmic package, then you’ll find it easy to
switch. You can use the old algorithms with the algcompatible layout, but
please use the algpseudocode layout for new algorithms.

To use algpseudocode, simply load `algpseudocode.sty`:

    \usepackage{algpseudocode}

You don’t need to manually load the algorithmicx package, as this is done by
algpseudocode.

The first algorithm one should write is the first algorithm ever (ok, an
improved version), Euclid’s algorithm:

Algorithm 1 Euclid’s algorithm

1:procedure Euclid($a,b$)$\triangleright$ The g.c.d. of a and b

2: $r\leftarrow a\bmod b$

3: while $r\not=0$ do$\triangleright$ We have the answer if r is 0

4: $a\leftarrow b$

5: $b\leftarrow r$

6: $r\leftarrow a\bmod b$

7: end while

8: return $b$$\triangleright$ The gcd is b

9:end procedure

Created with the following source:

    \begin{algorithm}
    \caption{Euclid’s algorithm}\label{euclid}
    \begin{algorithmic}[1]
    \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
       \State $r\gets a\bmod b$
       \While{$r\not=0$}\Comment{We have the answer if r is 0}
          \State $a\gets b$
          \State $b\gets r$
          \State $r\gets a\bmod b$
       \EndWhile\label{euclidendwhile}
       \State \textbf{return} $b$\Comment{The gcd is b}
    \EndProcedure
    \end{algorithmic}
    \end{algorithm}

The `\State` stands at the beginning of each simple statement; the respective
statement is put in a new line, with the needed indentation. The `\Procedure`
…`\EndProcedure` and `\While` …`\EndWhile` blocks (like any block defined in
the algpseudocode layout) automatically indent their content. The indentation
of the source doesn’t matter, so

    \begin{algorithmic}[1]
    \Repeat
    \Comment{forever}
    \State this\Until{you die.}
    \end{algorithmic}

1:repeat$\triangleright$ forever

2: this

3:until you die.

4:

But, generally, it is a good idea to keep the source indented, since you will
find errors much easier. And your tex file looks better!

All examples and syntax descriptions will be shown as the previous example —
the left side shows the LaTeX input, and the right side the algorithm, as it
appears in your document. I’m cheating! Don’t look in the `algorithmicx.tex`
file! Believe what the examples state! I may use some undocumented and dirty
stuff to create all these examples. You might be more confused after opening
`algorithmicx.tex` as you was before.

In the case of syntax descriptions the text between $<$ and $>$ is symbolic,
so if you type what you see on the left side, you will not get the algorithm
on the right side. But if you replace the text between $<$ $>$ with a proper
piece of algorithm, then you will probably get what you want. The parts
between $[$ and $]$ are optional.

####  3.1.1 The for block

The for block may have one of the forms:

    \For{<text>}
       <body>
    \EndFor

1:for $<$text$>$ do

2: $<$body$>$

3:end for

    \ForAll{<text>}
       <body>
    \EndFor

1:for all $<$text$>$ do

2: $<$body$>$

3:end for

Example:

    \begin{algorithmic}[1]
    \State $sum\gets 0$
    \For{$i\gets 1, n$}
       \State $sum\gets sum+i$
    \EndFor
    \end{algorithmic}

1:$sum\leftarrow 0$

2:for $i\leftarrow 1,n$ do

3: $sum\leftarrow sum+i$

4:end for

5:

####  3.1.2 The while block

The while block has the form:

    \While{<text>}
       <body>
    \EndWhile

1:while $<$text$>$ do

2: $<$body$>$

3:end while

Example:

    \begin{algorithmic}[1]
    \State $sum\gets 0$
    \State $i\gets 1$
    \While{$i\le n$}
       \State $sum\gets sum+i$
       \State $i\gets i+1$
    \EndWhile
    \end{algorithmic}

1:$sum\leftarrow 0$

2:$i\leftarrow 1$

3:while $i\leq n$ do

4: $sum\leftarrow sum+i$

5: $i\leftarrow i+1$

6:end while

7:

####  3.1.3 The repeat block

The repeat block has the form:

    \Repeat
       <body>
    \Until{<text>}

1:repeat

2: $<$body$>$

3:until $<$text$>$

Example:

    \begin{algorithmic}[1]
    \State $sum\gets 0$
    \State $i\gets 1$
    \Repeat
       \State $sum\gets sum+i$
       \State $i\gets i+1$
    \Until{$i>n$}
    \end{algorithmic}

1:$sum\leftarrow 0$

2:$i\leftarrow 1$

3:repeat

4: $sum\leftarrow sum+i$

5: $i\leftarrow i+1$

6:until $i>n$

7:

####  3.1.4 The if block

The if block has the form:

    \If{<text>}
       <body>
    [
    \ElsIf{<text>}
       <body>
    ...
    ]
    [
    \Else
       <body>
    ]
    \EndIf

1:if $<$text$>$ then

2: $<$body$>$

3:[

4:else if $<$text$>$ then

5: $<$body$>$

6:…

7:]

8:[

9:else

10: $<$body$>$

11:]

12:end if

Example:

    \begin{algorithmic}[1]
    \If{$quality\ge 9$}
       \State $a\gets perfect$
    \ElsIf{$quality\ge 7$}
       \State $a\gets good$
    \ElsIf{$quality\ge 5$}
       \State $a\gets medium$
    \ElsIf{$quality\ge 3$}
       \State $a\gets bad$
    \Else
       \State $a\gets unusable$
    \EndIf
    \end{algorithmic}

1:if $quality\geq 9$ then

2: $a\leftarrow perfect$

3:else if $quality\geq 7$ then

4: $a\leftarrow good$

5:else if $quality\geq 5$ then

6: $a\leftarrow medium$

7:else if $quality\geq 3$ then

8: $a\leftarrow bad$

9:else

10: $a\leftarrow unusable$

11:end if

12:

####  3.1.5 The procedure block

The procedure block has the form:

    \Procedure{<name>}{<params>}
       <body>
    \EndProcedure

1:procedure $<$name$>$($<$params$>$)

2: $<$body$>$

3:end procedure

Example: See Euclid’s algorithm on page 1.

####  3.1.6 The function block

The function block has the same syntax as the procedure block:

    \Function{<name>}{<params>}
       <body>
    \EndFunction

1:function $<$name$>$($<$params$>$)

2: $<$body$>$

3:end function

####  3.1.7 The loop block

The loop block has the form:

    \Loop
       <body>
    \EndLoop

1:loop

2: $<$body$>$

3:end loop

####  3.1.8 Other commands in this layout

The starting conditions for the algorithm can be described with the require
instruction, and its result with the ensure instruction.

A procedure call can be formatted with `\Call`.

    \Require something
    \Ensure something
    \Statex
    \State \Call{Create}{10}

1:something

2:something

3:

4:Create(10)

Example:

    \begin{algorithmic}[1]
    \Require $x\ge5$
    \Ensure $x\le-5$
    \Statex
    \While{$x>-5$}
       \State $x\gets x-1$
    \EndWhile
    \end{algorithmic}

1:$x\geq 5$

2:$x\leq-5$

3:

4:while $x>-5$ do

5: $x\leftarrow x-1$

6:end while

7:

####  3.1.9 Package options

The algpseudocode package supports the following options:

compatible/noncompatible

Obsolote, use the algcompatible layout instead.
If you would like to use old algorithms, written with the algorithmic package
without (too much) modification, then use the compatible option. This option
defines the uppercase version of the commands. Note that you still need to
remove the `[...]` comments (these comments appeared due to some limitations
in the algorithmic package, these limitations and comments are gone now). The
default noncompatible does not define the all uppercase commands.

noend/end

With noend specified all end … lines are omitted. You get a somewhat smaller
algorithm, and the ugly feeling, that something is missing… The end value is
the default, it means, that all end … lines are in their right place.

####  3.1.10 Changing command names

One common thing for a pseudocode is to change the command names. Many people
use many different kind of pseudocode command names. In algpseudocode all
keywords are declared as `\algorithmic<keyword>`. You can change them to
output the text you need:

    \algrenewcommand\algorithmicwhile{\textbf{am\’\i g}}
    \algrenewcommand\algorithmicdo{\textbf{v\’egezd el}}
    \algrenewcommand\algorithmicend{\textbf{v\’ege}}
    \begin{algorithmic}[1]
    \State $x \gets 1$
    \While{$x < 10$}
       \State $x \gets x + 1$
    \EndWhile
    \end{algorithmic}

1:$x\leftarrow 1$

2:amíg $x<10$ végezd el

3: $x\leftarrow x+1$

4:vége amíg

5:

In some cases you may need to change even more (in the above example amíg and
vége should be interchanged in the `\EndWhile` text). Maybe the number of the
parameters taken by some commands must be changed too. this can be done with
the command text customizing macros (see section 4.6). Here I’ll give only
some examples of the most common usage:

    \algrenewcommand\algorithmicwhile{\textbf{am\’\i g}}
    \algrenewcommand\algorithmicdo{\textbf{v\’egezd el}}
    \algrenewcommand\algorithmicend{\textbf{v\’ege}}
    \algrenewtext{EndWhile}{\algorithmicwhile\ \algorithmicend}
    \begin{algorithmic}[1]
    \State $x \gets 1$
    \While{$x < 10$}
       \State $x \gets x - 1$
    \EndWhile
    \end{algorithmic}

1:$x\leftarrow 1$

2:amíg $x<10$ végezd el

3: $x\leftarrow x-1$

4:amíg vége

5:

    \algnewcommand\algorithmicto{\textbf{to}}
    \algrenewtext{For}[3]%
      {\algorithmicfor\ #1 \gets #2 \algorithmicto\ #3 \algorithmicdo}
    \begin{algorithmic}[1]
    \State $p \gets 1$
    \For{i}{1}{n}
       \State $p \gets p * i$
    \EndFor
    \end{algorithmic}

1:$p\leftarrow 1$

2:for $i\leftarrow 1$ to $n$ do

3: $p\leftarrow p*i$

4:end for

5:

You could create a translation package, that included after the algpseudocode
package translates the keywords to the language you need.

###  3.2 The algpascal layout

The most important feature of the algpascal layout is that it performs
automatically the block indentation. In section 4 you will see how to define
such automatically indented loops. Here is an example to demonstrate this
feature:

    \begin{algorithmic}[1]
    \Begin
    \State $sum:=0$;
    \For{i=1}{n}\Comment{sum(i)}
       \State $sum:=sum+i$;
    \State writeln($sum$);
    \End.
    \end{algorithmic}

1:begin

2:$sum:=0$;

3:for $i=1$ to $n$ do{sum(i)}

4: $sum:=sum+i$;

5:writeln($sum$);

6:end.

7:

Note, that the `\For` is not closed explicitly, its end is detected
automatically. Again, the indentation in the source doesn’t affect the output.
In this layout every parameter passed to a command is put in mathematical
mode.

####  3.2.1 The begin … end block

    \Begin
       <body>
    \End

1:begin

2:$<$body$>$

3:end

The `\Begin` … `\End` block and the `\Repeat` … `\Until` block are the only
blocks in the algpascal style (instead of `\Begin` you may write `\Asm`). This
means, that every other loop is ended automatically after the following
command (another loop, or a block).

####  3.2.2 The for loop

    \For{<assign>}{<expr>}
       <command>

1:for $<$$assign$$>$ to $<$$expr$$>$ do

2: $<$command$>$

The For loop (as all other loops) ends after the following command (a block
counts also as a single command).

    \begin{algorithmic}[1]
    \Begin
       \State $sum:=0$;
       \State $prod:=1$;
       \For{i:=1}{10}
          \Begin
             \State $sum:=sum+i$;
             \State $prod:=prod*i$;
          \End
    \End.
    \end{algorithmic}

1:begin

2:$sum:=0$;

3:$prod:=1$;

4:for $i:=1$ to $10$ do

5: begin

6: $sum:=sum+i$;

7: $prod:=prod*i$;

8: end

9:end.

10:

####  3.2.3 The while loop

    \While{<expression>}
       <command>

1:while $<$$expression$$>$ do

2: $<$command$>$

####  3.2.4 The repeat… until block

    \Repeat
       <body>
    \Until{<expression>}

1:repeat

2: $<$body$>$

3:until $<$$expression$$>$

####  3.2.5 The if command

    \If{<expression>}
       <command>
    [
    \Else
       <command>
    ]

1:if $<$$expression$$>$ then

2: $<$command$>$

3:[

4:else

5: $<$command$>$

6:]

Every `\Else` matches the nearest `\If`.

####  3.2.6 The procedure command

    \Procedure <some text>

1:procedure $<$some text$>$

`\Procedure` just writes the “procedure” word on a new line… You will probably
put a `\Begin`… `\End` block after it.

####  3.2.7 The function command

    \Function<some text>

1:function $<$some text$>$

Just like Procedure.

###  3.3 The algc layout

Sorry, the algc layout is unfinished. The commands defined are:

  * •

`\{`… `\}` block

  * •

`\For` with 3 params

  * •

`\If` with 1 param

  * •

`\Else` with no params

  * •

`\While` with 1 param

  * •

`\Do` with no params

  * •

`\Function` with 3 params

  * •

`\Return` with no params

##  4 Custom algorithmic blocks

###  4.1 Blocks and loops

Most of the environments defined in the standard layouts (and most probably
the ones you will define) are divided in two categories:

Blocks

are the environments witch contain an arbitrary number of commands or nested
blocks. Each block has a name, begins with a starting command and ends with an
ending command. The commands in a block are indented by `\algorithmicindent`
(or another amount).

If your algorithm ends without closing all blocks, the algorithmicx package
gives you a nice error. So be good, and close them all!

Blocks are all the environments defined in the `algpseudocode` package, the
`\Begin` …`\End` block in the `algpascal` package, and some other ones.

Loops

(Let us call them loops…) The loops are environments that include only one
command, loop or block; a loop is closed automatically after this command. So
loops have no ending commands. If your algorithm (or a block) ends before the
single command of a loop, then this is considered an empty command, and the
loop is closed. Feel free to leave open loops at the end of blocks!

Loops are most of the environments in the `algpascal` and `algc` packages.

For some rare constructions you can create mixtures of the two environments
(see section 4.5). Each block and loop may be continued with another one (like
the `If` with `Else`).

###  4.2 Defining blocks

There are several commands to define blocks. The difference is in what is
defined beyond the block. The macro `\algblock` defines a new block with
starting and ending entity.

    \algblock[<block>]{<start>}{<end>}

The defined commands have no parameters, and the text displayed by them is
`\textbf{<start>}` and `\textbf{<end>}`. You can change these texts later
(4.6).

With `\algblockdefx` you can give the text to be output by the starting and
ending command and the number of parameters for these commands. In the text
reference with #$n$ to the parameter number $n$. Observe that the text is
given in the form you define or redefine macros, and really, this is what
happens.

    \algblockdefx[<block>]{<start>}{<end>}
       [<startparamcount>][<default value>]{<start text>}
       [<endparamcount>][<default value>]{<end text>}

This defines a new block called `<block>`, `<start>` opens the block, `<end>`
closes the block, `<start>` displays `<start text>`, and has
`<startparamcount>` parameters, `<end>` displays `<end text>`, and has
`<endparamcount>` parameters. For both `<start>` and `<end>`, if `<default
value>` is given, then the first parameter is optional, and its default value
is `<default value>`.

If you want to display different text (and to have a different number of
parameters) for `<end>` at the end of different blocks, then use the
`\algblockx` macro. Note that it is not possible to display different starting
texts, since it is not possible to start different blocks with the same
command. The `<start text>` defined with `\algblockx` has the same behavior as
if defined with `\algblockdefx`. All ending commands not defined with
`\algblockx` will display the same text, and the ones defined with this macro
will display the different texts you specified.

    \algblockx[<block>]{<start>}{<end>}
       [<startparamcount>][<default value>]{<start text>}
       [<endparamcount>][<default value>]{<end text>}

If in the above definitions the `<block>` is missing, then the name of the
starting command is used as block name. If a block with the given name already
exists, these macros don’t define a new block, instead this it will be used
the defined block. If `<start>` or `<end>` is empty, then the definition does
not define a new starting/ending command for the block, and then the
respective text must be missing from the definition. You may have more
starting and ending commands for one block. If the block name is missing, then
a starting command must be given.

    \algblock[Name]{Start}{End}
    \algblockdefx[NAME]{START}{END}%
       [2][Unknown]{Start #1(#2)}%
       {Ending}
    \algblockdefx[NAME]{}{OTHEREND}%
       [1]{Until (#1)}
    \begin{algorithmic}[1]
    \Start
       \Start
          \START[One]{x}
          \END
          \START{0}
          \OTHEREND{\texttt{True}}
       \End
       \Start
       \End
    \End
    \end{algorithmic}

1:Start

2: Start

3: Start One(x)

4: Ending

5: Start Unknown(0)

6: Until (True)

7: End

8: Start

9: End

10:End

11:

###  4.3 Defining loops

The loop defining macros are similar to the block defining macros. A loop has
no ending command and ends after the first state, block or loop that follows
the loop. Since loops have no ending command, the macro `\algloopx` would not
have mutch sense. The loop defining macros are:

    \algloop[<loop>]{<start>}

    \algloopdefx[<loop>]{<start>}
       [<startparamcount>][<default value>]{<start text>}

Both create a loop named `<loop>` with the starting command `<start>`. The
second also sets the number of parameters, and the text displayed by the
starting command.

    \algloop{For}
    \algloopdefx{If}[1]{\textbf{If} #1 \textbf{then}}
    \algblock{Begin}{End}
    \begin{algorithmic}[1]
    \For
       \Begin
       \If{$a < b$}
          \For
             \Begin
             \End
       \Begin
       \End
       \End
    \end{algorithmic}

1:For

2: Begin

3: If $a<b$ then

4: For

5: Begin

6: End

7: Begin

8: End

9: End

10:

###  4.4 Continuing blocks and loops

For each block/loop you may give commands that close the block or loop and
open another block or loop. A good example for this is the if … then … else
construct. The new block or loop can be closed or continued, as any other
blocks and loops.

To create a continuing block use one of the following:

    \algcblock[<new block>]{<old block>}{<continue>}{<end>}

    \algcblockdefx[<new block>]{<old block>}{<continue>}{<end>}
       [<continueparamcount>][<default value>]{<continue text>}
       [<endparamcount>][<default value>]{<end text>}

    \algcblockx[<new block>]{<old block>}{<continue>}{<end>}
       [<continueparamcount>][<default value>]{<continue text>}
       [<endparamcount>][<default value>]{<end text>}

All three macros define a new block named `<new block>`. If `<new block>` is
not given, then `<continue>` is used as the new block name. It is not allowed
to have both `<new block>` missing, and `<continue>` empty. The `<continue>`
command ends the `<old block>` block/loop and opens the `<new block>` block.
Since `<continue>` may end different blocks and loops, it can have different
text at the end of the different blocks/loops. If the `<continue>` command
doesn’t find an `<old block>` to close, then an error is reported.

Create continuing loops with the followings:

    \algcloop[<new loop>]{<old block>}{<continue>}

    \algcloopdefx[<new loop>]{<old block>}{<continue>}
       [<continueparamcount>][<default value>]{<continue text>}

    \algcloopx[<new loop>]{<old block>}{<continue>}
       [<continueparamcount>][<default value>]{<continue text>}

These macros create a continuing loop, the `<continue>` closes the `<old
block>` block/loop, and opens a `<new loop>` loop.

    \algblock{If}{EndIf}
    \algcblock[If]{If}{ElsIf}{EndIf}
    \algcblock{If}{Else}{EndIf}
    \algcblockdefx[Strange]{If}{Eeee}{Oooo}
       [1]{\textbf{Eeee} "#1"}
       {\textbf{Wuuuups\dots}}
    \begin{algorithmic}[1]
    \If
       \If
       \ElsIf
       \ElsIf
          \If
          \ElsIf
          \Else
          \EndIf
       \EndIf
       \If
       \EndIf
    \Eeee{Creep}
    \Oooo
    \end{algorithmic}

1:If

2: If

3: ElsIf

4: ElsIf

5: If

6: ElsIf

7: Else

8: EndIf

9: EndIf

10: If

11: EndIf

12:Eeee ”Creep”

13:Wuuuups…

14:

    \algloop{If}
    \algcloop{If}{Else}
    \algblock{Begin}{End}
    \begin{algorithmic}[1]
    \If
       \Begin
       \End
    \Else
       \If
          \Begin
          \End
    \end{algorithmic}

1:If

2: Begin

3: End

4:Else

5: If

6: Begin

7: End

8:

###  4.5 Even more customisation

With the following macros you can give the indentation used by the new block
(or loop), and the number of stataments after that the ”block” is
automatically closed. This value is $\infty$ for blocks, 1 for loops, and 0
for stataments. There is a special value, 65535, meaning that the defined
”block” does not end automatically, but if it is enclosed in a block, then the
ending command of the block closes this ”block” as well.

    \algsetblock[<block>]{<start>}{<end>}
       {<lifetime>}{<indent>}

    \algsetblockdefx[<block>]{<start>}{<end>}
       {<lifetime>}{<indent>}
       [<startparamcount>][<default value>]{<start text>}
       [<endparamcount>][<default value>]{<end text>}

    \algsetblockx[<block>]{<start>}{<end>}
       {<lifetime>}{<indent>}
       [<startparamcount>][<default value>]{<start text>}
       [<endparamcount>][<default value>]{<end text>}

    \algcsetblock[<new block>]{<old block>}{<continue>}{<end>}
       {<lifetime>}{<indent>}

    \algcsetblockdefx[<new block>]{<old block>}{<continue>}{<stop>}
       {<lifetime>}{<indent>}
       [<continueparamcount>][<default value>]{<continue text>}
       [<endparamcount>][<default value>]{<end text>}

    \algcsetblockx[<new block>]{<old block>}{<continue>}{<stop>}
       {<lifetime>}{<indent>}
       [<continueparamcount>][<default value>]{<continue text>}
       [<endparamcount>][<default value>]{<end text>}

The `<lifetime>` is the number of stataments after that the block is closed.
An empty `<lifetime>` field means $\infty$. The `<indent>` gives the
indentation of the block. Leave this field empty for the default indentation.
The rest of the parameters has the same function as for the previous macros.

    \algsetblock[Name]{Start}{Stop}{3}{1cm}
    \algsetcblock[CName]{Name}{CStart}{CStop}{2}{2cm}
    \begin{algorithmic}[1]
    \Start
       \State 1
       \State 2
       \State 3
    \State 4
    \Start
       \State 1
    \Stop
    \State 2
    \Start
       \State 1
    \CStart
       \State 1
       \State 2
    \State 3
    \Start
       \State 1
    \CStart
       \State 1
    \CStop
    \end{algorithmic}

1:Start

2: 1

3: 2

4: 3

5:4

6:Start

7: 1

8:Stop

9:2

10:Start

11: 1

12:CStart

13: 1

14: 2

15:3

16:Start

17: 1

18:CStart

19: 1

20:CStop

21:

The created environments behave as follows:

  * •

It starts with `\Start`. The nested environments are indented by 1 cm.

  * •

If it is followed by at least 3 environments (stataments), then it closes
automatically after the third one.

  * •

If you put a `\Stop` before the automatic closure, then this `\Stop` closes
the environment. `CStart` closes a block called `Name` and opens a new one
called `CName` and having an indentaion of 2 cm.

  * •

`CName` can be closed with `CStop` or it is closed automatically after 2
environments.

###  4.6 Parameters, custom text

With `\algrenewtext` you can change the number of parameters, and the text
displayed by the commands. With `algnotext` you can makes the vole output line
disappear, but it works only for ending commands, for beginning commands you
will get an incorrect output.

    \algrenewcommand[<block>]{<command>}
       [<paramcount>][<default value>]{<text>}

    \algnotext[<block>]{<ending command>}

If `<block>` is missing, then the default text is changed, and if `<block>` is
given, then the text displayed at the end of `<block>` is changed.

To make a command output the default text at the end of a block (say, you have
changed the text for this block), use `\algdefaulttext`.

    \algdefaulttext[<block>]{<command>}

If the `<block>` is missing, than the default text itself will be set to the
default value (this is `\textbf{<command>}`).

###  4.7 The ONE defining macro

All block and loop defining macros call the same macro. You may use this macro
to gain a better acces to what will be defined. This macro is `\algdef`.

    \algdef{<flags>}...

Depending on the flags the macro can have many forms.

Flag | Meaning
---|---
s | starting command, without text
S | starting command with text
c | continuing command, without text
C | continuing command, with default text
xC | continuing command, with block specific text
e | ending command, without text
E | continuing command, with default text
xE | continuing command, with block specific text
N | ending command, with default ”no text”
xN | ending command, with no text for this block
b | block(default)
l | loop
L | loop closes after the given number of stataments
i | indentation specified

The `<new block>` may be given for any combination of flags, and it is not
allowed to have `<new block>` missing and `<start>` missing/empty. For c, C,
xC an old block is expected. For s, S, c, C, xC the `<start>` must be given.
For e, E, xE, N, xN the `<end>` must be given. For L the `<lifetime>` must be
given. For i the `<indent>` must be given. For S, C, xC the starting text and
related infos must be given. For E, xE the ending text must be given. For each
combination of flags give only the needed parameters, in the following order:

    \algdef{<flags>}[<new block>]{<old block>}{<start>}{<end>}
       {<lifetime>}{<indent>}
       [<startparamcount>][<default value>]{<start text>}
       [<endparamcount>][<default value>]{<end text>}

The block and loop defining macros call `\algdef` with the following flags:

Macro | Meaning
---|---
`\algblock` | `\algdef{se}`
`\algcblock` | `\algdef{ce}`
`\algloop` | `\algdef{sl}`
`\algcloop` | `\algdef{cl}`
`\algsetblock` | `\algdef{seLi}`
`\algsetcblock` | `\algdef{ceLi}`
`\algblockx` | `\algdef{SxE}`
`\algblockdefx` | `\algdef{SE}`
`\algcblockx` | `\algdef{CxE}`
`\algcblockdefx` | `\algdef{CE}`
`\algsetblockx` | `\algdef{SxELi}`
`\algsetblockdefx` | `\algdef{SELi}`
`\algsetcblockx` | `\algdef{CxELi}`
`\algsetcblockdefx` | `\algdef{CELi}`
`\algloopdefx` | `\algdef{Sl}`
`\algcloopx` | `\algdef{Cxl}`
`\algcloopdefx` | `\algdef{Cl}`

##  5 Examples

###  5.1 A full example using algpseudocode

    \documentclass{article}
    \usepackage{algorithm}
    \usepackage{algpseudocode}
    \begin{document}
    \begin{algorithm}
    \caption{The Bellman-Kalaba algorithm}
    \begin{algorithmic}[1]
    \Procedure {BellmanKalaba}{$G$, $u$, $l$, $p$}
       \ForAll {$v \in V(G)$}
          \State $l(v) \leftarrow \infty$
       \EndFor
       \State $l(u) \leftarrow 0$
       \Repeat
          \For {$i \leftarrow 1, n$}
             \State $min \leftarrow l(v_i)$
             \For {$j \leftarrow 1, n$}
                \If {$min > e(v_i, v_j) + l(v_j)$}
                   \State $min \leftarrow e(v_i, v_j) + l(v_j)$
                   \State $p(i) \leftarrow v_j$
                \EndIf
             \EndFor
             \State $l’(i) \leftarrow min$
          \EndFor
          \State $changed \leftarrow l \not= l’$
          \State $l \leftarrow l’$
       \Until{$\neg changed$}
    \EndProcedure
    \Statex
    \Procedure {FindPathBK}{$v$, $u$, $p$}
       \If {$v = u$}
          \State \textbf{Write} $v$
       \Else
          \State $w \leftarrow v$
          \While {$w \not= u$}
             \State \textbf{Write} $w$
             \State $w \leftarrow p(w)$
          \EndWhile
       \EndIf
    \EndProcedure
    \end{algorithmic}
    \end{algorithm}
    \end{document}

Algorithm 2 The Bellman-Kalaba algorithm

1:procedure BellmanKalaba($G$, $u$, $l$, $p$)

2: for all $v\in V(G)$ do

3: $l(v)\leftarrow\infty$

4: end for

5: $l(u)\leftarrow 0$

6: repeat

7: for $i\leftarrow 1,n$ do

8: $min\leftarrow l(v_{i})$

9: for $j\leftarrow 1,n$ do

10: if $min>e(v_{i},v_{j})+l(v_{j})$ then

11: $min\leftarrow e(v_{i},v_{j})+l(v_{j})$

12: $p(i)\leftarrow v_{j}$

13: end if

14: end for

15: $l^{\prime}(i)\leftarrow min$

16: end for

17: $changed\leftarrow l\not=l^{\prime}$

18: $l\leftarrow l^{\prime}$

19: until $\neg changed$

20:end procedure

21:

22:procedure FindPathBK($v$, $u$, $p$)

23: if $v=u$ then

24: Write $v$

25: else

26: $w\leftarrow v$

27: while $w\not=u$ do

28: Write $w$

29: $w\leftarrow p(w)$

30: end while

31: end if

32:end procedure

###  5.2 Breaking up an algorithm

    \documentclass{article}
    \usepackage{algorithm}
    \usepackage{algpseudocode}
    \begin{document}
    \begin{algorithm}
    \caption{Part 1}
    \begin{algorithmic}[1]
    \Procedure {BellmanKalaba}{$G$, $u$, $l$, $p$}
       \ForAll {$v \in V(G)$}
          \State $l(v) \leftarrow \infty$
       \EndFor
       \State $l(u) \leftarrow 0$
       \Repeat
          \For {$i \leftarrow 1, n$}
             \State $min \leftarrow l(v_i)$
             \For {$j \leftarrow 1, n$}
                \If {$min > e(v_i, v_j) + l(v_j)$}
                   \State $min \leftarrow e(v_i, v_j) + l(v_j)$
                   \State \Comment For some reason we need to break here!
    \algstore{bkbreak}
    \end{algorithmic}
    \end{algorithm}

    And we need to put some additional text between\dots

    \begin{algorithm}[h]
    \caption{Part 2}
    \begin{algorithmic}[1]
    \algrestore{bkbreak}
                   \State $p(i) \leftarrow v_j$
                \EndIf
             \EndFor
             \State $l’(i) \leftarrow min$
          \EndFor
          \State $changed \leftarrow l \not= l’$
          \State $l \leftarrow l’$
       \Until{$\neg changed$}
    \EndProcedure
    \end{algorithmic}
    \end{algorithm}
    \end{document}

Algorithm 3 Part 1

1:procedure BellmanKalaba($G$, $u$, $l$, $p$)

2: for all $v\in V(G)$ do

3: $l(v)\leftarrow\infty$

4: end for

5: $l(u)\leftarrow 0$

6: repeat

7: for $i\leftarrow 1,n$ do

8: $min\leftarrow l(v_{i})$

9: for $j\leftarrow 1,n$ do

10: if $min>e(v_{i},v_{j})+l(v_{j})$ then

11: $min\leftarrow e(v_{i},v_{j})+l(v_{j})$

12: $\triangleright$ For some reason we need to break here!

And we need to put some additional text between…

Algorithm 4 Part 2

13: $p(i)\leftarrow v_{j}$

14: end if

15: end for

16: $l^{\prime}(i)\leftarrow min$

17: end for

18: $changed\leftarrow l\not=l^{\prime}$

19: $l\leftarrow l^{\prime}$

20: until $\neg changed$

21:end procedure

###  5.3 Using multiple layouts

    \documentclass{article}
    \usepackage{algorithm}
    \usepackage{algpseudocode}
    \usepackage{algpascal}
    \begin{document}

    \alglanguage{pseudocode}
    \begin{algorithm}
    \caption{A small pseudocode}
    \begin{algorithmic}[1]
    \State $s \gets 0$
    \State $p \gets 0$
    \For{$i \gets 1,\, 10$}
       \State $s \gets s + i$
       \State $p \gets p + s$
    \EndFor
    \end{algorithmic}
    \end{algorithm}

    \alglanguage{pascal}
    \begin{algorithm}
    \caption{The pascal version}
    \begin{algorithmic}[1]
    \State $s := 0$
    \State $p := 0$
    \For{i = 1}{10}
       \Begin
       \State $s := s + i$
       \State $p := p + s$
       \End
    \end{algorithmic}
    \end{algorithm}

    \end{document}

Algorithm 5 A small pseudocode

1:$s\leftarrow 0$

2:$p\leftarrow 0$

3:for $i\leftarrow 1,\,10$ do

4: $s\leftarrow s+i$

5: $p\leftarrow p+s$

6:end for

Algorithm 6 The pascal version

1:$s:=0$

2:$p:=0$

3:for $i=1$ to $10$ do

4: begin

5: $s:=s+i$

6: $p:=p+s$

7: end

##  6 Bugs

If you have a question or find a bug you can contact me on:

<EMAIL_ADDRESS>
If possible, please create a small LaTeX example related to your problem.