main.py 11.1 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
from scipy.sparse import dia_matrix
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
17

18
reload = True
19
20
21
22

app = Flask(__name__)
CORS(app)

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
    signatures_int = np.packbits(signatures_bool)
    return signatures_int.tolist(), hash_function

39
def calculate_signatures_new(data, window_size=None, hash_size=None, hash_function=None):
40
41
    if hash_function is None:
        hash_function = np.array([np.cumsum(np.random.uniform(-1, 1, window_size)) for _ in range(hash_size)]).transpose()
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
    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()
67
68
    return signatures_int.tolist(), hash_function

69
70

lsh_function = calculate_signatures_new
71

72
73
74
75
76
77
@app.route('/', methods=['GET'])
def index():
    return "hi"

@app.route('/read-data', methods=['GET'])
def read_data():
78
    t0 = time()
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
79
80
81
82
    size = bbi.chromsizes('test.bigWig')['chr1']
    bins = 100000
    data = bigwig.get('test.bigWig', 'chr1', 0, size, bins)
    print(data.shape)
83
    response = {
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
84
85
        "index": list(range(0, size, int(size/(bins)))),
        "values": data.tolist()
86
    }
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
87
    response = orjson.dumps(response)
88
    print('Data read: ' + str(time()-t0))
89
90
91
92
    # query = data[12000:24000]
    # loc, dist = _ucrdtw.ucrdtw(data, query, 0.05, True)
    # print(data[loc:loc+120])
    # print('found query: ' + str(loc) + '[' + str(time()-t0) + ']')
93
94
95
96
    return response

@app.route('/create-windows', methods=['POST'])
def create_windows():
97
    t0 = time()
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
98
    if reload:
99
100
        raw_data = request.json
        window_size = int(raw_data['parameters']["windowsize"])
101
102
103
104
        chromsize = bbi.chromsizes('test.bigWig')['chr1']
        step_size = chromsize / 10000
        data = bigwig.get('test.bigWig', 'chr1', 0, chromsize, 20000000)
        data = (data - np.min(data))/np.ptp(data)
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
105
        print(data.shape)
106
        np.save('processed-data', data)
107
    print('Windows created: ' + str(time()-t0))
108
    return '1'
109
110
111

@app.route('/create-tables', methods=['POST'])
def create_tables():
112
113
114
115
116
    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"])
117

118
    t0 = time()
119
120
121
122
123
124
125
126
    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]
        }
127
128
    response = jsonify(response)
    print('done: ' + str(time()-t0))
129
130
131
132
133
    return response


def lsh(data, window_size, hash_size, table_size):
    tables_hash_function = []
134
    tables = []
135
136
    print(data.shape)

137
    for index in range(table_size):
138
        signatures, hash_function = lsh_function(data, window_size=window_size, hash_size=hash_size)
139
140
141
142
        print('creating dictionary')
        table = defaultdict(list)
        for v, k in enumerate(signatures):
            table[k].append(v)
143
        tables.append(table)
144
        tables_hash_function.append(hash_function.tolist())
145

146
147
148
149
150
151
152
153
154
155
156
157
158
159
    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)

    for t in tables.values():
160
        signature = lsh_function(window, hash_function=t["hash"])
161
        neighbours.extend(t["entries"][str(signature)])
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
    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
188
        signature = lsh_function(window, hash_function=t['hash'])
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
        neighbours = t["entries"][signature]
        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:
205
206
            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)
207
208
            if correct_signatures.count(correct_signatures[0]) == len(correct_signatures) and incorrect_signatures.count(correct_signatures[0]) == 0:
                break
209
        signatures, _ = lsh_function(data, hash_function=hash_function)
210
211
212
213
214
215
216
217
218
        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))
219
    response = {}
220
221
222
223
    for table_index in range(len(new_tables)):
        response[table_index] = {
            "hash": new_tables[table_index]["hash"],
            "entries": new_tables[table_index]["entries"]
224
        }
225
    response = jsonify(response)
226
227
    return response

228
229
@app.route('/query', methods=['POST'])
def query():
230
    t0 = time()
231
    raw_data = orjson.loads(request.data)
232
    window = raw_data['window']
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
233
    if isinstance(window, int):
234
        output = np.load('processed-data.npy')[window:window+12000]
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
        response = orjson.dumps(output.tolist())
        print("Query done: " + str(time() - t0))
        return response
    else :
        output = preprocessing.minmax_scale(window, (-1, 1))
        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]
250
    response = orjson.dumps(output.tolist())
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
251
    print("Query done: " + str(time() - t0))
252
253
254
255
256
257
258
259
260
261
    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
262
    print("Starting average progress")
263
264
265
    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
266
        actual_windows.extend(data[windows])
267
268
269
        if len(actual_windows) == 0:
            output.append([])
            continue
270
271
272
        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
273
        output = [({
274
275
276
            'average': average_values,
            'max': max_values,
            'min': min_values
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
277
        })] + output
278
279
280
        print("Average calculated: " + str(time() - t1))
    response = orjson.dumps(output)
    print("Averages calculated: " + str(time() - t0))
281
282
    return response

283
284
@app.route('/average-table', methods=['POST'])
def average_table():
285
286
287
288
289
    t0 = time()
    raw_data = orjson.loads(request.data)
    all_windows = raw_data['windows']
    data = np.load('processed-data.npy')
    output = []
290
    print("Initialized: " + str(time() - t0))
291
292
    for windows in all_windows:
        t1 = time()
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
293
        actual_windows = data[windows]
294
        print(len(actual_windows))
295
296
297
298
299
300
301
        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()
302
        output.append({
303
304
305
            'average': average_values.tolist(),
            'max': max_values.tolist(),
            'min': min_values.tolist()
306
        })
307
308
        print("Average calculated: " + str(time() - t1))
    response = orjson.dumps(output)
309
    print("Averages calculated: " + str(time() - t0))
310
    return response