Skip to content

:format: format with black, lint with ruff #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions .github/workflows/cdci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ on:
types: [published]

jobs:
# format:
# runs-on: ubuntu-latest
# steps:
# - uses: actions/checkout@v4
# - uses: psf/black@stable
format:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: psf/black@stable
# lint:
# name: Lint with ruff
# runs-on: ubuntu-latest
Expand Down Expand Up @@ -51,7 +51,6 @@ jobs:
pip install -e .
# - name: Run tests
# run: python -m pytest tests



publish:
Expand Down
215 changes: 135 additions & 80 deletions src/vuecore/Dendrogram.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,19 @@
from collections import OrderedDict
import plotly.graph_objs as go

def plot_dendrogram(Z_dendrogram, cutoff_line=True, value=15, orientation='bottom', hang=30, hide_labels=False, labels=None,
colorscale=None, hovertext=None, color_threshold=None):

def plot_dendrogram(
Z_dendrogram,
cutoff_line=True,
value=15,
orientation="bottom",
hang=30,
hide_labels=False,
labels=None,
colorscale=None,
hovertext=None,
color_threshold=None,
):
"""
Modified version of Plotly _dendrogram.py that returns a dendrogram Plotly figure object with cutoff line.

Expand Down Expand Up @@ -36,25 +47,59 @@ def plot_dendrogram(Z_dendrogram, cutoff_line=True, value=15, orientation='botto
figure = plot_dendrogram(dendro_tree, hang=0.9, cutoff_line=False)
"""

dendrogram = Dendrogram(Z_dendrogram, orientation, hang, hide_labels, labels, colorscale, hovertext=hovertext, color_threshold=color_threshold)
dendrogram = Dendrogram(
Z_dendrogram,
orientation,
hang,
hide_labels,
labels,
colorscale,
hovertext=hovertext,
color_threshold=color_threshold,
)

if cutoff_line == True:
dendrogram.layout.update({'shapes':[{'type':'line',
'xref':'paper',
'yref':'y',
'x0':0, 'y0':value,
'x1':1, 'y1':value,
'line':{'color':'red'}}]})
dendrogram.layout.update(
{
"shapes": [
{
"type": "line",
"xref": "paper",
"yref": "y",
"x0": 0,
"y0": value,
"x1": 1,
"y1": value,
"line": {"color": "red"},
}
]
}
)

figure = dict(data=dendrogram.data, layout=dendrogram.layout)
figure['layout']['template'] = 'plotly_white'
figure["layout"]["template"] = "plotly_white"

return figure


class Dendrogram(object):
"""Refer to plot_dendrogram() for docstring."""
def __init__(self, Z_dendrogram, orientation='bottom', hang=1, hide_labels=False, labels=None, colorscale=None, hovertext=None,
color_threshold=None, width=np.inf, height=np.inf, xaxis='xaxis', yaxis='yaxis'):

def __init__(
self,
Z_dendrogram,
orientation="bottom",
hang=1,
hide_labels=False,
labels=None,
colorscale=None,
hovertext=None,
color_threshold=None,
width=np.inf,
height=np.inf,
xaxis="xaxis",
yaxis="yaxis",
):
self.orientation = orientation
self.labels = labels
self.xaxis = xaxis
Expand All @@ -64,20 +109,19 @@ def __init__(self, Z_dendrogram, orientation='bottom', hang=1, hide_labels=False
self.sign = {self.xaxis: 1, self.yaxis: 1}
self.layout = {self.xaxis: {}, self.yaxis: {}}

if self.orientation in ['left', 'bottom']:
if self.orientation in ["left", "bottom"]:
self.sign[self.xaxis] = 1
else:
self.sign[self.xaxis] = -1

if self.orientation in ['right', 'bottom']:
if self.orientation in ["right", "bottom"]:
self.sign[self.yaxis] = 1
else:
self.sign[self.yaxis] = -1

(dd_traces, xvals, yvals,
ordered_labels, leaves) = self.get_dendrogram_traces(Z_dendrogram, hang, colorscale,
hovertext,
color_threshold)
(dd_traces, xvals, yvals, ordered_labels, leaves) = self.get_dendrogram_traces(
Z_dendrogram, hang, colorscale, hovertext, color_threshold
)

self.labels = ordered_labels
self.leaves = leaves
Expand All @@ -93,9 +137,9 @@ def __init__(self, Z_dendrogram, orientation='bottom', hang=1, hide_labels=False
if len(self.zero_vals) > len(yvals) + 1:
l_border = int(min(self.zero_vals))
r_border = int(max(self.zero_vals))
correct_leaves_pos = range(l_border,
r_border + 1,
int((r_border - l_border) / len(yvals)))
correct_leaves_pos = range(
l_border, r_border + 1, int((r_border - l_border) / len(yvals))
)
self.zero_vals = [v for v in correct_leaves_pos]

self.zero_vals.sort()
Expand All @@ -113,26 +157,29 @@ def get_color_dict(self, colorscale):

# These are the color codes returned for dendrograms
# We're replacing them with nicer colors
d = {'r': 'red',
'g': 'green',
'b': 'blue',
'c': 'cyan',
'm': 'magenta',
'y': 'yellow',
'k': 'black',
'w': 'white'}
d = {
"r": "red",
"g": "green",
"b": "blue",
"c": "cyan",
"m": "magenta",
"y": "yellow",
"k": "black",
"w": "white",
}
default_colors = OrderedDict(sorted(d.items(), key=lambda t: t[0]))

if colorscale is None:
colorscale = [
'rgb(0,116,217)', # blue
'rgb(35,205,205)', # cyan
'rgb(61,153,112)', # green
'rgb(40,35,35)', # black
'rgb(133,20,75)', # magenta
'rgb(255,65,54)', # red
'rgb(255,255,255)', # white
'rgb(255,220,0)'] # yellow
"rgb(0,116,217)", # blue
"rgb(35,205,205)", # cyan
"rgb(61,153,112)", # green
"rgb(40,35,35)", # black
"rgb(133,20,75)", # magenta
"rgb(255,65,54)", # red
"rgb(255,255,255)", # white
"rgb(255,220,0)",
] # yellow

for i in range(len(default_colors.keys())):
k = list(default_colors.keys())[i] # PY3 won't index keys
Expand All @@ -150,32 +197,34 @@ def set_axis_layout(self, axis_key, hide_labels):
:return (dict): An axis_key dictionary with set parameters.
"""
axis_defaults = {
'type': 'linear',
'ticks': 'outside',
'mirror': 'allticks',
'rangemode': 'tozero',
'showticklabels': True,
'zeroline': False,
'showgrid': False,
'showline': True,
}
"type": "linear",
"ticks": "outside",
"mirror": "allticks",
"rangemode": "tozero",
"showticklabels": True,
"zeroline": False,
"showgrid": False,
"showline": True,
}

if len(self.labels) != 0:
axis_key_labels = self.xaxis
if self.orientation in ['left', 'right']:
if self.orientation in ["left", "right"]:
axis_key_labels = self.yaxis
if axis_key_labels not in self.layout:
self.layout[axis_key_labels] = {}
self.layout[axis_key_labels]['tickvals'] = \
[zv*self.sign[axis_key] for zv in self.zero_vals]
self.layout[axis_key_labels]['ticktext'] = self.labels
self.layout[axis_key_labels]['tickmode'] = 'array'
self.layout[axis_key_labels]["tickvals"] = [
zv * self.sign[axis_key] for zv in self.zero_vals
]
self.layout[axis_key_labels]["ticktext"] = self.labels
self.layout[axis_key_labels]["tickmode"] = "array"

self.layout[axis_key].update(axis_defaults)

if hide_labels == True:
self.layout[axis_key].update({'showticklabels': False})
else: pass
self.layout[axis_key].update({"showticklabels": False})
else:
pass

return self.layout[axis_key]

Expand All @@ -191,24 +240,27 @@ def set_figure_layout(self, width, height, hide_labels):
:type hide_labels: boolean
:return: Plotly layout
"""
self.layout.update({
'showlegend': False,
'autosize': False,
'hovermode': 'closest',
'width': width,
'height': height
})
self.layout.update(
{
"showlegend": False,
"autosize": False,
"hovermode": "closest",
"width": width,
"height": height,
}
)

self.set_axis_layout(self.xaxis, hide_labels=hide_labels)
self.set_axis_layout(self.yaxis, hide_labels=False)

return self.layout


def get_dendrogram_traces(self, Z_dendrogram, hang, colorscale, hovertext, color_threshold):
def get_dendrogram_traces(
self, Z_dendrogram, hang, colorscale, hovertext, color_threshold
):
"""
Calculates all the elements needed for plotting a dendrogram.

:param Z_dendrogram: Matrix of observations as array of arrays
:type Z_dendrogram: ndarray
:param hang: dendrogram distance of leaf lines
Expand All @@ -218,28 +270,28 @@ def get_dendrogram_traces(self, Z_dendrogram, hang, colorscale, hovertext, color
:param hovertext: List of hovertext for constituent traces of dendrogram
:type hovertext: list
:return (tuple): Contains all the traces in the following order:

a. trace_list: List of Plotly trace objects for dendrogram tree
b. icoord: All X points of the dendrogram tree as array of arrays with length 4
c. dcoord: All Y points of the dendrogram tree as array of arrays with length 4
d. ordered_labels: leaf labels in the order they are going to appear on the plot
e. Z_dendrogram['leaves']: left-to-right traversal of the leaves
"""
icoord = scp.array(Z_dendrogram['icoord'])
dcoord = scp.array(Z_dendrogram['dcoord'])
ordered_labels = scp.array(Z_dendrogram['ivl'])
color_list = scp.array(Z_dendrogram['color_list'])
icoord = scp.array(Z_dendrogram["icoord"])
dcoord = scp.array(Z_dendrogram["dcoord"])
ordered_labels = scp.array(Z_dendrogram["ivl"])
color_list = scp.array(Z_dendrogram["color_list"])
colors = self.get_color_dict(colorscale)

trace_list = []

for i in range(len(icoord)):
if self.orientation in ['top', 'bottom']:
if self.orientation in ["top", "bottom"]:
xs = icoord[i]
else:
xs = dcoord[i]

if self.orientation in ['top', 'bottom']:
if self.orientation in ["top", "bottom"]:
ys = dcoord[i]
else:
ys = icoord[i]
Expand All @@ -264,28 +316,31 @@ def get_dendrogram_traces(self, Z_dendrogram, hang, colorscale, hovertext, color
y_coord.append(y)

trace = dict(
type='scattergl',
type="scattergl",
x=np.multiply(self.sign[self.xaxis], x_coord),
y=np.multiply(self.sign[self.yaxis], y_coord),
mode='lines',
marker=dict(color='rgb(40,35,35)'),
line=dict(color='rgb(40,35,35)', width=1), #dict(color=colors[color_key]),
mode="lines",
marker=dict(color="rgb(40,35,35)"),
line=dict(
color="rgb(40,35,35)", width=1
), # dict(color=colors[color_key]),
text=hovertext_label,
hoverinfo='text')
hoverinfo="text",
)

try:
x_index = int(self.xaxis[-1])
except ValueError:
x_index = ''
x_index = ""

try:
y_index = int(self.yaxis[-1])
except ValueError:
y_index = ''
y_index = ""

trace['xaxis'] = 'x' + x_index
trace['yaxis'] = 'y' + y_index
trace["xaxis"] = "x" + x_index
trace["yaxis"] = "y" + y_index

trace_list.append(trace)

return trace_list, icoord, dcoord, ordered_labels, Z_dendrogram['leaves']
return trace_list, icoord, dcoord, ordered_labels, Z_dendrogram["leaves"]
Loading
Loading