chemotion-api 0.3.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- chemotion_api/__init__.py +243 -0
- chemotion_api/admin/__init__.py +23 -0
- chemotion_api/collection.py +395 -0
- chemotion_api/connection.py +65 -0
- chemotion_api/element_manager.py +123 -0
- chemotion_api/elements/__init__.py +125 -0
- chemotion_api/elements/abstract_element.py +307 -0
- chemotion_api/elements/empty_elements/__init__.py +20 -0
- chemotion_api/elements/empty_elements/container.json +12 -0
- chemotion_api/elements/empty_elements/reaction.json +41 -0
- chemotion_api/elements/empty_elements/research_plan.json +12 -0
- chemotion_api/elements/empty_elements/sample.json +44 -0
- chemotion_api/elements/empty_elements/solvents.json +762 -0
- chemotion_api/elements/empty_elements/wellplate.json +11 -0
- chemotion_api/elements/generic_element.py +22 -0
- chemotion_api/elements/reaction.py +163 -0
- chemotion_api/elements/research_plan.py +13 -0
- chemotion_api/elements/sample.py +245 -0
- chemotion_api/elements/wellplate.py +70 -0
- chemotion_api/generic_segments.py +31 -0
- chemotion_api/user.py +197 -0
- chemotion_api/utils/__init__.py +160 -0
- chemotion_api/utils/solvent_manager.py +16 -0
- chemotion_api-0.3.3.dist-info/METADATA +462 -0
- chemotion_api-0.3.3.dist-info/RECORD +26 -0
- chemotion_api-0.3.3.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import typing
|
|
2
|
+
|
|
3
|
+
from typing import TypeVar
|
|
4
|
+
|
|
5
|
+
from chemotion_api.collection import RootCollection
|
|
6
|
+
from chemotion_api.element_manager import ElementManager
|
|
7
|
+
from chemotion_api.user import User, Admin, Person, Device, Group, DeviceManager
|
|
8
|
+
from requests.exceptions import ConnectionError
|
|
9
|
+
|
|
10
|
+
from chemotion_api.elements import ElementSet, Wellplate, Sample, Reaction, GenericElement, ResearchPlan
|
|
11
|
+
from chemotion_api.elements.sample import MoleculeManager
|
|
12
|
+
from chemotion_api.connection import Connection
|
|
13
|
+
|
|
14
|
+
TInstance = TypeVar("TInstance", bound="Instance")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Instance:
|
|
18
|
+
""" The instance object is the core object of the Chemotion API. In order for the API to work,
|
|
19
|
+
a connection to a Chmotion (server-)iEBUG http://193.196.38.77:80 "GET /api/v1/collections/roots.json HTTP/1.1" 401 28
|
|
20
|
+
FAILED [ 16%]
|
|
21
|
+
test_collection.py:63 (test_get_create_collection)
|
|
22
|
+
logged_in_instance = <chemotion_api.Instance object at 0x7f3cc1a05e40>
|
|
23
|
+
|
|
24
|
+
def test_get_creanstance must first be established.
|
|
25
|
+
an Instance object manges such a connection. To initializes an instance it needs
|
|
26
|
+
the host URL of the chemotion server as a string.
|
|
27
|
+
|
|
28
|
+
:param host_url: URL for the new :class:`Request` object
|
|
29
|
+
|
|
30
|
+
Usage::
|
|
31
|
+
|
|
32
|
+
>>> from chemotion_api import Instance
|
|
33
|
+
>>> from requests.exceptions import ConnectionError as CE
|
|
34
|
+
>>> import logging
|
|
35
|
+
>>> try:
|
|
36
|
+
>>> s = Instance('http(d)://xxx.xxx.xxx').test_connection().login('<USER>', "<PASSWORD>")
|
|
37
|
+
>>> except CE as e:
|
|
38
|
+
>>> logging.error(f"A connection to Chemotion ({s.host_url}) cannot be established")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, host_url: str):
|
|
44
|
+
self._con = Connection(host_url)
|
|
45
|
+
self._root_col = None
|
|
46
|
+
self.element_manager = ElementManager(self._con)
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def host_url(self):
|
|
50
|
+
return self._con.host_url
|
|
51
|
+
|
|
52
|
+
def test_connection(self) -> TInstance:
|
|
53
|
+
"""
|
|
54
|
+
This test_connection methode simply test if the connection to a chemotion instance can be established.
|
|
55
|
+
The instance does not need to be logged in to use this methode.
|
|
56
|
+
|
|
57
|
+
:return: the instance self
|
|
58
|
+
|
|
59
|
+
:raises ConnectionError (requests.exceptions.ConnectionError) if the connection cannot be established.
|
|
60
|
+
"""
|
|
61
|
+
ping_url = "/api/v1/public/ping"
|
|
62
|
+
res = self._con.get(url_path=ping_url)
|
|
63
|
+
if res.status_code != 204:
|
|
64
|
+
raise ConnectionError('Could not ping the Chemotion instance: {}'.format(self.host_url))
|
|
65
|
+
return self
|
|
66
|
+
|
|
67
|
+
def login(self, user: str, password: str) -> TInstance:
|
|
68
|
+
"""
|
|
69
|
+
This login methode allows you to log in to a chemotion instance.
|
|
70
|
+
Hence, you need a valid chemotion user (abbreviation name or e-mail)
|
|
71
|
+
|
|
72
|
+
:param user: abbreviation name or e-mail of a chemotion user
|
|
73
|
+
:param password: The password of the user
|
|
74
|
+
|
|
75
|
+
:return: the instance self
|
|
76
|
+
|
|
77
|
+
:raise ConnectionError (requests.exceptions.ConnectionError) if the logging was not successful.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
payload = {'username': user, 'password': password}
|
|
81
|
+
login_url = "/api/v1/public/token"
|
|
82
|
+
|
|
83
|
+
res = self._con.post(url_path=login_url,
|
|
84
|
+
headers=self._con.get_default_session_header(),
|
|
85
|
+
data=payload)
|
|
86
|
+
|
|
87
|
+
if res.status_code != 201:
|
|
88
|
+
raise PermissionError('Could not login!!')
|
|
89
|
+
self._con.set_bearer_token(res.json()['token'])
|
|
90
|
+
return self
|
|
91
|
+
|
|
92
|
+
def login_token(self, jwt_token: str) -> TInstance:
|
|
93
|
+
"""
|
|
94
|
+
This login_token methode allows you to log in to a chemotion instance.
|
|
95
|
+
Hence, you need a valid chemotion jwt token. This token can be generated by the
|
|
96
|
+
get_token methode.
|
|
97
|
+
|
|
98
|
+
:param jwt_token: a Java Web Token.
|
|
99
|
+
|
|
100
|
+
:return: the instance self
|
|
101
|
+
|
|
102
|
+
:raise ConnectionError (requests.exceptions.ConnectionError) if the logging was not successful.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
self._con.set_bearer_token(jwt_token)
|
|
106
|
+
return self
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def token(self) -> str:
|
|
110
|
+
"""
|
|
111
|
+
The token property returns the JWT (java web token)
|
|
112
|
+
|
|
113
|
+
:return: JWT
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
return self._con.bearer_token
|
|
117
|
+
|
|
118
|
+
def get_user(self) -> Admin|Person|Group|Device:
|
|
119
|
+
"""
|
|
120
|
+
This get_user methode initializes a new User object. The user object allows you to fetch and edit user data.
|
|
121
|
+
|
|
122
|
+
:return: a new User instance
|
|
123
|
+
|
|
124
|
+
:raise PermissionError: if the userdata cannot be fetched. Make sure that you are logged in.
|
|
125
|
+
"""
|
|
126
|
+
u = User.load_me(self._con)
|
|
127
|
+
return u
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def device_manager(self):
|
|
132
|
+
return DeviceManager(self._con)
|
|
133
|
+
|
|
134
|
+
def get_root_collection(self, reload=True) -> RootCollection:
|
|
135
|
+
if reload or self._root_col is None:
|
|
136
|
+
self._root_col = RootCollection(self._con)
|
|
137
|
+
self._root_col.set_element_manager(self.element_manager)
|
|
138
|
+
self._root_col.load_collection()
|
|
139
|
+
self._root_col.load_sync_collection()
|
|
140
|
+
return self._root_col
|
|
141
|
+
|
|
142
|
+
@property
|
|
143
|
+
def all_element_classes(self) -> dict[str, dict[str, str]]:
|
|
144
|
+
"""
|
|
145
|
+
This all_element_classes fetches all information about all elements such as
|
|
146
|
+
Sample, Reaction, Wellplate and Research plan and all generic elements
|
|
147
|
+
|
|
148
|
+
:return: a dictionary which contains all information about all elements
|
|
149
|
+
|
|
150
|
+
:raise RequestException: (requests.exceptions.RequestException) if the information cannot be fetched. Make sure that your connection is active and you are logged in.
|
|
151
|
+
"""
|
|
152
|
+
return self.element_manager.all_classes
|
|
153
|
+
|
|
154
|
+
def get_reaction(self, id: int) -> Reaction:
|
|
155
|
+
"""
|
|
156
|
+
Fetches data of one Reaction object from the Chemotion server.
|
|
157
|
+
It automatically parses the data into a Python-Reaction-Object. However, you need to know the correct internally used ID
|
|
158
|
+
of the Reaction to be able to fetch it. Other methods to get Elements from Chemotion
|
|
159
|
+
are accessible via the Collection objects
|
|
160
|
+
|
|
161
|
+
:param id: The Database ID of the desired Element
|
|
162
|
+
:return: a Reacton object
|
|
163
|
+
|
|
164
|
+
:raises RequestException: (requests.exceptions.RequestException) if the information cannot be fetched. Make sure that your connection is active and you are logged in.
|
|
165
|
+
"""
|
|
166
|
+
e = ElementSet(self._con, self.all_element_classes.get('reaction'))
|
|
167
|
+
return typing.cast(Reaction, e.load_element(id))
|
|
168
|
+
|
|
169
|
+
def get_wellplate(self, id: int) -> Wellplate:
|
|
170
|
+
"""
|
|
171
|
+
Fetches data of one Wellplate object from the Chemotion server.
|
|
172
|
+
It automatically parses the data into a Python-Wellplate-Object. However, you need to know the correct internally used ID
|
|
173
|
+
of the Wellplate to be able to fetch it. Other methods to get Elements from Chemotion
|
|
174
|
+
are accessible via the Collection objects
|
|
175
|
+
|
|
176
|
+
:param id: The Database ID of the desired Element
|
|
177
|
+
:return: a Reacton object
|
|
178
|
+
|
|
179
|
+
:raises RequestException: (requests.exceptions.RequestException) if the information cannot be fetched. Make sure that your connection is active and you are logged in.
|
|
180
|
+
"""
|
|
181
|
+
e = ElementSet(self._con, self.all_element_classes.get('wellplate'))
|
|
182
|
+
return typing.cast(Wellplate, e.load_element(id))
|
|
183
|
+
|
|
184
|
+
def get_research_plan(self, id: int) -> ResearchPlan:
|
|
185
|
+
"""
|
|
186
|
+
Fetches data of one Research Plan object from the Chemotion server.
|
|
187
|
+
It automatically parses the data into a Python-ResearchPlan-Object. However, you need to know the correct internally used ID
|
|
188
|
+
of the Research Plan to be able to fetch it. Other methods to get Elements from Chemotion
|
|
189
|
+
are accessible via the Collection objects
|
|
190
|
+
|
|
191
|
+
:param id: The Database ID of the desired Element
|
|
192
|
+
:return: a ResearchPlan object
|
|
193
|
+
|
|
194
|
+
:raises RequestException: (requests.exceptions.RequestException) if the information cannot be fetched. Make sure that your connection is active and you are logged in.
|
|
195
|
+
"""
|
|
196
|
+
e = ElementSet(self._con, self.all_element_classes.get('research_plan'))
|
|
197
|
+
return typing.cast(ResearchPlan, e.load_element(id))
|
|
198
|
+
|
|
199
|
+
def get_sample(self, id: int) -> Sample:
|
|
200
|
+
"""
|
|
201
|
+
Fetches data of one Sample object from the Chemotion server.
|
|
202
|
+
It automatically parses the data into a Python-Sample-Object. However, you need to know the correct internally used ID
|
|
203
|
+
of the Sample to be able to fetch it. Other methods to get Elements from Chemotion
|
|
204
|
+
are accessible via the Collection objects
|
|
205
|
+
|
|
206
|
+
:param id: The Database ID of the desired Element
|
|
207
|
+
:return: a Sample object
|
|
208
|
+
|
|
209
|
+
:raises RequestException: (requests.exceptions.RequestException) if the information cannot be fetched. Make sure that your connection is active and you are logged in.
|
|
210
|
+
"""
|
|
211
|
+
e = ElementSet(self._con, self.all_element_classes.get('sample'))
|
|
212
|
+
return typing.cast(Sample, e.load_element(id))
|
|
213
|
+
|
|
214
|
+
def get_generic_by_name(self, name: str, id: int) -> GenericElement:
|
|
215
|
+
"""
|
|
216
|
+
Fetches data of one Generic object from the Chemotion server. Which generic element type
|
|
217
|
+
It automatically parses the data into a Python-Generic-Object. However, you need to know the correct internally used ID
|
|
218
|
+
of the Generic element to be able to fetch it. Other methods to get Elements from Chemotion
|
|
219
|
+
are accessible via the Collection objects
|
|
220
|
+
|
|
221
|
+
:param name: The name of the Genetic Element
|
|
222
|
+
:param id: The Database ID of the desired Element
|
|
223
|
+
:return: a Sample object
|
|
224
|
+
|
|
225
|
+
:raises RequestException: (requests.exceptions.RequestException) if the information cannot be fetched. Make sure that your connection is active and you are logged in.
|
|
226
|
+
"""
|
|
227
|
+
elem = self.all_element_classes.get(name)
|
|
228
|
+
if elem is None:
|
|
229
|
+
raise ValueError(f'Could not find a generic element under the name: "{name}"')
|
|
230
|
+
e = ElementSet(self._con, elem)
|
|
231
|
+
return typing.cast(GenericElement, e.load_element(id))
|
|
232
|
+
|
|
233
|
+
def get_generic_by_label(self, label, id) -> GenericElement:
|
|
234
|
+
for (elem_name, elem) in self.all_element_classes.items():
|
|
235
|
+
if elem['label'] == label:
|
|
236
|
+
return self.get_generic_by_name(elem_name, id)
|
|
237
|
+
raise ValueError(f'Could not find a generic element with the label: "{label}"')
|
|
238
|
+
|
|
239
|
+
def molecule(self):
|
|
240
|
+
return MoleculeManager(self._con)
|
|
241
|
+
|
|
242
|
+
def get_solvent_list(self):
|
|
243
|
+
return list(ElementManager.get_solvent_list().keys())
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from chemotion_api.connection import Connection
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class AdminMenu:
|
|
5
|
+
def __init__(self, session: Connection):
|
|
6
|
+
self._session = session
|
|
7
|
+
|
|
8
|
+
def greate_device(self, first_name: str, last_name: str, name_abbreviation: str):
|
|
9
|
+
payload = {'first_name': first_name,
|
|
10
|
+
'last_name': last_name,
|
|
11
|
+
'rootType': "Device",
|
|
12
|
+
"name_abbreviation": name_abbreviation}
|
|
13
|
+
|
|
14
|
+
res = self._session.post('/api/v1/admin/group_device/create',
|
|
15
|
+
headers=self._session.get_default_session_header(),
|
|
16
|
+
data=payload)
|
|
17
|
+
|
|
18
|
+
if res.status_code == 401:
|
|
19
|
+
raise PermissionError('Not allowed to greate device (only Admin)')
|
|
20
|
+
elif res.status_code != 201 and res.status_code != 200:
|
|
21
|
+
raise ConnectionError(f"Error ({res.status_code}) \n{res.text}")
|
|
22
|
+
|
|
23
|
+
return res.json()
|
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
from random import random
|
|
4
|
+
from typing import TypeVar
|
|
5
|
+
|
|
6
|
+
from chemotion_api.elements.sample import MoleculeManager
|
|
7
|
+
from chemotion_api.connection import Connection
|
|
8
|
+
|
|
9
|
+
from chemotion_api.element_manager import ElementManager
|
|
10
|
+
from chemotion_api.elements import ElementSet, AbstractElement
|
|
11
|
+
|
|
12
|
+
TAbstractCollection = TypeVar("TAbstractCollection", bound="AbstractCollection")
|
|
13
|
+
TRootCollection = TypeVar("TRootCollection", bound="RootCollection")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class AbstractCollection:
|
|
17
|
+
children: list[TAbstractCollection]
|
|
18
|
+
label: str = None
|
|
19
|
+
_parent: TAbstractCollection = None
|
|
20
|
+
id: int = None
|
|
21
|
+
|
|
22
|
+
@classmethod
|
|
23
|
+
def prepare_label(cls, label: str, case_insensitive):
|
|
24
|
+
if case_insensitive:
|
|
25
|
+
return label.lower()
|
|
26
|
+
return label
|
|
27
|
+
|
|
28
|
+
def __init__(self):
|
|
29
|
+
self.children = []
|
|
30
|
+
self.is_sync = False
|
|
31
|
+
|
|
32
|
+
def __str__(self) -> str:
|
|
33
|
+
return self.get_path()
|
|
34
|
+
|
|
35
|
+
def __iter__(self):
|
|
36
|
+
yield ('collections', self.children)
|
|
37
|
+
|
|
38
|
+
def _set_children(self, new_children: list[dict]):
|
|
39
|
+
if new_children is None:
|
|
40
|
+
self.children = []
|
|
41
|
+
return
|
|
42
|
+
ids = []
|
|
43
|
+
for child in new_children:
|
|
44
|
+
ids.append(child['id'])
|
|
45
|
+
child_obj: TAbstractCollection | None = next((x for x in self.children if x.id == child['id']), None)
|
|
46
|
+
if child_obj is None:
|
|
47
|
+
self.children.append(Collection(child))
|
|
48
|
+
else:
|
|
49
|
+
child_obj.set_json(child)
|
|
50
|
+
self.children = [child_obj for child_obj in self.children if child_obj.id in ids]
|
|
51
|
+
self._update_relations()
|
|
52
|
+
|
|
53
|
+
def _update_relations(self):
|
|
54
|
+
for child in self.children:
|
|
55
|
+
child._parent = self
|
|
56
|
+
child.is_sync = self.is_sync
|
|
57
|
+
child._update_relations()
|
|
58
|
+
|
|
59
|
+
def to_json(self) -> dict:
|
|
60
|
+
return {'children': [x.to_json() for x in self.children]}
|
|
61
|
+
|
|
62
|
+
def find(self, label: str = None, **kwargs) -> list[TAbstractCollection]:
|
|
63
|
+
results: list[AbstractCollection] = []
|
|
64
|
+
if label is not None: kwargs['label'] = label
|
|
65
|
+
hit = True
|
|
66
|
+
for (key, val) in kwargs.items():
|
|
67
|
+
if getattr(self, key) != val:
|
|
68
|
+
hit = False
|
|
69
|
+
break
|
|
70
|
+
if hit:
|
|
71
|
+
results.append(self)
|
|
72
|
+
for x in self.children:
|
|
73
|
+
results += x.find(**kwargs)
|
|
74
|
+
return results
|
|
75
|
+
|
|
76
|
+
def get_path(self) -> str:
|
|
77
|
+
abs_path = []
|
|
78
|
+
col = self
|
|
79
|
+
while col._parent is not None:
|
|
80
|
+
abs_path.append(col.label)
|
|
81
|
+
col = col._parent
|
|
82
|
+
abs_path.append('')
|
|
83
|
+
abs_path.reverse()
|
|
84
|
+
return '/'.join(abs_path)
|
|
85
|
+
|
|
86
|
+
def get_root(self) -> TRootCollection:
|
|
87
|
+
col = self
|
|
88
|
+
while col._parent is not None:
|
|
89
|
+
col = col._parent
|
|
90
|
+
return col
|
|
91
|
+
|
|
92
|
+
def get_collection(self, col_path: str | list[str], case_insensitive: bool = False) -> TAbstractCollection | None:
|
|
93
|
+
abs_path = self.get_path()
|
|
94
|
+
if col_path.__class__ is not str:
|
|
95
|
+
col_path = '/'.join(col_path)
|
|
96
|
+
return self.get_root().get_collection(os.path.join(abs_path, col_path), case_insensitive)
|
|
97
|
+
|
|
98
|
+
def get_or_create_collection(self, col_path: str | list[str],
|
|
99
|
+
case_insensitive: bool = False) -> TAbstractCollection:
|
|
100
|
+
try:
|
|
101
|
+
return self.get_collection(col_path, case_insensitive)
|
|
102
|
+
except:
|
|
103
|
+
new_col = self.add_collection(col_path)
|
|
104
|
+
root = self.get_root()
|
|
105
|
+
new_path = new_col.get_path()
|
|
106
|
+
root.save()
|
|
107
|
+
return root.get_collection(new_path)
|
|
108
|
+
|
|
109
|
+
def add_collection(self, col_path: str | list[str]):
|
|
110
|
+
if self.is_sync:
|
|
111
|
+
raise Exception("You cannot add a collection to a synced collection!")
|
|
112
|
+
raise NotImplementedError('This collection cannot add a collection')
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def get_samples(self, per_page=10) -> ElementSet:
|
|
116
|
+
root = self.get_root()
|
|
117
|
+
e = ElementSet(root._session, root._element_manager.all_classes.get('sample'), self.id,
|
|
118
|
+
self.is_sync)
|
|
119
|
+
e.load_elements(per_page)
|
|
120
|
+
return e
|
|
121
|
+
|
|
122
|
+
def get_reactions(self, per_page=10) -> ElementSet:
|
|
123
|
+
root = self.get_root()
|
|
124
|
+
e = ElementSet(root._session, root._element_manager.all_classes.get('reaction'), self.id,
|
|
125
|
+
self.is_sync)
|
|
126
|
+
e.load_elements(per_page)
|
|
127
|
+
return e
|
|
128
|
+
|
|
129
|
+
def get_research_plans(self, per_page=10) -> ElementSet:
|
|
130
|
+
root = self.get_root()
|
|
131
|
+
e = ElementSet(root._session, root._element_manager.all_classes.get('research_plan'), self.id,
|
|
132
|
+
self.is_sync)
|
|
133
|
+
e.load_elements(per_page)
|
|
134
|
+
return e
|
|
135
|
+
|
|
136
|
+
def get_wellplates(self, per_page=10) -> ElementSet:
|
|
137
|
+
root = self.get_root()
|
|
138
|
+
e = ElementSet(root._session, root._element_manager.all_classes.get('wellplate'), self.id,
|
|
139
|
+
self.is_sync)
|
|
140
|
+
e.load_elements(per_page)
|
|
141
|
+
return e
|
|
142
|
+
|
|
143
|
+
def get_generics_by_name(self, name, per_page=10):
|
|
144
|
+
root = self.get_root()
|
|
145
|
+
elem = root._element_manager.all_classes.get(name)
|
|
146
|
+
if elem is None:
|
|
147
|
+
raise ValueError(f'Could not find a generic element under the name: "{name}"')
|
|
148
|
+
|
|
149
|
+
e = ElementSet(root._session, elem, self.id, self.is_sync)
|
|
150
|
+
e.load_elements(per_page)
|
|
151
|
+
return e
|
|
152
|
+
|
|
153
|
+
def get_generics_by_label(self, label, id):
|
|
154
|
+
root = self.get_root()
|
|
155
|
+
for (elem_name, elem) in root._element_manager.all_classes.items():
|
|
156
|
+
if elem['label'] == label:
|
|
157
|
+
return self.get_generics_by_label(elem_name, id)
|
|
158
|
+
raise ValueError(f'Could not find a generic element with the label: "{label}"')
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class AbstractEditableCollection(AbstractCollection):
|
|
162
|
+
|
|
163
|
+
def new_sample(self) -> AbstractElement:
|
|
164
|
+
return self._create_new_element('sample')
|
|
165
|
+
|
|
166
|
+
def new_sample_smiles(self, smiles_code: str) -> AbstractElement:
|
|
167
|
+
sample = self._create_new_element('sample')
|
|
168
|
+
mol = MoleculeManager(self.get_root()._session).create_molecule_by_smiles(smiles_code)
|
|
169
|
+
sample.molecule = mol
|
|
170
|
+
return sample
|
|
171
|
+
|
|
172
|
+
def new_solvent(self, name) -> AbstractElement:
|
|
173
|
+
root = self.get_root()
|
|
174
|
+
new_json = root._element_manager.build_solvent_sample(name, self.id)
|
|
175
|
+
e = ElementSet(root._session, root._element_manager.all_classes.get('sample'), self.id,
|
|
176
|
+
self.is_sync)
|
|
177
|
+
return e.new_element(new_json)
|
|
178
|
+
|
|
179
|
+
def new_reaction(self) -> AbstractElement:
|
|
180
|
+
return self._create_new_element('reaction')
|
|
181
|
+
|
|
182
|
+
def new_research_plan(self) -> AbstractElement:
|
|
183
|
+
return self._create_new_element('research_plan')
|
|
184
|
+
|
|
185
|
+
def new_wellplate(self) -> AbstractElement:
|
|
186
|
+
return self._create_new_element('wellplate')
|
|
187
|
+
|
|
188
|
+
def new_generic(self, type_name) -> AbstractElement:
|
|
189
|
+
return self._create_new_element(type_name)
|
|
190
|
+
|
|
191
|
+
def new_generic_by_label(self, label) -> AbstractElement:
|
|
192
|
+
for (elem_name, elem) in self.get_root()._element_manager.all_classes.items():
|
|
193
|
+
if elem['label'] == label:
|
|
194
|
+
return self._create_new_element(elem_name)
|
|
195
|
+
raise ValueError(f'Could not find a generic element with the label: "{label}"')
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _create_new_element(self, type_name) -> AbstractElement:
|
|
199
|
+
root = self.get_root()
|
|
200
|
+
new_json = root._element_manager.build_new(type_name, self.id)
|
|
201
|
+
|
|
202
|
+
e = ElementSet(root._session, root._element_manager.all_classes.get(type_name), self.id,
|
|
203
|
+
self.is_sync)
|
|
204
|
+
return e.new_element(new_json)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
class Collection(AbstractEditableCollection):
|
|
208
|
+
permission_level: int = None
|
|
209
|
+
reaction_detail_level: int = None
|
|
210
|
+
sample_detail_level: int = None
|
|
211
|
+
screen_detail_level: int = None
|
|
212
|
+
wellplate_detail_level: int = None
|
|
213
|
+
element_detail_level: int = None
|
|
214
|
+
sync_collections_users: dict = None
|
|
215
|
+
is_locked: bool = None
|
|
216
|
+
is_shared: bool = None
|
|
217
|
+
is_synchronized: bool = None
|
|
218
|
+
|
|
219
|
+
collection_json: dict = None
|
|
220
|
+
|
|
221
|
+
def __init__(self, collection_json: dict = None):
|
|
222
|
+
super().__init__()
|
|
223
|
+
self.set_json(collection_json)
|
|
224
|
+
|
|
225
|
+
def set_json(self, collection_json):
|
|
226
|
+
if collection_json is None:
|
|
227
|
+
collection_json = self._get_new_json()
|
|
228
|
+
|
|
229
|
+
self.collection_json = collection_json
|
|
230
|
+
self._set_children(collection_json.get('children', []))
|
|
231
|
+
if 'children' in collection_json: del collection_json['children']
|
|
232
|
+
|
|
233
|
+
for (key, val) in collection_json.items():
|
|
234
|
+
if hasattr(self, key):
|
|
235
|
+
setattr(self, key, val)
|
|
236
|
+
|
|
237
|
+
def _get_new_json(self):
|
|
238
|
+
return {
|
|
239
|
+
"id": random(),
|
|
240
|
+
"label": 'New Collection',
|
|
241
|
+
"isNew": True
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
def __iter__(self):
|
|
245
|
+
for (key, val) in self.collection_json.items():
|
|
246
|
+
if hasattr(self, key):
|
|
247
|
+
val = getattr(self, key)
|
|
248
|
+
yield (key, val)
|
|
249
|
+
|
|
250
|
+
def to_json(self):
|
|
251
|
+
as_dict = dict(self)
|
|
252
|
+
return super().to_json() | as_dict
|
|
253
|
+
|
|
254
|
+
def move(self, dest):
|
|
255
|
+
abs_path = self.get_path()
|
|
256
|
+
dest = os.path.abspath(os.path.join(os.path.dirname(abs_path), dest))
|
|
257
|
+
self.get_root().move(abs_path, dest)
|
|
258
|
+
|
|
259
|
+
def delete(self):
|
|
260
|
+
abs_path = self.get_path()
|
|
261
|
+
self.get_root().delete(abs_path)
|
|
262
|
+
|
|
263
|
+
def add_collection(self, name):
|
|
264
|
+
abs_path = os.path.join(self.get_path(), name)
|
|
265
|
+
return self.get_root().add_collection(abs_path)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
class RootSyncCollection(AbstractCollection):
|
|
269
|
+
|
|
270
|
+
def __init__(self, session: Connection, element_manager: ElementManager):
|
|
271
|
+
super().__init__()
|
|
272
|
+
self.is_sync = True
|
|
273
|
+
self._session = session
|
|
274
|
+
self._element_manager = element_manager
|
|
275
|
+
self.label = 'sync_root'
|
|
276
|
+
|
|
277
|
+
def to_json(self):
|
|
278
|
+
as_dict = dict(self)
|
|
279
|
+
return super().to_json() | as_dict
|
|
280
|
+
|
|
281
|
+
def move(self, *args, **kwargs):
|
|
282
|
+
raise Exception("You cannot move a synced collection collection!")
|
|
283
|
+
|
|
284
|
+
def delete(self, *args, **kwargs):
|
|
285
|
+
raise Exception("You cannot delete a synced collection collection!")
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class RootCollection(AbstractCollection):
|
|
289
|
+
sync_root: RootSyncCollection = None
|
|
290
|
+
all: dict = None
|
|
291
|
+
_element_manager: ElementManager
|
|
292
|
+
|
|
293
|
+
def __init__(self, session: Connection):
|
|
294
|
+
super().__init__()
|
|
295
|
+
self._session = session
|
|
296
|
+
self.label = 'root'
|
|
297
|
+
self._deleted_ids = []
|
|
298
|
+
|
|
299
|
+
def set_element_manager(self, element_manager: ElementManager):
|
|
300
|
+
self._element_manager = element_manager
|
|
301
|
+
|
|
302
|
+
def load_collection(self):
|
|
303
|
+
collection_url = '/api/v1/collections/roots.json'
|
|
304
|
+
|
|
305
|
+
res = self._session.get(collection_url)
|
|
306
|
+
|
|
307
|
+
if res.status_code != 200:
|
|
308
|
+
raise ConnectionError('{} -> {}'.format(res.status_code, res.text))
|
|
309
|
+
|
|
310
|
+
collections = json.loads(res.content)
|
|
311
|
+
self.all = self._load_all_collection()['collection']
|
|
312
|
+
self.id = self.all['id']
|
|
313
|
+
self._set_children(collections['collections'])
|
|
314
|
+
|
|
315
|
+
def _load_all_collection(self):
|
|
316
|
+
collection_url = '/api/v1/collections/all'
|
|
317
|
+
|
|
318
|
+
res = self._session.get(collection_url)
|
|
319
|
+
|
|
320
|
+
if res.status_code != 200:
|
|
321
|
+
raise ConnectionError('{} -> {}'.format(res.status_code, res.text))
|
|
322
|
+
return json.loads(res.content)
|
|
323
|
+
|
|
324
|
+
def load_sync_collection(self):
|
|
325
|
+
collection_url = '/api/v1/syncCollections/sync_remote_roots'
|
|
326
|
+
|
|
327
|
+
res = self._session.get(collection_url)
|
|
328
|
+
|
|
329
|
+
if res.status_code != 200:
|
|
330
|
+
raise ConnectionError('{} -> {}'.format(res.status_code, res.text))
|
|
331
|
+
collections = json.loads(res.content)
|
|
332
|
+
self.sync_root = RootSyncCollection(self._session, self._element_manager)
|
|
333
|
+
self.sync_root._set_children(collections['syncCollections'])
|
|
334
|
+
|
|
335
|
+
def save(self):
|
|
336
|
+
collection_url = '/api/v1/collections'
|
|
337
|
+
payload = self.to_json()
|
|
338
|
+
payload['deleted_ids'] = self._deleted_ids
|
|
339
|
+
res = self._session.patch(collection_url,
|
|
340
|
+
data=payload)
|
|
341
|
+
if res.status_code != 200:
|
|
342
|
+
raise ConnectionError('{} -> {}'.format(res.status_code, res.text))
|
|
343
|
+
self.load_collection()
|
|
344
|
+
|
|
345
|
+
def get_collection(self, col_path: str | list[str], case_insensitive: bool = False) -> TAbstractCollection | None:
|
|
346
|
+
col_path = self._prepare_path(col_path)
|
|
347
|
+
current_pos = self
|
|
348
|
+
for col_label in self._prepare_path(col_path):
|
|
349
|
+
current_pos = next((x for x in current_pos.children if
|
|
350
|
+
AbstractCollection.prepare_label(x.label, case_insensitive) == col_label), None)
|
|
351
|
+
if current_pos is None:
|
|
352
|
+
raise ModuleNotFoundError("'{}' Collection Not Found".format('/'.join(col_path)))
|
|
353
|
+
return current_pos
|
|
354
|
+
|
|
355
|
+
def move(self, src: str | list[str], dest: str | list[str], case_insensitive: bool = False):
|
|
356
|
+
prepared_src = self._prepare_path(src, case_insensitive)
|
|
357
|
+
src_col = self.get_collection(prepared_src, case_insensitive)
|
|
358
|
+
|
|
359
|
+
idx = next((i for (i, x) in enumerate(src_col._parent.children) if
|
|
360
|
+
AbstractCollection.prepare_label(x.label, case_insensitive) == prepared_src[-1]), None)
|
|
361
|
+
dest_col = self.get_collection(dest, case_insensitive)
|
|
362
|
+
|
|
363
|
+
src_col._parent.children.pop(idx)
|
|
364
|
+
dest_col.children.append(src_col)
|
|
365
|
+
self._update_relations()
|
|
366
|
+
|
|
367
|
+
def delete(self, src: str | list[str]):
|
|
368
|
+
prepared_src = self._prepare_path(src)
|
|
369
|
+
src_col = self.get_collection(prepared_src)
|
|
370
|
+
idx = next((i for (i, x) in enumerate(src_col._parent.children) if x.label == prepared_src[-1]), None)
|
|
371
|
+
|
|
372
|
+
src_col._parent.children.pop(idx)
|
|
373
|
+
src_col._parent = None
|
|
374
|
+
self._deleted_ids.append(src_col.id)
|
|
375
|
+
|
|
376
|
+
def add_collection(self, path_to_new: str | list[str]):
|
|
377
|
+
prepared_src = self._prepare_path(path_to_new)
|
|
378
|
+
src_col = self.get_collection(prepared_src[:-1])
|
|
379
|
+
c = Collection()
|
|
380
|
+
c.label = prepared_src[-1]
|
|
381
|
+
src_col.children.append(c)
|
|
382
|
+
self._update_relations()
|
|
383
|
+
return c
|
|
384
|
+
|
|
385
|
+
def to_json(self) -> dict:
|
|
386
|
+
return {'collections': super().to_json()['children']}
|
|
387
|
+
|
|
388
|
+
def _prepare_path(self, col_path: str | list[str], case_insensitive: bool = False) -> list[str]:
|
|
389
|
+
if type(col_path) == str:
|
|
390
|
+
if not col_path.startswith('/'): col_path = '/' + col_path
|
|
391
|
+
col_path = [x for x in os.path.abspath(col_path).strip('/').split('/') if x != '']
|
|
392
|
+
if case_insensitive:
|
|
393
|
+
col_path = [x.lower() for x in col_path]
|
|
394
|
+
|
|
395
|
+
return col_path
|