{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Automata\n",
"\n",
"Tensor trains can represent compactly *deterministic finite automata* and *weighted finite automata* that read a fixed number of symbols."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"torch.set_default_dtype(torch.float64)\n",
"import tntorch as tn"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For instance, `weight_mask` produces an automaton that accepts a string iff it has a certain amount of 1's:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"4D TT tensor:\n",
"\n",
" 2 2 2 2\n",
" | | | |\n",
" (0) (1) (2) (3)\n",
" / \\ / \\ / \\ / \\\n",
"1 2 3 2 1"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"m = tn.weight_mask(N=4, weight=2)\n",
"m"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"All accepted input strings can be retrieved alphabetically via `accepted_inputs()`:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[0, 0, 1, 1],\n",
" [0, 1, 0, 1],\n",
" [0, 1, 1, 0],\n",
" [1, 0, 0, 1],\n",
" [1, 0, 1, 0],\n",
" [1, 1, 0, 0]])"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tn.accepted_inputs(m)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"On the other hand, `weight()` produces an automaton that is a little different. Instead of accepting or rejecting strings, it just counts how many 1's the string has:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"tensor(0.)\n",
"tensor(1.)\n",
"tensor(3.)\n"
]
}
],
"source": [
"m = tn.weight(N=4)\n",
"print(m[0, 0, 0, 0])\n",
"print(m[0, 1, 0, 0])\n",
"print(m[1, 0, 1, 1])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Applications\n",
"\n",
"TT automata come in handy to group and sum tensor entries, which is important to obtain advanced [metrics for sensitivity analysis](sobol.ipynb). See also the tutorial on [Boolean logic with *tntorch*](logic.ipynb)."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}