Skip to content

Commit 4985f66

Browse files
committed
Apply ruff unsafe fixes
1 parent 7057aa8 commit 4985f66

File tree

17 files changed

+78
-268
lines changed

17 files changed

+78
-268
lines changed

abcd/__init__.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -60,11 +60,3 @@ def from_url(cls, url, **kwargs):
6060
url = "mongodb://mongoadmin:secret@localhost:27017/abcd_new"
6161
abcd = ABCD.from_url(url)
6262
abcd.print_info()
63-
64-
# from ase.io import iread
65-
# for atoms in iread('../tutorials/data/bcc_bulk_54_expanded_2_high.xyz', index=slice(1)):
66-
# # Hack to fix the representation of forces
67-
# atoms.calc.results['forces'] = atoms.arrays['force']
68-
#
69-
# abcd.push(atoms)
70-
# print(atoms)

abcd/backends/atoms_http.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import json
22
import logging
33
from os import linesep
4-
from typing import List
54

65
import ase
76
import requests
@@ -45,14 +44,12 @@ def pull(self, query=None, properties=None):
4544
def query(self, query_string):
4645
pass
4746

48-
def search(self, query_string: str) -> List[str]:
49-
results = requests.get(self.url + "/calculation").json()
50-
return results
47+
def search(self, query_string: str) -> list[str]:
48+
return requests.get(self.url + "/calculation").json()
5149

5250
def get_atoms(self, id: str) -> Atoms:
5351
data = requests.get(self.url + f"/calculation/{id}").json()
54-
atoms = Atoms.from_dict(data)
55-
return atoms
52+
return Atoms.from_dict(data)
5653

5754
def __repr__(self):
5855
return f"ABCD(type={self.__class__.__name__}, url={self.url}, ...)"

abcd/backends/atoms_pymongo.py

Lines changed: 24 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ def __init__(
161161
collection_name="atoms",
162162
username=None,
163163
password=None,
164-
authSource="admin",
164+
auth_source="admin",
165165
uri_mode=False,
166166
**kwargs,
167167
):
@@ -175,31 +175,31 @@ def __init__(
175175
collection_name,
176176
username,
177177
password,
178-
authSource,
178+
auth_source,
179179
kwargs,
180180
)
181181
)
182182

183183
if uri_mode:
184-
self.client = MongoClient(host=host, authSource=authSource)
184+
self.client = MongoClient(host=host, authSource=auth_source)
185185
else:
186186
self.client = MongoClient(
187187
host=host,
188188
port=port,
189189
username=username,
190190
password=password,
191-
authSource=authSource,
191+
authSource=auth_source,
192192
)
193193

194194
try:
195195
info = self.client.server_info() # Forces a call.
196196
logger.info(f"DB info: {info}")
197197

198-
except pymongo.errors.OperationFailure:
199-
raise abcd.errors.AuthenticationError()
198+
except pymongo.errors.OperationFailure as err:
199+
raise abcd.errors.AuthenticationError() from err
200200

201-
except pymongo.errors.ServerSelectionTimeoutError:
202-
raise abcd.errors.TimeoutError()
201+
except pymongo.errors.ServerSelectionTimeoutError as err:
202+
raise abcd.errors.TimeoutError() from err
203203

204204
self.db = self.client[db_name]
205205
self.collection = self.db[collection_name]
@@ -258,8 +258,7 @@ def upload(self, file: Path, extra_infos=None, store_calc=True):
258258
def get_items(self, query=None):
259259
# TODO: better method for aggregations
260260
query = parser(query)
261-
for dct in self.db.atoms.find(query):
262-
yield dct
261+
yield from self.db.atoms.find(query)
263262

264263
def get_atoms(self, query=None):
265264
query = parser(query)
@@ -320,18 +319,18 @@ def properties(self, query=None):
320319
return properties
321320

322321
def get_type_of_property(self, prop, category):
323-
# TODO: Probably it would be nicer to store the type info in the database from the beginning.
322+
# TODO: Store the type info in the database from the beginning?
324323
atoms = self.db.atoms.find_one({prop: {"$exists": True}})
325324
data = atoms[prop]
326325

327326
if category == "arrays":
328-
if type(data[0]) == list:
327+
if isinstance(data[0], list):
329328
return f"array({map_types[type(data[0][0])]}, N x {len(data[0])})"
330329
return f"vector({map_types[type(data[0])]}, N)"
331330

332-
if type(data) == list:
333-
if type(data[0]) == list:
334-
if type(data[0][0]) == list:
331+
if isinstance(data, list):
332+
if isinstance(data[0], list):
333+
if isinstance(data[0][0], list):
335334
return "list(list(...)"
336335
return f"array({map_types[type(data[0][0])]})"
337336
return f"vector({map_types[type(data[0])]})"
@@ -397,7 +396,8 @@ def add_property(self, data, query=None):
397396

398397
def rename_property(self, name, new_name, query=None):
399398
logger.info(f"rename: query={query}, old={name}, new={new_name}")
400-
# TODO name in derived.info_keys OR name in derived.arrays_keys OR name in derived.derived_keys
399+
# TODO name in derived.info_keys OR name in derived.arrays_keys
400+
# OR name in derived.derived_keys
401401
self.collection.update_many(
402402
parser(query), {"$push": {"derived.info_keys": new_name}}
403403
)
@@ -407,15 +407,6 @@ def rename_property(self, name, new_name, query=None):
407407
{"$pull": {"derived.info_keys": name}, "$rename": {name: new_name}},
408408
)
409409

410-
# self.collection.update_many(
411-
# parser(query + ['arrays.{}'.format(name)]),
412-
# {'$push': {'derived.arrays_keys': new_name}})
413-
#
414-
# self.collection.update_many(
415-
# parser(query + ['arrays.{}'.format(name)]),
416-
# {'$pull': {'derived.arrays_keys': name},
417-
# '$rename': {'arrays.{}'.format(name): 'arrays.{}'.format(new_name)}})
418-
419410
def delete_property(self, name, query=None):
420411
logger.info(f"delete: query={name}, porperty={query}")
421412

@@ -435,7 +426,7 @@ def exec(self, code, query=None):
435426
# TODO: Separate python environment with its own packages loaded
436427

437428
for dct in self.get_items(query):
438-
atoms = AtomsModel(self.collection, dct)
429+
AtomsModel(self.collection, dct)
439430
exec(code)
440431

441432
def __repr__(self):
@@ -483,30 +474,30 @@ def histogram(name, data, **kwargs):
483474
print(f"Mixed type error of the {name} property!")
484475
return None
485476

486-
if ptype == float:
477+
if isinstance(data[0], float):
487478
bins = kwargs.get("bins", 10)
488479
return _hist_float(name, data, bins)
489480

490-
if ptype == int:
481+
if isinstance(data[0], int):
491482
bins = kwargs.get("bins", 10)
492483
return _hist_int(name, data, bins)
493484

494-
if ptype == str:
485+
if isinstance(data[0], str):
495486
return _hist_str(name, data, **kwargs)
496487

497-
if ptype == datetime:
488+
if isinstance(data[0], datetime):
498489
bins = kwargs.get("bins", 10)
499490
return _hist_date(name, data, bins)
500491

501492
print(f"{name}: Histogram for list of {type(data[0])} types are not supported!")
502493
logger.info(
503494
f"{name}: Histogram for list of {type(data[0])} types are not supported!"
504495
)
505-
506-
else:
507-
logger.info(f"{name}: Histogram for {type(data)} types are not supported!")
508496
return None
509497

498+
logger.info(f"{name}: Histogram for {type(data)} types are not supported!")
499+
return None
500+
510501

511502
def _hist_float(name, data, bins=10):
512503
data = np.array(data)
@@ -596,39 +587,7 @@ def _hist_str(name, data, bins=10, truncate=20):
596587

597588

598589
if __name__ == "__main__":
599-
# import json
600-
# from ase.io import iread
601-
# from pprint import pprint
602-
# from server.styles.myjson import JSONEncoderOld, JSONDecoderOld, JSONEncoder
603-
604-
print("hello")
605590
db = MongoDatabase(username="mongoadmin", password="secret")
606591
print(db.info())
607592
print(db.count())
608-
609593
print(db.hist("uploaded"))
610-
611-
# for atoms in iread('../../tutorials/data/bcc_bulk_54_expanded_2_high.xyz', index=slice(None)):
612-
# # print(at)
613-
# atoms.calc.results['forces'] = atoms.arrays['force']
614-
# # at.arrays['force'] = None
615-
#
616-
# json_data = json.dumps(atoms, cls=JSONEncoderOld)
617-
# print(json_data)
618-
#
619-
# atom_dict = json.loads(json_data, cls=JSONDecoderOld)
620-
# print(atom_dict)
621-
#
622-
# print(atoms == atom_dict)
623-
#
624-
# with JSONEncoder() as encoder:
625-
# data = encoder.encode(atoms)
626-
#
627-
# print(data)
628-
#
629-
# with DictEncoder() as encoder:
630-
# data = encoder.encode(atoms)
631-
#
632-
# pprint(data)
633-
#
634-
# db.collection.insert_one(DictEncoder().encode(atoms))

abcd/database.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
from abc import ABCMeta, abstractmethod
1+
# ruff: noqa: B024, B027
2+
from abc import ABCMeta
23
import logging
34

45
logger = logging.getLogger(__name__)
@@ -7,7 +8,6 @@
78
class AbstractABCD(metaclass=ABCMeta):
89
"""Factory method"""
910

10-
@abstractmethod
1111
def __init__(self):
1212
pass
1313

abcd/frontends/commandline/commands.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,8 @@ def key_delete(*, db, query, yes, keys, **kwargs):
218218

219219
if not yes:
220220
print(
221-
f"Please use --yes for deleting keys from {db.count(query=query)} configurations"
221+
f"Please use --yes for deleting keys from {db.count(query=query)} "
222+
"configurations"
222223
)
223224
exit(1)
224225

@@ -232,7 +233,8 @@ def key_delete(*, db, query, yes, keys, **kwargs):
232233
def execute(*, db, query, yes, python_code, **kwargs):
233234
if not yes:
234235
print(
235-
f"Please use --yes for executing code on {db.count(query=query)} configurations"
236+
f"Please use --yes for executing code on {db.count(query=query)} "
237+
"configurations"
236238
)
237239
exit(1)
238240

@@ -258,16 +260,14 @@ def server(*, abcd_url, url, api_only, **kwargs):
258260

259261

260262
class Formater:
261-
partialBlocks = ["▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"] # char=pb
262-
263263
def title(self, title):
264264
print("", title, "=" * len(title), sep=os.linesep)
265265

266266
def describe(self, data):
267267
if data["type"] == "hist_float":
268268
print(
269-
"{} count: {} min: {:11.4e} med: {:11.4e} max: {:11.4e} std: {:11.4e} var:{"
270-
":11.4e}".format(
269+
"{} count: {} min: {:11.4e} med: {:11.4e} max: {:11.4e} std: {:11.4e} "
270+
"var:{:11.4e}".format(
271271
data["name"],
272272
sum(data["counts"]),
273273
data["min"],

abcd/frontends/commandline/config.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,7 @@ def load(cls):
3232

3333
logger.info(f"Using config file: {file}")
3434

35-
config = cls.from_json(file)
36-
37-
return config
35+
return cls.from_json(file)
3836

3937
def save(self):
4038
file = (

abcd/frontends/commandline/parser.py

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -234,20 +234,4 @@ def main(args=None):
234234
if __name__ == "__main__":
235235
main(["summary"])
236236
main("delete-key -q pbc pbc".split())
237-
# main('upload -e cas -i ../../../tutorials/GB_alphaFe_001/tilt/00110391110_v6bxv2_tv0.4bxv0.2_d1.6z_traj.xyz'.split())
238-
# main('summary -q formula~"Si2"'.split())
239-
# main('upload -e cas -i ../../../tutorials/GB_alphaFe_001/tilt/00110391110_v6bxv2_tv0.4bxv0.2_d1.6z_traj.xyz'.split())
240-
# main('-v login mongodb://mongoadmin:secret@localhost:27017/abcd'.split())
241-
# main('-v summary'.split())
242-
# main('-v summary -p energy'.split())
243-
# main('-v summary -p *'.split())
244-
# main('add-key -q cas selected user="cas"'.split())
245237
main("delete-key user".split())
246-
# main(['summary', '-p', '*'])
247-
# main(['summary', '-p', 'info.config_name, info.energy'])
248-
# main(['summary', '-p', 'info.config_name, info.energy,info.energy;info.energy info.energy'])
249-
# main(['-s', 'fancy', 'summary', '-p', '*'])
250-
# main(['summary', '-p', '*'])
251-
# main(['-s', 'fancy', 'summary'])
252-
# main(['-v', 'summary', '-p', 'config_type', '-p', 'haha', '-p' 'sdgsdg, dsgsdg,asd fgg', '-q', 'config_type~bcc',
253-
# '-q', 'config_type~bcc'])

abcd/model.py

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,9 @@ def __getitem__(self, key):
8686

8787
def __setitem__(self, key, value):
8888
if key == "derived":
89-
# raise KeyError('Please do not use "derived" as key because it is protected!')
89+
# raise KeyError(
90+
# 'Please do not use "derived" as key because it is protected!'
91+
# )
9092
# Silent return to avoid raising error in pymongo package
9193
return
9294

@@ -96,7 +98,8 @@ def __setitem__(self, key, value):
9698
super().__setitem__(key, value)
9799

98100
def convert(self, value):
99-
# TODO: https://api.mongodb.com/python/current/api/bson/index.html using type_registry
101+
# TODO: https://api.mongodb.com/python/current/api/bson/index.html
102+
# using type_registry
100103

101104
if isinstance(value, np.int64):
102105
return int(value)
@@ -105,7 +108,9 @@ def convert(self, value):
105108

106109
def update_key_category(self, key, value):
107110
if key == "_id":
108-
# raise KeyError('Please do not use "derived" as key because it is protected!')
111+
# raise KeyError(
112+
# 'Please do not use "derived" as key because it is protected!'
113+
# )
109114
return
110115

111116
for category in ("arrays_keys", "info_keys", "results_keys", "derived_keys"):
@@ -136,8 +141,7 @@ def __delitem__(self, key):
136141
super().__delitem__(key)
137142

138143
def __iter__(self):
139-
for item in super().__iter__():
140-
yield item
144+
yield from super().__iter__()
141145
yield "derived"
142146

143147
@classmethod
@@ -319,14 +323,3 @@ def pre_save(self):
319323

320324
model = AbstractModel.from_atoms(atoms)
321325
print(model.to_ase())
322-
323-
# xyz = io.StringIO(
324-
# """
325-
# 2
326-
# Properties=species:S:1:pos:R:3 s="sadf" _vtk_test="t e s t _ s t r" pbc="F F F"
327-
# Si 0.00000000 0.00000000 0.00000000
328-
# Si 0.00000000 0.00000000 0.00000000
329-
#
330-
# """)
331-
#
332-
# atoms = read(xyz, format='extxyz', index=0)

0 commit comments

Comments
 (0)