cluto.py 11.5 KB
Newer Older
Bartłomiej Bojanowski's avatar
Bartłomiej Bojanowski committed
1 2 3 4 5 6 7 8 9 10 11 12
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Implementation of cluto worker."""

from __future__ import print_function
import json
import re
import io
import os
import shutil
import tempfile
from subprocess import call
13 14

import numpy as _np
Bartłomiej Bojanowski's avatar
Bartłomiej Bojanowski committed
15 16 17 18 19 20
from sklearn.externals import joblib
import xlsxwriter

verbose = False


21
def load_data(inputFile):
Bartłomiej Bojanowski's avatar
Bartłomiej Bojanowski committed
22 23 24 25 26 27 28 29 30
    """Loading data."""
    with open(inputFile) as json_ifs:
        jsonVal = json.load(json_ifs)
        rowlabels = _np.asarray(jsonVal["rowlabels"])
        data = _np.asarray(jsonVal["arr"])
        jsonVal["arr"] = None
        return data, rowlabels


31
def save_XLSX(names, clustering_path, outfile):
Bartłomiej Bojanowski's avatar
Bartłomiej Bojanowski committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
    """Saving to XLSX."""
    srow = 3
    scol = 4
    with open(clustering_path) as f:
        groups = f.readlines()
    ind = 0
    workbook = xlsxwriter.Workbook(outfile)
    worksheet = workbook.add_worksheet("result")
    worksheet.write(srow, scol, 'Nazwy')
    worksheet.write(srow, scol + 1, 'Grupa')
    srow += 1
    for name in names:
        worksheet.write(srow, scol, name)
        worksheet.write(srow, scol + 1, groups[ind])
        srow += 1
        ind = ind + 1
    workbook.close()


51
def to_heat_map_json(cluto_path, clustering_path, names, outfile):
Bartłomiej Bojanowski's avatar
Bartłomiej Bojanowski committed
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
    """Saving to JSON."""
    with open(clustering_path) as f:
        groups = f.readlines()
    names_out = []
    ind = 0
    for name in names:
        tmp_hsh = {
            'name': name,
            'group': groups[ind].strip()
        }
        names_out.append(tmp_hsh)
        ind = ind + 1

    array = []
    line_num = 0
    with open(cluto_path) as f:
        content = f.readlines()

    regex = r"\d+\s[0-9]*\.?[0-9]+"
    for line in content[1:]:
        arr = re.findall(regex, line)
        for node in arr:
            node = node.split()
            tmp_hsh = {
                'source': str(line_num),
                'target': str((int(node[0]) - 1)),
                'value': str(float(node[1]))
            }
            array.append(tmp_hsh)
        line_num += 1

    out = {'nodes': names_out, 'links': array}
    json_hsh = json.dumps(out)
    with open(outfile, 'w') as outfile:
        outfile.write(json_hsh)


# Reads data from set of csvs from fextor
# Creats matrix and normalise it (divides by tok_count)

def number_of_clusters(options, rowlabels):
    """Calculation of the number of clusters."""
    if 'no_clusters' in options:
        no_clusters = options['no_clusters']
        if not isinstance(no_clusters, int):
            no_clusters = 2
        if no_clusters < 2:
            no_clusters = 2
    else:
        no_clusters = 2
    if int(no_clusters) > len(rowlabels):
        no_clusters = str(len(rowlabels))
    return no_clusters


107 108
def save_cluto_files(mat, rlabels, clabels, cluto_path, rlabel_path,
                     clabel_path):
Bartłomiej Bojanowski's avatar
Bartłomiej Bojanowski committed
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
    """Saving cluto file."""
    with open(cluto_path, 'w') as cluto_ofs:
        # Print header:
        # <num_rows> <num_cols> <num_nonzero>
        print(
            len(rlabels),
            len(clabels),
            _np.count_nonzero(mat),
            file=cluto_ofs,
        )
        for row in mat:
            buf = []
            for idx in row.nonzero()[0]:
                buf.append('{} {}'.format(idx + 1, row[idx]))
            print(' '.join(buf), file=cluto_ofs)
    # Save label files
    with io.open(rlabel_path, 'w') as rlabel_ofs:
        for lab in rlabels:
            print(lab, file=rlabel_ofs)

    with io.open(clabel_path, 'w') as clabel_ofs:
        for lab in clabels:
            print(lab, file=clabel_ofs)


def run_cluto(options, no_clusters, cluto_input_file, rlabel_path, cl_out_file,
              clutoout):
    """Running cluto."""
    cluto_path = "./cluto-2.1.2/Linux-x86_64/scluster"
    with open(clutoout, "w") as outfile:
        call([cluto_path, cluto_input_file, str(no_clusters), '-fulltree',
              '-rlabelfile', rlabel_path,
              '-plotformat', 'ps',
              '-' + options['analysis_type'] +
              '=' + cl_out_file], stdout=outfile)

    # print("fulltree")


def write_node(node_id, tree_dict, name2group):
    """Writing node."""
    child_node_strings = []

    if node_id in tree_dict:
        for child in tree_dict[node_id]:
            child_node_strings.append(write_node(child, tree_dict,
                                                 name2group))
    if len(child_node_strings) == 0:
        node_str = '{"id":"node_' + node_id + '", "group":' + \
158
                   str(name2group[node_id]) + \
Bartłomiej Bojanowski's avatar
Bartłomiej Bojanowski committed
159 160 161 162
                   ', "name":"' + \
                   node_id + \
                   '", "data":{}, "children":['
    else:
163
        node_str = '{"id":"node_' + node_id + '", "name":"' + node_id + \
Bartłomiej Bojanowski's avatar
Bartłomiej Bojanowski committed
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
                   '", "data":{}, "children":['
    node_str += ', '.join(child_node_strings)
    node_str += ']}'
    return node_str


def run_convert2json(cl_out_file, out_file, labels, clustering_path):
    """Converting to json."""
    with open(clustering_path) as f:
        groups = f.readlines()
    name2group = {}
    for i, gr in enumerate(groups):
        name2group[labels[i]] = int(gr)

    tree_dict = {}
    with open(cl_out_file, 'rb') as infile:
        for i, line in enumerate(infile.readlines()):
            if i < len(labels):
                child = labels[i]
            else:
                child = str(i)
            parent = line.split(' ')[0]
            if parent not in tree_dict:
                tree_dict[parent] = [child]
            else:
                tree_dict[parent].append(child)

    out_string = ''
    out_string += write_node(tree_dict['-1'][0], tree_dict, name2group)
    out_string += ''

    with io.open(out_file, 'wb') as outfile:
        outfile.write(out_string.encode("utf8"))


def run_convert(cl_out_file, out_file, options, rowlabels):
    """Running convert."""
    density = '150'
    if options['analysis_type'] != 'plottree':
        density = '300'

    if len(rowlabels) < 50:
        density = '100'

    if len(rowlabels) < 25:
        density = '50'

211 212 213 214
    #    if options['analysis_type'] == 'plottree':
    #       resize = '50%'
    #   else:
    #       resize = '100%'
Bartłomiej Bojanowski's avatar
Bartłomiej Bojanowski committed
215 216 217 218 219 220 221

    # print density
    call(['convert', '-density', density, cl_out_file, 'png:' + out_file])


def run(inputFile, outputFile, options):
    """Running cluto worker."""
222
    data, rowlabels = load_data(inputFile + "/similarity.json")
Bartłomiej Bojanowski's avatar
Bartłomiej Bojanowski committed
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
    if "analysis_type" not in options:
        options["analysis_type"] = "plottree"
    no_clusters = number_of_clusters(options, rowlabels)
    temp_folder = tempfile.mkdtemp()

    if not os.path.exists(temp_folder):
        os.mkdir(temp_folder)

    cluto_path = os.path.join(temp_folder, 'matrix.txt')
    rlabel_path = os.path.join(temp_folder, 'documents_ids.txt')
    cluto_out_path = os.path.join(temp_folder, 'cluto.ps')

    shutil.copy2(os.path.join(inputFile, 'matrix.txt'),
                 os.path.join(temp_folder, 'matrix.txt'))
    with io.open(rlabel_path, 'w') as rlabel_ofs:
        for lab in rowlabels:
            print(lab, file=rlabel_ofs)

    run_cluto(options, no_clusters, cluto_path, rlabel_path,
              cluto_out_path, os.path.join(temp_folder, 'clutoout.txt'))

    if not os.path.exists(outputFile):
        os.mkdir(outputFile)
    shutil.copyfile(os.path.join(temp_folder, 'clutoout.txt'),
                    os.path.join(outputFile, 'clutoout.txt'))
    run_convert2json(os.path.join(temp_folder, 'matrix.txt.tree'),
                     os.path.join(outputFile, 'result.json'), rowlabels,
                     os.path.join(temp_folder, 'matrix.txt.clustering.' +
                                  str(no_clusters)))
    run_convert(cluto_out_path, os.path.join(outputFile, 'result.png'),
                options, rowlabels)

    # for heatmap
256 257 258 259
    to_heat_map_json(cluto_path, os.path.join(temp_folder,
                                              'matrix.txt.clustering.' +
                                              str(no_clusters)), rowlabels,
                     outputFile + "/data.json")
Bartłomiej Bojanowski's avatar
Bartłomiej Bojanowski committed
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277

    # Check if they are required by any tool
    shutil.copyfile(os.path.join(temp_folder, 'matrix.txt.clustering.' +
                                 str(no_clusters)),
                    os.path.join(outputFile, 'result.clustering'))
    shutil.copyfile(cluto_path, os.path.join(outputFile, 'matrix.txt'))
    joblib.dump(rowlabels, outputFile + "/rowlabels.pkl")

    # Results in JSON:
    with open(os.path.join(temp_folder, 'matrix.txt.clustering.' +
                                        str(no_clusters)), 'rb') as f:
        clusters = [cluster_id.strip('\n') for cluster_id in f.readlines()]

    # to be deleted, but now required by visualisation
    res = {"clusters": clusters, "rowlabels": rowlabels.tolist()}
    with open(os.path.join(outputFile, 'clusters.json'), 'w') as outfile:
        json.dump(res, outfile)

278
    labels = get_lables_from_names(rowlabels)
Bartłomiej Bojanowski's avatar
Bartłomiej Bojanowski committed
279 280 281 282 283 284
    labels["groupnames"]["clusters"] = list(set(clusters))
    labels["groups"]["clusters"] = clusters
    with open(os.path.join(outputFile, 'labels.json'), 'w') as outfile:
        json.dump(labels, outfile)

    # results in XLSX
285 286 287
    save_XLSX(rowlabels, os.path.join(temp_folder, 'matrix.txt.clustering.' +
                                      str(no_clusters)),
              os.path.join(outputFile, 'result.xlsx'))
Bartłomiej Bojanowski's avatar
Bartłomiej Bojanowski committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305

    # Coping results for next tools
    # for visulisation (mds)
    # similarity matrix
    shutil.copyfile(os.path.join(inputFile, 'similarity.json'),
                    os.path.join(outputFile, 'similarity.json'))
    shutil.copyfile(os.path.join(inputFile, 'distance.json'),
                    os.path.join(outputFile, 'distance.json'))

    # for featsel
    # matrix after selection and weighting
    shutil.copyfile(os.path.join(inputFile, 'weighted.json'),
                    os.path.join(outputFile, 'weighted.json'))

    # remove temp_folder
    shutil.rmtree(temp_folder)


306
def get_lables_from_names(row_labels):
Bartłomiej Bojanowski's avatar
Bartłomiej Bojanowski committed
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    """Getting labels from names."""
    # data, data_cleaned,shortest_row_len, row_labels = get_data(row)
    shortest_row_len = 10000000

    data = []
    for i, t in enumerate(row_labels):
        t = str(t.encode('utf-8'))
        t = re.split(r"[,._\-:]", t)
        t = list(map(str.strip, t))
        data.append(t)
        if shortest_row_len > len(t):
            shortest_row_len = len(t)

    repeating = set(data[0])
    for s in data[1:]:
        repeating.intersection_update(s)
    repeating = list(repeating)

    for i, d in enumerate(data):
        for r in repeating:
            if r in d:
                d.remove(r)
                data[i] = d

    first_lvl_categories = set()
    first_lvl_name = 'first level'

    second_lvl_categories = set()
    second_lvl_name = 'second level'

    last_lvl_categories = set()
    last_lvl_name = 'last level'

    second_lvl_idx = 1
    if shortest_row_len < 2:
        second_lvl_idx = 0

    for row in data:
        if len(row) <= second_lvl_idx:
            second_lvl_idx = 0
        first_lvl_categories.add(row[0])

        second_lvl_categories.add(row[second_lvl_idx])
        last_lvl_categories.add('_'.join(row[0:-1]))

    group_names = {
        first_lvl_name: list(first_lvl_categories),
        second_lvl_name: list(second_lvl_categories),
        last_lvl_name: list(last_lvl_categories)
    }

    groups = {
        first_lvl_name: [],
        second_lvl_name: [],
        last_lvl_name: []
    }

    for i, row in enumerate(data):
        groups[first_lvl_name].append(row[0])
        groups[second_lvl_name].append(row[second_lvl_idx])
        groups[last_lvl_name].append('_'.join(row[0:-1]))

    return {
        'rowlabels': row_labels.tolist(),
        'groups': groups,
        'groupnames': group_names
    }