File size: 9,511 Bytes
168e76d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c5d33d
168e76d
 
 
 
f6825c2
168e76d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c5d33d
168e76d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c5d33d
 
 
168e76d
 
 
 
 
 
 
 
 
 
 
 
 
 
3c5d33d
 
 
 
 
168e76d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c5d33d
 
 
 
 
 
 
 
 
168e76d
 
 
 
 
 
 
 
 
 
 
 
 
 
f6825c2
168e76d
 
 
 
 
 
 
 
 
 
 
 
 
 
f7f2122
168e76d
f7f2122
168e76d
 
 
 
 
 
 
 
 
 
 
 
 
 
f7f2122
168e76d
f7f2122
168e76d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7f2122
168e76d
 
 
 
 
 
f6825c2
 
168e76d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
facede3
 
 
 
168e76d
 
3d1e933
168e76d
 
 
3d1e933
 
 
 
 
 
 
168e76d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# Copyright 2023 Dmitry Ustalov
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__author__ = 'Dmitry Ustalov'
__license__ = 'Apache 2.0'

import csv
import os
import re
import subprocess
from dataclasses import dataclass
from tempfile import NamedTemporaryFile
from typing import Dict, IO, List, cast, Tuple, Optional, Any

import gradio as gr
import matplotlib.pyplot as plt
import networkx as nx
import pandas as pd


@dataclass
class Algorithm:
    name: str
    mode: Optional[str] = None
    local_name: Optional[str] = None
    local_params: Optional[str] = None
    global_name: Optional[str] = None
    global_params: Optional[str] = None
    mcl_bin: Optional[str] = None

    def args_clustering(self) -> List[str]:
        args = [self.name]

        if self.mode:
            args.extend(['--mode', self.mode])

        args.extend(self.args_graph())

        if self.global_name:
            args.extend(['--global', self.global_name])

        if self.global_params:
            args.extend(['--global-params', self.global_params])

        if self.mcl_bin:
            args.extend(['--mcl-bin', self.mcl_bin])

        return args

    def args_graph(self) -> List[str]:
        args = []

        if self.local_name:
            args.extend(['--local', self.local_name])

        if self.local_params:
            args.extend(['--local-params', self.local_params])

        return args


if 'MCL_BIN' in os.environ and os.path.isfile(os.environ['MCL_BIN']) and os.access(os.environ['MCL_BIN'], os.X_OK):
    mcl: Optional[str] = os.environ['MCL_BIN']
else:
    mcl = None

ALGORITHMS: Dict[str, Algorithm] = {
    'Watset[CW_top, CW_top]': Algorithm('watset', None, 'cw', 'mode=top', 'cw', 'mode=top'),
    'Watset[CW_lin, CW_top]': Algorithm('watset', None, 'cw', 'mode=lin', 'cw', 'mode=top'),
    'Watset[CW_log, CW_top]': Algorithm('watset', None, 'cw', 'mode=log', 'cw', 'mode=top'),
    'Watset[MCL, CW_top]': Algorithm('watset', None, 'mcl', None, 'cw', 'mode=top'),
    'Watset[CW_top, CW_lin]': Algorithm('watset', None, 'cw', 'mode=top', 'cw', 'mode=lin'),
    'Watset[CW_lin, CW_lin]': Algorithm('watset', None, 'cw', 'mode=lin', 'cw', 'mode=lin'),
    'Watset[CW_log, CW_lin]': Algorithm('watset', None, 'cw', 'mode=log', 'cw', 'mode=lin'),
    'Watset[MCL, CW_lin]': Algorithm('watset', None, 'mcl', None, 'cw', 'mode=lin'),
    'Watset[CW_top, CW_log]': Algorithm('watset', None, 'cw', 'mode=top', 'cw', 'mode=log'),
    'Watset[CW_lin, CW_log]': Algorithm('watset', None, 'cw', 'mode=lin', 'cw', 'mode=log'),
    'Watset[CW_log, CW_log]': Algorithm('watset', None, 'cw', 'mode=log', 'cw', 'mode=log'),
    'Watset[MCL, CW_log]': Algorithm('watset', None, 'mcl', None, 'cw', 'mode=log'),
    'CW_top': Algorithm('cw', 'top'),
    'CW_lin': Algorithm('cw', 'lin'),
    'CW_log': Algorithm('cw', 'log'),
    'MaxMax': Algorithm('maxmax')
}

if mcl:
    ALGORITHMS.update({
        'Watset[CW_top, MCL]': Algorithm('watset', None, 'cw', 'mode=top', 'mcl', 'mcl-bin=' + mcl),
        'Watset[CW_lin, MCL]': Algorithm('watset', None, 'cw', 'mode=lin', 'mcl', 'mcl-bin=' + mcl),
        'Watset[CW_log, MCL]': Algorithm('watset', None, 'cw', 'mode=log', 'mcl', 'mcl-bin=' + mcl),
        'Watset[MCL, MCL]': Algorithm('watset', None, 'mcl', None, 'mcl', 'mcl-bin=' + mcl),
        'MCL': Algorithm('mcl')
    })

SENSE = re.compile(r'^(?P<item>\d+)#(?P<sense>\d+)$')


def visualize(G: nx.Graph, seed: int = 0) -> plt.Figure:
    pos = nx.spring_layout(G, seed=seed)

    fig = plt.figure(dpi=240)
    plt.axis('off')
    nx.draw_networkx_edges(G, pos, alpha=.15)
    nx.draw_networkx_labels(G, pos)

    return fig


# noinspection PyPep8Naming
def watset(G: nx.Graph, algorithm: str, seed: int = 0,
           jar: str = 'watset.jar', timeout: int = 10) -> Tuple[pd.DataFrame, Optional[nx.Graph]]:
    with (NamedTemporaryFile() as graph,
          NamedTemporaryFile(mode='rb') as clusters,
          NamedTemporaryFile(mode='rb') as senses):
        nx.write_edgelist(G, graph.name, delimiter='\t', data=['weight'])

        try:
            result = subprocess.run(['java', '-jar', jar,
                                     '--input', graph.name, '--output', clusters.name, '--seed', str(seed),
                                     *ALGORITHMS[algorithm].args_clustering()],
                                    capture_output=True, text=True, timeout=timeout)

            if result.returncode != 0:
                raise gr.Error(f'Clustering error (code {result.returncode}): {result.stderr}')
        except subprocess.SubprocessError as e:
            raise gr.Error(f'Clustering error: {e}')

        df_clusters = pd.read_csv(clusters, sep='\t', names=('cluster', 'size', 'items'),
                                  dtype={'cluster': int, 'size': int, 'items': str})

        df_clusters['items'] = df_clusters['items'].str.split(', ')

        if ALGORITHMS[algorithm].name == 'watset':
            try:
                result = subprocess.run(['java', '-jar', jar,
                                         '--input', graph.name, '--output', senses.name, '--seed', str(seed),
                                         'graph', *ALGORITHMS[algorithm].args_graph()],
                                        capture_output=True, text=True, timeout=timeout)

                if result.returncode != 0:
                    raise gr.Error(f'Graph error (code {result.returncode}): {result.stderr}')
            except subprocess.SubprocessError as e:
                raise gr.Error(f'Graph error: {e}')

            G_senses = nx.read_edgelist(senses.name, delimiter='\t', comments='\n', data=[('weight', float)])

            return df_clusters, G_senses

        return df_clusters, None


def handler(file: IO[bytes], algorithm: str, seed: int) -> Tuple[pd.DataFrame, plt.Figure]:
    if file is None:
        raise gr.Error('File must be uploaded')

    if algorithm not in ALGORITHMS:
        raise gr.Error(f'Unknown algorithm: {algorithm}')

    with open(file.name) as f:
        try:
            dialect = csv.Sniffer().sniff(f.read(4096))
            delimiter = dialect.delimiter
        except csv.Error:
            delimiter = ','

    G: nx.Graph = nx.read_edgelist(file.name, delimiter=delimiter, comments='\n', data=[('weight', float)])

    mapping: Dict[Any, int] = {}
    reverse: Dict[int, Any] = {}

    for i, node in enumerate(G):
        mapping[node] = i
        reverse[i] = node

    nx.relabel_nodes(G, mapping, copy=False)

    df_clusters, G_senses = watset(G, algorithm=algorithm, seed=seed)

    nx.relabel_nodes(G, reverse, copy=False)

    df_clusters['items'] = df_clusters['items'].apply(lambda items: sorted(reverse[int(item)] for item in items))

    if G_senses is None:
        fig = visualize(G, seed=seed)
    else:
        sense_mapping = {node: f'{reverse[int(match["item"])]}#{match["sense"]}'  # type: ignore
                         for node in G_senses for match in (SENSE.match(node),)}

        nx.relabel_nodes(G_senses, sense_mapping, copy=False)

        fig = visualize(G_senses, seed=seed)

    return df_clusters, fig


def main() -> None:
    iface = gr.Interface(
        fn=handler,
        inputs=[
            gr.File(
                file_types=['.tsv', '.csv'],
                label='Graph'
            ),
            gr.Dropdown(
                choices=cast(List[str], ALGORITHMS),
                value='Watset[MCL, CW_lin]',
                label='Algorithm'
            ),
            gr.Number(
                label='Seed',
                precision=0
            )
        ],
        outputs=[
            gr.Dataframe(
                headers=['cluster', 'size', 'items'],
                label='Clustering'
            ),
            gr.Plot(
                label='Graph'
            )
        ],
        examples=[
            ['java.tsv', 'Watset[MCL, CW_lin]', 0],
            ['java.tsv', 'MaxMax', 0]
        ],
        title='Structure Discovery with Watset',
        description='''
**Watset** is a powerful algorithm for structure discovery in undirected graphs.

By capturing the ambiguity of nodes in a graph, Watset efficiently finds clusters in the input data.

As the input, this tool expects [edge list](https://en.wikipedia.org/wiki/Edge_list) as a comma-separated (CSV) file without header.
Each line of the file should contain three columns:

- `source`: edge source
- `target`: edge target
- `weight`: edge weight

Whether you're working with linguistic data or other networks, Watset is the go-to solution for unlocking hidden patterns and structures.
        ''',
        article='''
**More Watset:**

- Paper: <https://doi.org/10.1162/COLI_a_00354> ([arXiv](https://arxiv.org/abs/1808.06696))
- Implementation: <https://github.com/nlpub/watset-java>
- Maven Central: <https://search.maven.org/artifact/org.nlpub/watset>
- conda-forge: <https://anaconda.org/conda-forge/watset>
        ''',
        allow_flagging='never'
    )

    iface.launch()


if __name__ == '__main__':
    main()