Skip to content

Commit

Permalink
yapf
Browse files Browse the repository at this point in the history
  • Loading branch information
hainm committed Nov 22, 2024
1 parent d20c319 commit a3cc1b2
Show file tree
Hide file tree
Showing 24 changed files with 188 additions and 143 deletions.
2 changes: 2 additions & 0 deletions .style.yapf
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[style]
based_on_style = google
3 changes: 2 additions & 1 deletion nglview/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
with warnings.catch_warnings():
warnings.simplefilter("ignore")


# Register nbextension
# FIXME: do we still need this?
def _jupyter_nbextension_paths():
Expand All @@ -33,4 +34,4 @@ def _jupyter_nbextension_paths():


__all__ = ['NGLWidget', 'write_html'
] + widget.__all__ + adaptor.__all__ + show.__all__
] + widget.__all__ + adaptor.__all__ + show.__all__
15 changes: 15 additions & 0 deletions nglview/adaptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ def _get_structure_string(write_method, suffix='.pdb'):


class register_backend:

def __init__(self, package_name):
# package_name must match exactly to your Python package
self.package_name = package_name
Expand All @@ -72,6 +73,7 @@ def __call__(self, cls):


class FileStructure(Structure):

def __init__(self, path):
super().__init__()
self.fm = FileManager(path)
Expand All @@ -84,6 +86,7 @@ def get_structure_string(self):


class TextStructure(Structure):

def __init__(self, text, ext='pdb', params={}):
super().__init__()
self.path = ''
Expand All @@ -97,6 +100,7 @@ def get_structure_string(self):

@register_backend('rdkit')
class RdkitStructure(Structure):

def __init__(self, rdkit_mol, ext="pdb", conf_id=-1):
super().__init__()
self.path = ''
Expand All @@ -114,6 +118,7 @@ def get_structure_string(self):


class PdbIdStructure(Structure):

def __init__(self, pdbid):
super().__init__()
self.pdbid = pdbid
Expand All @@ -126,6 +131,7 @@ def get_structure_string(self):


class ASEStructure(Structure):

def __init__(self, ase_atoms, ext='pdb', params={}):
super().__init__()
self.path = ''
Expand All @@ -138,6 +144,7 @@ def get_structure_string(self):


class IODataStructure(Structure):

def __init__(self, obj):
super().__init__()
self._obj = obj
Expand All @@ -152,6 +159,7 @@ def get_structure_string(self):


class QCElementalStructure(Structure):

def __init__(self, obj):
super().__init__()
self._obj = obj
Expand All @@ -166,6 +174,7 @@ class Psi4Structure(QCElementalStructure):


class OpenbabelStructure(Structure):

def __init__(self, obj):
super().__init__()
self._obj = obj
Expand All @@ -183,6 +192,7 @@ def get_structure_string(self):


class BiopythonStructure(Structure):

def __init__(self, entity, ext='pdb', params={}):
super().__init__()
self.path = ''
Expand All @@ -201,6 +211,7 @@ def get_structure_string(self):


class IOTBXStructure(Structure):

def __init__(self, obj, ext='pdb', params={}):
"""
obj must have as_pdb_string method
Expand All @@ -216,6 +227,7 @@ def get_structure_string(self):


class RosettaStructure(Structure):

def __init__(self, pose, ext='pdb', params={}):
# type: (pyrosetta.rosetta.core.pose.Pose, str, Dict) -> None
super().__init__()
Expand All @@ -230,6 +242,7 @@ def get_structure_string(self):

@register_backend('prody')
class ProdyStructure(Structure):

def __init__(self, obj):
super().__init__()
self._obj = obj
Expand All @@ -251,6 +264,7 @@ def write(fname):

@register_backend('prody')
class ProdyTrajectory(Trajectory, ProdyStructure):

def __init__(self, obj):
ProdyStructure.__init__(self, obj)

Expand Down Expand Up @@ -370,6 +384,7 @@ def get_structure_string(self, index=0):

@register_backend('parmed')
class ParmEdStructure(Structure):

def __init__(self, structure):
self._structure = structure
self.only_save_1st_model = True
Expand Down
13 changes: 9 additions & 4 deletions nglview/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
def _singleton(cls):
# https://www.python.org/dev/peps/pep-0318/#examples
instances = {}

def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]

return getinstance


Expand All @@ -21,17 +23,20 @@ def _js(self, code):
self._call("executeCode", code)

def _call(self, method_name, *args, **kwargs):
msg = {"type": "callMethod",
"methodName": method_name,
"args": args, "kwargs": kwargs}
msg = {
"type": "callMethod",
"methodName": method_name,
"args": args,
"kwargs": kwargs
}
if not self._ready:
# fire later
self._msg_q.append(msg)
else:
self.send(msg)
msg_ar = self._msg_ar[:]
msg_ar.append(msg)
self._msg_ar = msg_ar # trigger sync
self._msg_ar = msg_ar # trigger sync

@observe("_ready")
def _on_ready(self, change):
Expand Down
8 changes: 4 additions & 4 deletions nglview/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from IPython.display import display
import time


COLOR_SCHEMES = [
" ", "picking", "random", "uniform", "atomindex", "residueindex",
"chainindex", "modelindex", "sstruc", "element", "resname", "bfactor",
Expand All @@ -15,7 +14,6 @@
_USER_COLOR_DICT = {}



class _ColorScheme:
_color_dict = {}

Expand All @@ -38,12 +36,14 @@ class _ColormakerRegistry(BaseWidget):
_model_name = Unicode("ColormakerRegistryModel").tag(sync=True)
_model_module = Unicode("nglview-js-widgets").tag(sync=True)
_model_module_version = Unicode(__frontend_version__).tag(sync=True)
_msg_q = List().tag(sync=True) # overwrite BaseWidget's trait to avoid caling base method in frontend
_msg_q = List().tag(
sync=True
) # overwrite BaseWidget's trait to avoid caling base method in frontend

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
try:
get_ipython() # only display in notebook
get_ipython() # only display in notebook
self._ipython_display_()
except NameError:
pass
Expand Down
4 changes: 2 additions & 2 deletions nglview/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ def __init__(self, view, id):
widget_utils._add_repr_method_shortcut(self, self._view)
self._borrow_attribute(self._view, [
'clear_representations', '_remove_representations_by_name',
'_update_representations_by_name', 'center_view', 'center',
'clear', 'set_representations'
'_update_representations_by_name', 'center_view', 'center', 'clear',
'set_representations'
], ['get_structure_string', 'get_coordinates', 'n_frames'])

@property
Expand Down
55 changes: 26 additions & 29 deletions nglview/contrib/movie.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,8 @@ def sleep(self):

def make_old_impl(self, in_memory=False):
# TODO : make base class so we can reuse this with sandbox/base.py
progress = IntProgress(
description='Rendering...', max=len(self._time_range) - 1)
progress = IntProgress(description='Rendering...',
max=len(self._time_range) - 1)
self._event = threading.Event()

def _make(event):
Expand All @@ -156,18 +156,16 @@ def _make(event):
iw = self.view.render_image(**self.render_params)
self.sleep()
if self.in_memory:
rgb = self._base64_to_ndarray(
self.view._image_data)
rgb = self._base64_to_ndarray(self.view._image_data)
self._image_array.append(rgb)
if iw:
iw.close() # free memory
if not self.in_memory:
template = "{}/{}.{}.png"
image_files = [
image_dir
for image_dir in (template.format(
image_dir for image_dir in (template.format(
self.download_folder, self.prefix, str(i))
for i in self._time_range)
for i in self._time_range)
if os.path.exists(image_dir)
]
else:
Expand All @@ -177,20 +175,20 @@ def _make(event):
clip = mpy.ImageSequenceClip(image_files, fps=self.fps)
with Output():
if self.output.endswith('.gif'):
clip.write_gif(
self.output,
fps=self.fps,
verbose=False,
**self.moviepy_params)
clip.write_gif(self.output,
fps=self.fps,
verbose=False,
**self.moviepy_params)
else:
clip.write_videofile(
self.output, fps=self.fps, **self.moviepy_params)
clip.write_videofile(self.output,
fps=self.fps,
**self.moviepy_params)
self._image_array = []
progress.description = 'Done'
time.sleep(1)
progress.close()

self.thread = threading.Thread(target=_make, args=(self._event, ))
self.thread = threading.Thread(target=_make, args=(self._event,))
self.thread.daemon = True
self.thread.start()
return progress
Expand Down Expand Up @@ -219,8 +217,9 @@ def hook(frame):

# trigger movie making communication between backend and frontend
self.perframe_hook and hook(frame)
self.view._set_coordinates(
frame, movie_making=True, render_params=self.render_params)
self.view._set_coordinates(frame,
movie_making=True,
render_params=self.render_params)
self._progress.description = 'Rendering ...'

def on_msg(widget, msg, buffers):
Expand All @@ -229,10 +228,9 @@ def on_msg(widget, msg, buffers):
try:
frame = next(iframe)
self.perframe_hook and hook(frame)
self.view._set_coordinates(
frame,
movie_making=True,
render_params=self.render_params)
self.view._set_coordinates(frame,
movie_making=True,
render_params=self.render_params)
self._progress.value = frame
except StopIteration:
if movie:
Expand Down Expand Up @@ -262,15 +260,15 @@ def _make_from_array(self, image_array: List[str]):
clip = mpy.ImageSequenceClip(image_files, fps=self.fps)
with self._woutput:
if self.output.endswith('.gif'):
clip.write_gif(
self.output,
fps=self.fps,
verbose=False,
**self.moviepy_params)
clip.write_gif(self.output,
fps=self.fps,
verbose=False,
**self.moviepy_params)
else:

clip.write_videofile(
self.output, fps=self.fps, **self.moviepy_params)
clip.write_videofile(self.output,
fps=self.fps,
**self.moviepy_params)

def interupt(self):
""" Stop making process """
Expand All @@ -287,4 +285,3 @@ def _base64_to_ndarray(cls, value):
im_bytes = io.BytesIO(im_bytes)
# convert to numpy RGB value (for moviepy.editor.VideoClip)
return np.array(Image.open(im_bytes))

3 changes: 1 addition & 2 deletions nglview/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ def _relayout(box, form_item_layout):
kid,
], layout=form_item_layout)
else:
box2 = Box([Label(value=label_value), kid],
layout=form_item_layout)
box2 = Box([Label(value=label_value), kid], layout=form_item_layout)
form_items.append(box2)

return form_items
Expand Down
3 changes: 1 addition & 2 deletions nglview/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,4 @@
]

REPRESENTATION_NAMES = list(
sorted({name
for pairs in REPRESENTATION_NAME_PAIRS for name in pairs}))
sorted({name for pairs in REPRESENTATION_NAME_PAIRS for name in pairs}))
1 change: 1 addition & 0 deletions nglview/remote_thread.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@


class RemoteCallThread(threading.Thread):

def __init__(self, view, timeout=0.1, registered_funcs=['loadFile']):
'''
Expand Down
2 changes: 1 addition & 1 deletion nglview/sandbox/amber.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def _update(event):
self._update_coordinates(traj[0].xyz)

# non-blocking so we can use other Jupyter's cells
self.thread = threading.Thread(target=_update, args=(self.event, ))
self.thread = threading.Thread(target=_update, args=(self.event,))
self.thread.daemon = True
self.thread.start()

Expand Down
2 changes: 2 additions & 0 deletions nglview/sandbox/grid_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@


class GridBoxNGL(GridBox):

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._ngl_class_id = None
Expand All @@ -69,6 +70,7 @@ def fullscreen(self, js_code=None):


class GridBoxViewAndPlayer(GridBoxNGL):

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._view = self.children[0]
Expand Down
Loading

0 comments on commit a3cc1b2

Please sign in to comment.