Skip to content

Commit

Permalink
Update lint (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
hoxbro authored Sep 21, 2023
1 parent b7bd8d7 commit 9e9da08
Show file tree
Hide file tree
Showing 9 changed files with 124 additions and 105 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ repos:
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.285
rev: v0.0.290
hooks:
- id: ruff
args: [holonote]
files: holonote/
- repo: https://github.com/hoxbro/clean_notebook
rev: v0.1.10
rev: v0.1.11
hooks:
- id: clean-notebook
- repo: https://github.com/codespell-project/codespell
Expand Down
98 changes: 50 additions & 48 deletions holonote/annotate/annotator.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ class Indicator:
displayed (vectorized) HoloViews object.
"""

range_style = dict(color='red', alpha=0.4, apply_ranges=False)
range_style = {'color': 'red', 'alpha': 0.4, 'apply_ranges': False}
point_style = {}
indicator_highlight = {'alpha':(0.7,0.2)}

edit_range_style = dict(alpha=0.4, line_alpha=1, line_width=1, line_color='black')
edit_range_style = {'alpha': 0.4, 'line_alpha': 1, 'line_width': 1, 'line_color': 'black'}
edit_point_style = {}

@classmethod
Expand Down Expand Up @@ -66,7 +66,8 @@ def ranges_1d(cls, region_df, field_df, invert_axes=False, extra_params=None):
NOTE: Should use VSpans once available!
"""
if extra_params is None:
raise Exception('Extra parameters required until vectorized HSpans/VSpans supported')
msg = 'Extra parameters required until vectorized HSpans/VSpans supported'
raise Exception(msg)
return cls._range_indicators(region_df, field_df, "1d", invert_axes, extra_params)

@classmethod
Expand Down Expand Up @@ -160,9 +161,11 @@ def normalize_spec(self, input_spec: dict[str, Any]) -> SpecDict:
v = {"type": v, "region": "range"}

if v["region"] not in ["range", "point", "geometry"]:
raise ValueError("Region type must be range, point, or geometry.")
msg = 'Region type must be range, point, or geometry.'
raise ValueError(msg)
if v["region"] == "geometry" and not isinstance(k, tuple):
raise ValueError("Geometry region dimension must be a tuple.")
msg = 'Geometry region dimension must be a tuple.'
raise ValueError(msg)
new_spec[k] = v

return new_spec
Expand Down Expand Up @@ -230,7 +233,8 @@ def _set_regions(self, **items):
# TODO: Validate values based on spec
for dim, values in items.items():
if dim not in self.spec:
raise ValueError(f"Dimension {dim} not in spec")
msg = f'Dimension {dim} not in spec'
raise ValueError(msg)
self._region[dim] = values

def clear_regions(self):
Expand All @@ -240,32 +244,29 @@ def clear_regions(self):
def set_range(self, startx, endx, starty=None, endy=None):
print("set_range is legacy use set_regions instead")
if None in [starty, endy] and ([starty, endy] != [None, None]):
raise ValueError('Both starty and endy need to be non-None')
msg = 'Both starty and endy need to be non-None'
raise ValueError(msg)

value = (startx, endx) if starty is None else (startx, endx, starty, endy)
kdims = list(self.spec)
if len(value) == 2:
if len(kdims) != 1:
raise ValueError('Only one key dimension is allowed in spec.')
msg = 'Only one key dimension is allowed in spec.'
raise ValueError(msg)
if (r := self.spec[kdims[0]]['region']) != 'range':
raise ValueError(
"Only 'range' region allowed for 'set_range', "
f"{kdims[0]!r} is {r!r}."
)
msg = f"Only 'range' region allowed for 'set_range', {kdims[0]!r} is {r!r}."
raise ValueError(msg)
regions = {kdims[0]: value}
elif len(value) == 4:
if len(kdims) != 2:
raise ValueError('Only two key dimensions is allowed in spec.')
msg = 'Only two key dimensions is allowed in spec.'
raise ValueError(msg)
if (r := self.spec[kdims[0]]['region']) != 'range':
raise ValueError(
"Only 'range' region allowed for 'set_range', "
f"{kdims[0]!r} is {r!r}."
)
msg = f"Only 'range' region allowed for 'set_range', {kdims[0]!r} is {r!r}."
raise ValueError(msg)
if (r := self.spec[kdims[1]]['region']) != 'range':
raise ValueError(
"Only 'range' region allowed for 'set_range', "
f"{kdims[1]!r} is {r!r}."
)
msg = f"Only 'range' region allowed for 'set_range', {kdims[1]!r} is {r!r}."
raise ValueError(msg)
regions = {kdims[0]: (value[0], value[1]), kdims[1]: (value[2], value[3])}

self.set_regions(**regions)
Expand All @@ -276,26 +277,22 @@ def set_point(self, posx, posy=None):
kdims = list(self.spec)
if posy is None:
if len(kdims) != 1:
raise ValueError('Only one key dimension is allowed in spec.')
msg = 'Only one key dimension is allowed in spec.'
raise ValueError(msg)
if (r := self.spec[kdims[0]]['region']) != 'point':
raise ValueError(
"Only 'point' region allowed for 'set_point', "
f"{kdims[0]!r} is {r!r}."
)
msg = f"Only 'point' region allowed for 'set_point', {kdims[0]!r} is {r!r}."
raise ValueError(msg)
regions = {kdims[0]: posx}
else:
if len(kdims) != 2:
raise ValueError('Only two key dimensions is allowed in spec.')
msg = 'Only two key dimensions is allowed in spec.'
raise ValueError(msg)
if (r := self.spec[kdims[0]]['region']) != 'point':
raise ValueError(
"Only 'point' region allowed for 'set_point', "
f"{kdims[0]!r} is {r!r}."
)
msg = f"Only 'point' region allowed for 'set_point', {kdims[0]!r} is {r!r}."
raise ValueError(msg)
if (r := self.spec[kdims[1]]['region']) != 'point':
raise ValueError(
"Only 'point' region allowed for 'set_point', "
f"{kdims[1]!r} is {r!r}."
)
msg = f"Only 'point' region allowed for 'set_point', {kdims[1]!r} is {r!r}."
raise ValueError(msg)
regions = {kdims[0]: posx, kdims[1]: posy}

self.set_regions(**regions)
Expand All @@ -310,8 +307,8 @@ def _add_annotation(self, **fields):
# Don't do anything if self.region is an empty dict
if self.region and self.region != self._last_region:
if len(self.annotation_table._annotators)>1:
raise AssertionError('Multiple annotation instances attached to the connector: '
'Call add_annotation directly from the associated connector.')
msg = 'Multiple annotation instances attached to the connector: Call add_annotation directly from the associated connector.'
raise AssertionError(msg)
self.annotation_table.add_annotation(self._region, spec=self.spec, **fields)
self._last_region = self._region.copy()

Expand All @@ -330,7 +327,8 @@ def delete_annotation(self, index):
try:
self.annotation_table.delete_annotation(index)
except KeyError:
raise ValueError(f"Annotation with index {index!r} does not exist.") from None
msg = f'Annotation with index {index!r} does not exist.'
raise ValueError(msg) from None

if index in self.selected_indices:
self.selected_indices.remove(index)
Expand Down Expand Up @@ -375,7 +373,7 @@ def define_fields(self, fields_df, preserve_index=False):
print("define_fields is legacy use define_annotations instead")
if not preserve_index:
indices = [self.connector.primary_key(self.connector) for el in range(len(fields_df))]
index_mapping = {old:new for old, new in zip(fields_df.index, indices)}
index_mapping = dict(zip(fields_df.index, indices))
fields_df = fields_df.set_index(pd.Series(indices,
name=self.connector.primary_key.field_name))
else:
Expand All @@ -385,14 +383,16 @@ def define_fields(self, fields_df, preserve_index=False):
def define_ranges(self, startx, endx, starty=None, endy=None, dims=None):
print("define_ranges is legacy use define_annotations instead")
if dims is None:
raise ValueError('Please specify dimension annotated by defined ranges')
msg = 'Please specify dimension annotated by defined ranges'
raise ValueError(msg)

self.annotation_table.define_ranges(dims, startx, endx, starty, endy)

def define_points(self, posx, posy=None, dims=None):
print("define_points is legacy use define_annotations instead")
if dims is None:
raise ValueError('Please specify dimension annotated by defined ranges')
msg = 'Please specify dimension annotated by defined ranges'
raise ValueError(msg)
self.annotation_table.define_points(dims, posx, posy=posy)


Expand Down Expand Up @@ -473,7 +473,8 @@ def edit_tools(self)-> list[Tool]:
@classmethod
def _infer_kdim_dtypes(cls, element):
if not isinstance(element, hv.Element):
raise ValueError('Supplied object {element} is not a bare HoloViews Element')
msg = 'Supplied object {element} is not a bare HoloViews Element'
raise ValueError(msg)
kdim_dtypes = {}
for kdim in element.dimensions(selection='key'):
kdim_dtypes[str(kdim)] = type(element.dimension_values(kdim)[0])
Expand Down Expand Up @@ -522,9 +523,7 @@ def _filter_stream_values(self, bounds, x, y, geometry):
bounds = None

# If selection enabled, tap stream used for selection not for creating point regions
if 'point' in self.region_types and self.selection_enabled:
x, y = None, None
elif 'point' not in self.region_types:
if ('point' in self.region_types and self.selection_enabled) or 'point' not in self.region_types:
x, y = None, None

return bounds, x, y, geometry
Expand Down Expand Up @@ -559,7 +558,8 @@ def inner(bounds, x, y, geometry):
elif len(kdims) == 2:
self.annotator._set_regions(**{kdims[0]: x, kdims[1]: y})
else:
raise ValueError('Only 1d and 2d supported for Points')
msg = 'Only 1d and 2d supported for Points'
raise ValueError(msg)

return region_element

Expand Down Expand Up @@ -774,7 +774,8 @@ def _infer_kdim_dtypes(self, element: hv.Element) -> dict:
def _create_annotation_element(self, element_key: tuple[str, ...]) -> AnnotationDisplay:
for key in element_key:
if key not in self.spec:
raise ValueError(f"Dimension {key!r} not in spec")
msg = f'Dimension {key!r} not in spec'
raise ValueError(msg)
return AnnotationDisplay(self, kdims=list(element_key))

def get_element(self, kdims: tuple[str, ...] | str) -> AnnotationDisplay:
Expand Down Expand Up @@ -828,7 +829,8 @@ def delete_annotation(self, index):

def delete_annotations(self, *indices):
if not indices:
raise ValueError('At least one index must be specified to delete annotations')
msg = 'At least one index must be specified to delete annotations'
raise ValueError(msg)
for index in indices:
super().delete_annotation(index)
self.refresh()
Expand Down
7 changes: 4 additions & 3 deletions holonote/annotate/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ class Connector(param.Parameterized):
@classmethod
def field_value_to_type(cls, value):
if isinstance(value, list):
assert all([isinstance(el, str) for el in value]), 'Only string enums supported'
assert all(isinstance(el, str) for el in value), 'Only string enums supported'
return str
elif hasattr(value, 'dtype'):
return value.dtype
Expand All @@ -183,7 +183,8 @@ def field_value_to_type(cls, value):
elif isinstance(value, param.Parameter) and value.default is not None:
return type(value.default)
else:
raise Exception(f'Connector cannot handle type {type(value)!s}')
msg = f'Connector cannot handle type {type(value)!s}'
raise TypeError(msg)

@classmethod
def schema_from_field_values(cls, fields):
Expand Down Expand Up @@ -355,7 +356,7 @@ def delete_row(self, id_val):
def update_row(self, **updates): # updates as a dictionary OR remove posarg?
assert self.primary_key.field_name in updates
id_val = updates.pop(self.primary_key.field_name)
set_updates = ', '.join('\"' + k + '\"' + " = ?" for k in updates.keys())
set_updates = ', '.join('\"' + k + '\"' + " = ?" for k in updates)
query = f"UPDATE {self.table_name} SET " + set_updates + f" WHERE \"{self.primary_key.field_name}\" = ?;"
self.cursor.execute(query, [*updates.values(), id_val])
self.con.commit()
Expand Down
Loading

0 comments on commit 9e9da08

Please sign in to comment.