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2 |
+
|
3 |
+
NAMESPACE = 'wormmine'
|
4 |
+
NAMESPACE = 'mousemine'
|
5 |
+
NAMESPACE = 'flymine'
|
6 |
+
|
7 |
+
from opensearchpy import OpenSearch
|
8 |
+
from opensearch_dsl import Search
|
9 |
+
|
10 |
+
import opensearch_py_ml as oml
|
11 |
+
import pandas as pd
|
12 |
+
|
13 |
+
from os_credential import credentials
|
14 |
+
|
15 |
+
import json
|
16 |
+
from datetime import datetime
|
17 |
+
|
18 |
+
from intermine.webservice import Service
|
19 |
+
|
20 |
+
import time
|
21 |
+
|
22 |
+
def get_os_client():
|
23 |
+
|
24 |
+
(OS_HOST, OS_PORT, OS_USER, OS_PASSWORD) = credentials()
|
25 |
+
|
26 |
+
# Create the client with SSL/TLS enabled, but hostname verification disabled.
|
27 |
+
client = OpenSearch(
|
28 |
+
hosts = [{'host': OS_HOST, 'port': OS_PORT}],
|
29 |
+
http_compress = True, # enables gzip compression for request bodies
|
30 |
+
http_auth = (OS_USER, OS_PASSWORD),
|
31 |
+
use_ssl = True,
|
32 |
+
verify_certs = False,
|
33 |
+
ssl_assert_hostname = False,
|
34 |
+
ssl_show_warn = False
|
35 |
+
)
|
36 |
+
|
37 |
+
#print(client)
|
38 |
+
|
39 |
+
return client
|
40 |
+
|
41 |
+
os_client = get_os_client()
|
42 |
+
os_client
|
43 |
+
|
44 |
+
oml_classes = oml.DataFrame(os_client, 'intermine-classe')
|
45 |
+
oml_classes.shape
|
46 |
+
|
47 |
+
pd_classes = oml.opensearch_to_pandas(oml_classes)
|
48 |
+
pd_classes.shape
|
49 |
+
pd_classes
|
50 |
+
|
51 |
+
pd_classes_name = pd_classes.get(['classe', 'namespace', 'count']).query('namespace == "'+NAMESPACE+'"').sort_values('classe')
|
52 |
+
print('max', pd_classes_name['count'].max())
|
53 |
+
print('sum', pd_classes_name['count'].sum())
|
54 |
+
#pd_classes_name
|
55 |
+
|
56 |
+
list_classes_name = pd_classes_name.values.tolist()
|
57 |
+
list_classes_name
|
58 |
+
|
59 |
+
def list2doc(data_views):
|
60 |
+
data_obj = {}
|
61 |
+
for i in range(0, len(data_views['data'])):
|
62 |
+
key = data_views['views'][i]
|
63 |
+
key = key.split('.')[1]
|
64 |
+
value = data_views['data'][i]
|
65 |
+
#print(key, value)
|
66 |
+
|
67 |
+
if not value is None:
|
68 |
+
data_obj[key] = value
|
69 |
+
|
70 |
+
return data_obj
|
71 |
+
|
72 |
+
test = {'data': [1, '(3R)-3-hydroxyacyl-CoA dehydrogenase', None, 13396260, True], 'views': ['UniProtFeature.begin', 'UniProtFeature.description', 'UniProtFeature.end', 'UniProtFeature.id', 'UniProtFeature.type'], 'index_map': None}
|
73 |
+
list2doc(test)
|
74 |
+
|
75 |
+
def clase2obj(intermine_service, intermine_class_name, end_pos=10, start_pos=0):
|
76 |
+
|
77 |
+
query = intermine_service.new_query(intermine_class_name)
|
78 |
+
|
79 |
+
ctr = 0
|
80 |
+
for row in query.rows():
|
81 |
+
ctr += 1
|
82 |
+
if ctr < start_pos:
|
83 |
+
continue
|
84 |
+
if ctr > end_pos:
|
85 |
+
break
|
86 |
+
|
87 |
+
#print(row["diseaseId"], row["diseaseType"], row["name"], row["primaryIdentifier"], row["alleles.primaryIdentifier"], row["genes.primaryIdentifier"])
|
88 |
+
row_dict = list2doc(row.__dict__)
|
89 |
+
#print(row_dict)
|
90 |
+
|
91 |
+
yield row_dict, ctr
|
92 |
+
|
93 |
+
#for (row_dict, ctr) in clase2obj(intermine_service, 'CrossReference', end_pos=100*1000*1000, start_pos=0):
|
94 |
+
# pass
|
95 |
+
#print(ctr)
|
96 |
+
|
97 |
+
class OSBulkBuffer:
|
98 |
+
"""
|
99 |
+
A fixed-size buffer class that overwrites the oldest element when full.
|
100 |
+
"""
|
101 |
+
def __init__(self, size, length, index_name, os_connection, debug_mode=False):
|
102 |
+
"""
|
103 |
+
Initializes the buffer with a specified size.
|
104 |
+
|
105 |
+
Args:
|
106 |
+
size (int): The maximum number of elements the buffer can hold.
|
107 |
+
"""
|
108 |
+
self.buffer = []
|
109 |
+
self.str_length = 0
|
110 |
+
self.head = 0 # Index of the element to be overwritten on next insertion
|
111 |
+
|
112 |
+
self.max_size = size
|
113 |
+
self.max_length = length
|
114 |
+
self.index = index_name
|
115 |
+
self.connection = os_connection
|
116 |
+
self.debug_mode = debug_mode
|
117 |
+
|
118 |
+
def is_full(self):
|
119 |
+
"""
|
120 |
+
Checks if the buffer is at its maximum capacity.
|
121 |
+
|
122 |
+
Returns:
|
123 |
+
bool: True if the buffer is full, False otherwise.
|
124 |
+
"""
|
125 |
+
return len(self.buffer) == self.max_size
|
126 |
+
|
127 |
+
def transmit(self):
|
128 |
+
"""
|
129 |
+
Checks if the buffer is at its maximum capacity.
|
130 |
+
|
131 |
+
Returns:
|
132 |
+
bool: True if the buffer is full, False otherwise.
|
133 |
+
"""
|
134 |
+
#print('plein', self.head)
|
135 |
+
|
136 |
+
os_buffer = ''
|
137 |
+
|
138 |
+
for doc in self.buffer:
|
139 |
+
#print(doc)
|
140 |
+
#response = self.connection.index(index=self.index, body=doc, id=doc['doc_id'])
|
141 |
+
#print(response)
|
142 |
+
|
143 |
+
operation = { "index" : { "_index" : self.index, "_id" : doc['doc_id'] } }
|
144 |
+
os_buffer = os_buffer + '\n' + json.dumps(operation) + '\n' + json.dumps(doc)
|
145 |
+
|
146 |
+
try:
|
147 |
+
response = self.connection.bulk(os_buffer)
|
148 |
+
if self.debug_mode:
|
149 |
+
print(response)
|
150 |
+
except:
|
151 |
+
print("OS retry 3 minutes")
|
152 |
+
time.sleep(180)
|
153 |
+
response = self.connection.bulk(os_buffer)
|
154 |
+
if self.debug_mode:
|
155 |
+
print(response)
|
156 |
+
|
157 |
+
|
158 |
+
self.buffer = []
|
159 |
+
#print(self.buffer)
|
160 |
+
self.str_length = 0
|
161 |
+
self.head = 0
|
162 |
+
|
163 |
+
def put(self, data):
|
164 |
+
"""
|
165 |
+
Adds an element to the buffer. If full, overwrites the oldest element.
|
166 |
+
|
167 |
+
Args:
|
168 |
+
data: The data to be added to the buffer.
|
169 |
+
"""
|
170 |
+
if self.is_full():
|
171 |
+
self.transmit()
|
172 |
+
|
173 |
+
self.head += 1
|
174 |
+
|
175 |
+
self.buffer.append(data)
|
176 |
+
#print(len(self.buffer))
|
177 |
+
|
178 |
+
def close(self):
|
179 |
+
"""
|
180 |
+
Retrieves the most recently added element from the buffer.
|
181 |
+
|
182 |
+
Returns:
|
183 |
+
any: The data from the buffer, or None if empty.
|
184 |
+
"""
|
185 |
+
|
186 |
+
if self.head == 0:
|
187 |
+
return None
|
188 |
+
else:
|
189 |
+
self.transmit()
|
190 |
+
self.connection.close()
|
191 |
+
|
192 |
+
print('close')
|
193 |
+
|
194 |
+
return self.connection
|
195 |
+
|
196 |
+
|
197 |
+
service_taxon = NAMESPACE
|
198 |
+
class_name = 'Sequence'
|
199 |
+
|
200 |
+
services = {}
|
201 |
+
services['humanmine'] = "https://www.humanmine.org/humanmine/service"
|
202 |
+
services['flymine'] = "https://www.flymine.org/flymine/service"
|
203 |
+
|
204 |
+
services['mousemine'] = "https://www.mousemine.org/mousemine/service"
|
205 |
+
|
206 |
+
services['wormmine'] = "http://intermine.wormbase.org/tools/wormmine/service"
|
207 |
+
|
208 |
+
intermine_service = Service(services[NAMESPACE])
|
209 |
+
#service = Service("https://www.wormmine.org/wormmine/service")
|
210 |
+
|
211 |
+
# Get a new query on the class (table) you will be querying:
|
212 |
+
query = intermine_service.new_query(class_name)
|
213 |
+
|
214 |
+
log_freq = 100*1000
|
215 |
+
namespace = NAMESPACE
|
216 |
+
|
217 |
+
my_buffer = OSBulkBuffer(1000, 10000000, 'intermine-' + namespace + '-object', os_client, False)
|
218 |
+
|
219 |
+
for class1 in list_classes_name:
|
220 |
+
print(NAMESPACE, class1[0], class1[2])
|
221 |
+
class_name = class1[0]
|
222 |
+
namespace = class1[1]
|
223 |
+
|
224 |
+
if class_name < 'ZZZ':
|
225 |
+
continue
|
226 |
+
|
227 |
+
for (row_dict, ctr) in clase2obj(intermine_service, class_name, end_pos=100*1000*1000, start_pos=0):
|
228 |
+
|
229 |
+
row_dict['doc_id'] = namespace + '-' + class_name + '-' + str(row_dict['id'])
|
230 |
+
row_dict['timestamp'] = datetime.utcnow().isoformat()
|
231 |
+
|
232 |
+
my_buffer.put(row_dict)
|
233 |
+
if ctr % log_freq == 0 or ctr == 1:
|
234 |
+
print('clase2obj', NAMESPACE, ctr, datetime.utcnow().isoformat())
|
235 |
+
|
236 |
+
my_buffer.close()
|