main.py 19.5 KB
Newer Older
1
2
3
4
from flask import Flask, jsonify, request
import pandas as pd
import numpy as np
from flask_cors import CORS
5
from collections import defaultdict, Counter
6
from time import time
7
8
9
import os.path
import json
from sklearn import preprocessing
10
import orjson
11
import dask.dataframe as dd
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
12
13
import bigwig
import bbi
14
15
from bitarray import bitarray
import _ucrdtw
16
17
import _lsh
from scipy.spatial import distance
18
from scipy.sparse import dia_matrix
19
20
21
22
23
from fastdtw import fastdtw
from scipy.spatial.distance import euclidean
import dtw
import math
from random import sample
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
24

25
reload = False
26
27
28
29

app = Flask(__name__)
CORS(app)

30
31
32
33
34
35
36
37
38
39
40
41
42
def calculate_signatures_random_weights(data, window_size=None, hash_size=None, hash_function=None):
    if hash_function is None:
        hash_function = np.random.uniform(-1, 1, size=(window_size, hash_size))
    signatures_bool = np.dot(data, hash_function) > 0
    if signatures_bool.ndim == 1:
        return ''.join(['1' if x else '0' for x in signatures_bool])
    return [''.join(['1' if x else '0' for x in lst]) for lst in signatures_bool], hash_function


def calculate_signatures_cumsum_weights(data, window_size=None, hash_size=None, hash_function=None):
    if hash_function is None:
        hash_function = np.array([np.cumsum(np.random.uniform(-1, 1, window_size)) for _ in range(hash_size)]).transpose()
    signatures_bool = np.dot(data, hash_function) > 0
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
    if hash_size is None:
        signatures_int = np.packbits(signatures_bool)
    else:
        signatures_int = np.packbits(signatures_bool, axis=1).flatten()
    return signatures_int.tolist(), hash_function

def calculate_signatures_normal_weights(data, window_size=None, hash_size=None, hash_function=None):
    if hash_function is None:
        hash_function = np.array([np.random.normal(0, 1, window_size) for _ in range(hash_size)]).transpose()
    signatures_bool = np.dot(data, hash_function) > 0
    if hash_size is None:
        signatures_int = np.packbits(signatures_bool)
    else:
        signatures_int = np.packbits(signatures_bool, axis=1).flatten()
    return signatures_int.tolist(), hash_function

def calculate_signatures_normal_split_weights(data, window_size=None, hash_size=None, hash_function=None):
    if hash_function is None:
        hash_function = []
        interval = int(window_size / hash_size)
        empty = np.zeros(window_size)
        for i in range(hash_size):
            copy = np.copy(empty)
            copy[i * interval:(i+1) * interval] = np.random.normal(0, 1, interval)
            hash_function.append(copy)
        hash_function = np.array(hash_function).transpose()
    signatures_bool = np.dot(data, hash_function) > 0
    if hash_size is None:
        signatures_int = np.packbits(signatures_bool)
    else:
        signatures_int = np.packbits(signatures_bool, axis=1).flatten()
74
75
    return signatures_int.tolist(), hash_function

76
def calculate_signatures_new(data, window_size=None, hash_size=None, hash_function=None):
77
78
    if hash_function is None:
        hash_function = np.array([np.cumsum(np.random.uniform(-1, 1, window_size)) for _ in range(hash_size)]).transpose()
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
    if len(data) == len(np.array(hash_function)[:, 0]):
        signatures_bool = np.dot(data, hash_function) > 0
        output = signatures_bool.astype(int)[0]
        print(output)
        return output
    print('starting hashing')
    t0 = time()
    all_signatures = []
    batch_size = 20
    data = data.transpose()
    temp = np.zeros((batch_size, window_size + batch_size - 1))
    for h in range(hash_size):
        for i in range(batch_size):
            temp[i, i:i + window_size] = hash_function[:, h]
        print('first: ' + str(time() - t0))
        signatures_bool = [np.dot(temp, data[i:i + window_size + batch_size - 1]) > 0 for i in range(0, len(data) - window_size, batch_size)]
        # signatures_bool = []
        # for i in range(0, len(data) - window_size, batch_size):
        #     if i % 1000000 == 0:
        #         print(i)
        #     signatures_bool.append(np.dot(temp, data[i:i + window_size + batch_size - 1]) > 0)
        print('second: ' + str(time() - t0))
        all_signatures.append(np.array(signatures_bool).flatten().astype(int))
    print('done')
    signatures_int = np.packbits(np.stack(np.array(all_signatures), axis=1), axis=0).flatten()
104
105
    return signatures_int.tolist(), hash_function

106

107
lsh_function = calculate_signatures_normal_weights
108

109
110
111
112
113
114
@app.route('/', methods=['GET'])
def index():
    return "hi"

@app.route('/read-data', methods=['GET'])
def read_data():
115
    t0 = time()
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
116
117
118
119
    size = bbi.chromsizes('test.bigWig')['chr1']
    bins = 100000
    data = bigwig.get('test.bigWig', 'chr1', 0, size, bins)
    print(data.shape)
120
    response = {
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
121
122
        "index": list(range(0, size, int(size/(bins)))),
        "values": data.tolist()
123
    }
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
124
    response = orjson.dumps(response)
125
    print('Data read: ' + str(time()-t0))
126
127
128
129
    return response

@app.route('/create-windows', methods=['POST'])
def create_windows():
130
    t0 = time()
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
131
    if reload:
132
133
134
        # raw_data = request.json
        # window_size = int(raw_data['parameters']["windowsize"])
        window_size = 120
135
        chromsize = bbi.chromsizes('test.bigWig')['chr1']
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
        step_size = int(12000 / 6)
        start_bps = np.arange(0, chromsize - 12000 + step_size, step_size)
        end_bps = np.arange(12000, chromsize + step_size, step_size)
        data = bigwig.chunk(
            'test.bigWig',
            12000,
            int(12000 / window_size),
            int(12000 / 6),
            ['chr1'],
            verbose=True,
        )
        # data = bbi.stackup(
        #     'test.bigWig',
        #     ['chr1'] * start_bps.size,
        #     start_bps,
        #     end_bps,
        #     bins=window_size,
        #     missing=0.0,
        #     oob=0.0,
        # )
        # data = (data - np.min(data))/np.ptp(data)
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
157
        print(data.shape)
158
        np.save('processed-data', data)
159
        np.savetxt('processed-data', data, delimiter=' ', fmt='%f')
160
    print('Windows created: ' + str(time()-t0))
161
    return '1'
162
163
164

@app.route('/create-tables', methods=['POST'])
def create_tables():
165
166
167
168
169
    data = np.load('processed-data.npy')
    raw_data = orjson.loads(request.data)
    window_size = int(raw_data['parameters']["windowsize"])
    hash_size = int(raw_data['parameters']["hashsize"])
    table_size = int(raw_data['parameters']["tablesize"])
170

171
    t0 = time()
172
173
    r, a, sd = preprocess()
    lsh_method(r, a, sd)
174
175
176
177
178
179
180
181
    hash_functions, tables = lsh(data, window_size, hash_size, table_size)

    response = {}
    for table_index in range(table_size):
        response[str(table_index)] = {
            "hash": hash_functions[table_index],
            "entries": tables[table_index]
        }
182
183
    response = jsonify(response)
    print('done: ' + str(time()-t0))
184
185
186
187
188
    return response


def lsh(data, window_size, hash_size, table_size):
    tables_hash_function = []
189
    tables = []
190
191
    print(data.shape)

192
    for index in range(table_size):
193
        signatures, hash_function = lsh_function(data, window_size=window_size, hash_size=hash_size)
194
        print(index)
195
196
197
        table = defaultdict(list)
        for v, k in enumerate(signatures):
            table[k].append(v)
198
        tables.append(table)
199
        tables_hash_function.append(hash_function.tolist())
200

201
202
203
204
205
206
207
208
209
210
211
212
    hash_functions = tables_hash_function
    return hash_functions, tables


@app.route('/similarity', methods=['POST'])
def similarity():
    t0 = time()
    raw_data = orjson.loads(request.data)
    window = raw_data['query']
    tables = raw_data["tables"]
    neighbours = []
    output = defaultdict(list)
213
    i = 0
214
    for t in tables.values():
215
216
217
218
        print(i)
        signatures, _ = lsh_function(window, hash_function=t["hash"])
        neighbours.extend(t["entries"][str(signatures[0])])
        i = i+1
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
    neighbours_with_frequency = dict(Counter(neighbours))
    for index, frequency in neighbours_with_frequency.items():
        output[str(frequency)].append(index)

    response = orjson.dumps(output)
    print("Similarity done: " + str(time()-t0))
    return response

@app.route('/update', methods=['POST'])
def update():
    t0 = time()
    raw_data = orjson.loads(request.data)
    data = np.load('processed-data.npy')
    label_data = raw_data["labelData"]
    tables = raw_data["tables"]
    window = raw_data["query"]
    window_size = int(raw_data['parameters']["windowsize"])
    hash_size = int(raw_data['parameters']["hashsize"])
    table_size = int(raw_data['parameters']["tablesize"])
    new_tables = []

    correct_indices = [int(index) for index, value in label_data.items() if value is True]
    incorrect_indices = [int(index) for index, value in label_data.items() if value is False]

    for t in tables.values():
        valid = True
245
246
        signatures, _ = lsh_function(window, hash_function=t['hash'])
        neighbours = t["entries"][str(signatures[0])]
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
        for index in correct_indices:
            if index not in neighbours:
                valid = False
                break
        for index in incorrect_indices:
            if index in neighbours:
                valid = False
                break
        if valid:
            new_tables.append(t)

    for index in range(table_size - len(new_tables)):
        entries = defaultdict(list)
        t1 = time()
        while True:
262
263
            correct_signatures, hash_function = lsh_function(data[correct_indices], window_size=window_size, hash_size=hash_size)
            incorrect_signatures, _ = lsh_function(data[incorrect_indices], hash_function=hash_function)
264
265
            if correct_signatures.count(correct_signatures[0]) == len(correct_signatures) and incorrect_signatures.count(correct_signatures[0]) == 0:
                break
266
        signatures, _ = lsh_function(data, hash_function=hash_function)
267
268
269
270
271
272
273
274
275
        for i in range(len(signatures)):
            entries[signatures[i]].append(i)
        print(str(index) + ": " + str(time() - t1))
        new_tables.append({
            "hash": hash_function.tolist(),
            "entries": entries
        })

    print('Update time: ' + str(time() - t0))
276
    response = {}
277
278
279
280
    for table_index in range(len(new_tables)):
        response[table_index] = {
            "hash": new_tables[table_index]["hash"],
            "entries": new_tables[table_index]["entries"]
281
        }
282
    response = jsonify(response)
283
284
    return response

285
286
@app.route('/query', methods=['POST'])
def query():
287
    t0 = time()
288
    raw_data = orjson.loads(request.data)
289
    window = raw_data['window']
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
290
    if isinstance(window, int):
291
        output = np.load('processed-data.npy')[window]
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
292
293
294
        response = orjson.dumps(output.tolist())
        print("Query done: " + str(time() - t0))
        return response
295
296
297
    else:
        print("OOOOOOOOOOOOOOOO")
        output = (window - np.min(window))/np.ptp(window)
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
298
299
300
301
302
303
304
305
306
307
        response = orjson.dumps(output.tolist())
        print("Query done: " + str(time()-t0))
        return response

@app.route('/window', methods=['POST'])
def window():
    t0 = time()
    raw_data = orjson.loads(request.data)
    indices = raw_data['indices']
    output = np.load('processed-data.npy')[indices]
308
    response = orjson.dumps(output.tolist())
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
309
    print("Query done: " + str(time() - t0))
310
311
312
313
314
315
316
317
318
319
    return response

@app.route('/average-progress', methods=['POST'])
def average_progress():
    t0 = time()
    raw_data = orjson.loads(request.data)
    all_windows = raw_data['windows']
    data = np.load('processed-data.npy')
    output = []
    actual_windows = []
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
320
    print("Starting average progress")
321
322
323
    print("Initialized: " + str(time() - t0))
    for windows in all_windows:
        t1 = time()
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
324
        actual_windows.extend(data[windows])
325
326
327
        if len(actual_windows) == 0:
            output.append([])
            continue
328
329
330
        max_values = np.maximum.reduce(actual_windows).tolist()
        min_values = np.minimum.reduce(actual_windows).tolist()
        average_values = (np.sum(actual_windows, 0)/len(actual_windows)).tolist()
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
331
        output = [({
332
333
334
            'average': average_values,
            'max': max_values,
            'min': min_values
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
335
        })] + output
336
337
338
        print("Average calculated: " + str(time() - t1))
    response = orjson.dumps(output)
    print("Averages calculated: " + str(time() - t0))
339
340
    return response

341
342
@app.route('/average-table', methods=['POST'])
def average_table():
343
344
345
346
347
    t0 = time()
    raw_data = orjson.loads(request.data)
    all_windows = raw_data['windows']
    data = np.load('processed-data.npy')
    output = []
348
    print("Initialized: " + str(time() - t0))
349
350
    for windows in all_windows:
        t1 = time()
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
351
        actual_windows = data[windows]
352
        print(len(actual_windows))
353
354
355
356
357
358
359
        average_values = np.average(actual_windows, 0)
        # average_values = (np.sum(actual_windows, 0) / len(actual_windows))
        std_values = np.std(actual_windows, 0)
        max_values = average_values + std_values
        min_values = average_values - std_values
        # max_values = np.maximum.reduce(actual_windows).tolist()
        # min_values = np.minimum.reduce(actual_windows).tolist()
360
        output.append({
361
362
363
            'average': average_values.tolist(),
            'max': max_values.tolist(),
            'min': min_values.tolist()
364
        })
365
366
        print("Average calculated: " + str(time() - t1))
    response = orjson.dumps(output)
367
    print("Averages calculated: " + str(time() - t0))
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
    return response

def preprocess():
    data = np.load('processed-data.npy')
    # data = np.array(data, dtype='double')
    # data = np.reshape(data, (int(len(data) / 1), 1, len(data[0])))
    # data = np.repeat(data, repeats=1, axis=1)
    subset = []
    # query = data[80503]
    t0 = time()
    # for i, window in enumerate(data):
    #     print(i)
    #     a = dtw.dtw(window, query, dist_method="Euclidean").distance
    # print(time() - t0)
    # print("done")

    r = 3
    for i, window in enumerate(data):
        if i % 10000 == 0:
            print(str(i) + ':' + str(len(subset)))
        state = 1
        for s in subset:
            if np.linalg.norm(window - data[s]) < r:
                state = 0
                break
        if state == 1:
            subset.append(i)

    #
    # subset = sample(list(range(len(data))), 50)
    # print(subset)
    dtw_distances = []
    eq_distances = []
    for i, index_1 in enumerate(subset):
        print(i)
        for j, index_2 in enumerate(subset):
            if index_1 == index_2:
                continue
            e = distance.euclidean(data[index_1], data[index_2])
            eq_distances.append(e)
            # d = dtw.dtw(data[index_1], data[index_2], dist_method="Euclidean", window_type="sakoechiba", window_args={"window_size": 6}).distance
            # print(d-e)
            # if (e != 0):
            #     dtw_distances.append(d)#(dtw.dtw(data[index_1], data[index_2], keep_internals=True).distance)
            #     eq_distances.append(e)
            # else:
            #     dtw_distances.append(0)
            #     eq_distances.append(1)
    # ratios = np.array(dtw_distances)/np.array(eq_distances)
    # mean_dtw = np.mean(dtw_distances)
    # sd_dtw = np.std(dtw_distances)
    mean_eq = np.mean(eq_distances)
    sd_eq = np.std(eq_distances)
    a=1
    sd=1
    # a = np.mean(ratios)
    # sd = np.std(ratios)
    # theta = mean_dtw + -2.58 * sd_dtw
    theta = mean_eq + -2.58 * sd_eq
    # r = theta / ((a-sd)*math.sqrt(120))
    r = theta / (math.sqrt(120))
    # print(mean_dtw)
    # print(sd_dtw)
    print(a)
    print(sd)
    print(theta)
    print(r)
    print(time() - t0)
    return r, a, sd

def dtw_query():
    data = np.load('processed-data.npy')
    data= np.array(data, dtype='double')
    data = np.repeat(data, repeats=1, axis=0)
    data = np.reshape(data, (int(len(data)/1), 1, len(data[0])))
    query = data[80503]
    t0 = time()
    for i, window in enumerate(data):
        print(i)
        alignment = dtw.dtw(query, window, keep_internals=True)
    print(time() - t0)

def lsh_method(r, a, sd):
    create_windows()
    query_n = 80503
    dim = 10
    data = np.load('processed-data.npy')
    data= np.array(data, dtype='double')
    data = np.reshape(data, (len(data), len(data[0]), 1))
    data = np.repeat(data, repeats=1, axis=2)
    query = data[query_n]
    candidates, hf = _lsh.lsh(data, query, r, a, sd)
    print(repr(candidates[0:10]))

    # data = np.load('processed-data.npy')
    # query = data[query_n]
    # distances = [_ucrdtw.ucrdtw(window, query, 0.05, False)[1] for window in data]
    # topk_dtw = sorted(range(len(distances)), key=lambda k: distances[k])
    # print(topk_dtw[0:10])

    distances_ed = [distance.euclidean(query, window) for window in data]
    topk_ed = sorted(range(len(distances_ed)), key=lambda k: distances_ed[k])

    accuracy = 0
    # for index in topk_dtw[0:50]:
    #     if index in candidates[0:50]:
    #         accuracy += 1
    # print(accuracy)

    accuracy = 0
    for index in topk_ed[0:20]:
        if index in candidates[0:20]:
            accuracy += 1
    print(accuracy)

    accuracy = 0
    for index in topk_ed[0:50]:
        if index in candidates[0:50]:
            accuracy += 1
    print(accuracy)

    # accuracy = 0
    # for index in topk_dtw[0:50]:
    #     if index in candidates[0:1000]:
    #         accuracy += 1
    # print(accuracy)
    #
    # accuracy = 0
    # for index in topk_dtw[0:50]:
    #     if index in candidates[0:5000]:
    #         accuracy += 1
    # print(accuracy)
    #
    # accuracy = 0
    # for index in topk_dtw[0:50]:
    #     if index in candidates[0:10000]:
    #         accuracy += 1
    # print(accuracy)
    #
    # accuracy = 0
    # for index in topk_dtw[0:50]:
    #     if index in candidates[0:50000]:
    #         accuracy += 1
    # print(accuracy)
    #
    # accuracy = 0
    # for index in topk_dtw[0:50]:
    #     if index in candidates:
    #         accuracy += 1
    # print(accuracy)

# r, a, sd = preprocess()
# lsh_method(r, a, sd)
# create_windows()
# query_n = 80503
# data = np.load('processed-data.npy')
# data= np.array(data, dtype='double')
# data = np.reshape(data, (len(data), len(data[0]), 1))
# data = np.repeat(data, repeats=10, axis=2)
# query = data[query_n]
# # candidates, hf = _lsh.lsh(data, query)
# # data = np.load('processed-data.npy')
# # query = data[query_n]
#
# data = np.load('processed-data.npy')
# print(_ucrdtw.ucrdtw(data[query_n], data[0], 0.05, False)[1])
#
# # l2_norm = lambda x, y: (x - y) ** 2
#
# data = np.load('processed-data.npy')
# data= np.array(data, dtype='double')
# data = np.repeat(data, repeats=1, axis=0)
# data = np.reshape(data, (int(len(data)/1), 1, len(data[0])))
# query = data[query_n]
# # distances = [_ucrdtw.ucrdtw(window, query, 0.05, False)[1] for window in data]
# # topk_dtw = sorted(range(len(distances)), key=lambda k: distances[k])
# # print(topk_dtw[0:10])
#
# # Generate our data
# template = data[query_n]
# rt,ct = template.shape
# rq,cq = query.shape
# t0 = time()
# # Calculate the alignment vector and corresponding distance
# alignment = dtw.dtw(query, template, keep_internals=True)
# print(alignment.distance)
#
# print(time()-t0)
# np.save('topk', np.array(topk_dtw))
print('done')
# topk_dtw = np.load('topk.npy')
# distances_ed = [distance.euclidean(query, window) for window in data]
# topk_ed = sorted(range(len(distances_ed)), key=lambda k: distances_ed[k])

#
#
# accuracy = 0
# for index in topk_dtw[0:50]:
#     if index in candidates[0:50]:
#         accuracy += 1
# print(accuracy)
# accuracy = 0
# output = []
# for index in topk_ed[0:50]:
#     if index in candidates:
#         accuracy += 1
# print(accuracy)
# accuracy = 0
# for index in topk_ed[0:50]:
#     if index in candidates[0:50]:
#         accuracy += 1
# print(accuracy)
# accuracy = 0
# for index in topk_ed[0:20]:
#     if index in candidates[0:20]:
#         accuracy += 1
# print(accuracy)